diff options
author | Robert Godfrey <rgodfrey@apache.org> | 2012-03-10 19:22:10 +0000 |
---|---|---|
committer | Robert Godfrey <rgodfrey@apache.org> | 2012-03-10 19:22:10 +0000 |
commit | 4eaa4e42093e5524d9552d8fa312c214524b6bb4 (patch) | |
tree | a251d57ee92d9c779fe4455c583be0ed90e69a43 /qpid/java/client | |
parent | 92be7e8f3163c048a8642d2deeaa921bbb65dc9c (diff) | |
download | qpid-python-rg-amqp-1-0-sandbox.tar.gz |
NO-JIRA : AMQP-1-0 sandbox updates - merge from trunkrg-amqp-1-0-sandbox
git-svn-id: https://svn.apache.org/repos/asf/qpid/branches/rg-amqp-1-0-sandbox@1299257 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'qpid/java/client')
200 files changed, 2681 insertions, 7832 deletions
diff --git a/qpid/java/client/README.txt b/qpid/java/client/README.txt index b9cde71db3..a8c7da32c5 100644 --- a/qpid/java/client/README.txt +++ b/qpid/java/client/README.txt @@ -47,5 +47,3 @@ Run 'ant build' in the parent directory from where this file is stored, ie: This will build the various Java modules, leaving binary .jar files output in: <installation path>/qpid/java/build/lib -Taking the above the 'distribution directory', consult the README.txt file at: -<installation path>/qpid/java/client/example/src/main/java diff --git a/qpid/java/client/build.xml b/qpid/java/client/build.xml index d52de8dca6..5a72d67b68 100644 --- a/qpid/java/client/build.xml +++ b/qpid/java/client/build.xml @@ -32,14 +32,6 @@ <property name="output.dir" value="${module.precompiled}/org/apache/qpid/filter/selector"/> - <target name="precompile"> - <mkdir dir="${output.dir}"/> - <javacc target="src/main/grammar/SelectorParser.jj" - outputdirectory="${output.dir}" - javacchome="${project.root}/lib"/> - </target> - - <uptodate property="doc-release.done" targetfile="${module.release}/api/index.html"> <srcfiles dir="${module.src}" includes="**/*.java"/> </uptodate> diff --git a/qpid/java/client/example/src/main/java/README.txt b/qpid/java/client/example/src/main/java/README.txt deleted file mode 100644 index 757054e492..0000000000 --- a/qpid/java/client/example/src/main/java/README.txt +++ /dev/null @@ -1,33 +0,0 @@ -In order to use the runSample script, you are required to set two environment -variables, QPID_HOME and QPID_SAMPLE. If not the default values will be used. - -QPID_HOME ---------- -This is the directory that contains the QPID distribution. If you are running the Qpid -Java broker on the same machine as the examples, you have already set QPID_HOME to this -directory. - -default: /usr/share/java/ - -QPID_SAMPLE ------------ - -This is the examples directory, which is the parent directory of the -'java' directory in which you find 'runSample.sh' - -(Ex:- $QPID_SRC_HOME/java/client/example/src/main) - -default: $PWD - -Note: you must have write privileges to this directory in order to run -the examples. - - -Running the Examples -=========================== - -To run these programs, do the following: - - 1. Make sure that a Qpid broker is running. - 2. In the java directory, use runSample.sh to run the program: - $ ./runSample.sh <class name> <arguments>
\ No newline at end of file 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 index b43031ad23..28e1d5a87e 100644 --- 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 @@ -27,8 +27,6 @@ import javax.jms.MessageConsumer; import javax.jms.Session; import org.apache.qpid.client.AMQAnyDestination; -import org.apache.qpid.client.AMQConnection; -import org.slf4j.Logger; public class Drain extends OptionParser { @@ -50,13 +48,13 @@ public class Drain extends OptionParser static { - optDefs.add(BROKER); - optDefs.add(HELP); - optDefs.add(TIMEOUT); - optDefs.add(FOREVER); - optDefs.add(COUNT); - optDefs.add(CON_OPTIONS); - optDefs.add(BROKER_OPTIONS); + 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 @@ -66,7 +64,7 @@ public class Drain extends OptionParser Connection con = createConnection(); con.start(); Session ssn = con.createSession(false,Session.AUTO_ACKNOWLEDGE); - Destination dest = new AMQAnyDestination(address); + Destination dest = new AMQAnyDestination(getAddress()); MessageConsumer consumer = ssn.createConsumer(dest); Message msg; 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 index f4e17c5c4c..6aa12f07fa 100644 --- 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 @@ -68,12 +68,12 @@ public class OptionParser String.class); - protected Map<String,Object> optMap = new HashMap<String,Object>(); - protected static final List<Option> optDefs = new ArrayList<Option>(); + private Map<String,Object> optMap = new HashMap<String,Object>(); + private static final List<Option> optDefs = new ArrayList<Option>(); - protected String usage; - protected String desc; - protected String address; + private String usage; + private String desc; + private String address; public OptionParser(String[] args, String usage, String desc) { @@ -147,8 +147,8 @@ public class OptionParser for (Option option: optDefs) { - if ((op.startsWith("-") && option.shortForm != null && option.shortForm.equals(key)) || - (op.startsWith("--") && option.longForm != null && option.longForm.equals(key)) ) + if ((op.startsWith("-") && option.getShortForm() != null && option.getShortForm().equals(key)) || + (op.startsWith("--") && option.getLongForm() != null && option.getLongForm().equals(key)) ) { match = true; break; @@ -205,7 +205,9 @@ public class OptionParser if (op.startsWith("'")) { if (!op.endsWith("'")) + { throw new IllegalArgumentException(" The option " + op + " needs to be inside quotes"); + } return op.substring(1,op.length() -1); } @@ -217,18 +219,18 @@ public class OptionParser protected boolean containsOp(Option op) { - return optMap.containsKey(op.shortForm) || optMap.containsKey(op.longForm); + return optMap.containsKey(op.getShortForm()) || optMap.containsKey(op.getLongForm()); } protected String getOp(Option op) { - if (optMap.containsKey(op.shortForm)) + if (optMap.containsKey(op.getShortForm())) { - return (String)optMap.get(op.shortForm); + return (String)optMap.get(op.getShortForm()); } - else if (optMap.containsKey(op.longForm)) + else if (optMap.containsKey(op.getLongForm())) { - return (String)optMap.get(op.longForm); + return (String)optMap.get(op.getLongForm()); } else { @@ -281,15 +283,25 @@ public class OptionParser 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 String shortForm; - private String longForm; - private String desc; - private String valueLabel; - private String defaultValue; - private Class type; + 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) 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 index 5da319a658..61ff2dfc19 100644 --- 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 @@ -69,15 +69,15 @@ public class Spout extends OptionParser static { - optDefs.add(BROKER); - optDefs.add(HELP); - optDefs.add(TIMEOUT); - optDefs.add(COUNT); - optDefs.add(MSG_PROPERTY); - optDefs.add(MAP_ENTRY); - optDefs.add(CONTENT); - optDefs.add(CON_OPTIONS); - optDefs.add(BROKER_OPTIONS); + 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 @@ -87,7 +87,7 @@ public class Spout extends OptionParser Connection con = createConnection(); con.start(); Session ssn = con.createSession(false,Session.AUTO_ACKNOWLEDGE); - Destination dest = new AMQAnyDestination(address); + Destination dest = new AMQAnyDestination(getAddress()); MessageProducer producer = ssn.createProducer(dest); int count = Integer.parseInt(getOp(COUNT)); diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageDispatcher.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageDispatcher.java deleted file mode 100644 index 1849f733e9..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageDispatcher.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.example.publisher; - -import java.io.File; - -import javax.jms.JMSException; - - -import org.apache.qpid.example.shared.FileUtils; -import org.apache.qpid.example.shared.Statics; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -/** - * Class that sends message files to the Publisher to distribute - * using files as input - * Must set properties for host in properties file or uses in vm broker - */ -public class FileMessageDispatcher -{ - - protected static final Logger _logger = LoggerFactory.getLogger(FileMessageDispatcher.class); - - protected static Publisher _publisher = null; - - /** - * To use this main method you need to specify a path or file to use for input - * This class then uses file contents from the dir/file specified to generate - * messages to publish - * Intended to be a very simple way to get going with publishing using the broker - * @param args - must specify one value, the path to file(s) for publisher - */ - public static void main(String[] args) - { - - // Check command line args ok - must provide a path or file for us to dispatch - if (args.length == 0) - { - System.out.println("Usage: FileMessageDispatcher <filesToDispatch>" + ""); - } - else - { - try - { - // publish message(s) from file(s) to configured queue - publish(args[0]); - - // Move payload file(s) to archive location as no error - FileUtils.moveFileToNewDir(args[0], System.getProperties().getProperty(Statics.ARCHIVE_PATH)); - } - catch (Exception e) - { - // log error and exit - _logger.error("Error trying to dispatch message: " + e); - System.exit(1); - } - finally - { - // clean up before exiting - if (getPublisher() != null) - { - getPublisher().cleanup(); - } - } - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Finished dispatching message"); - } - - System.exit(0); - } - - /** - * Publish the content of a file or files from a directory as messages - * @param path - from main args - * @throws JMSException - * @throws MessageFactoryException - if cannot create message from file content - */ - public static void publish(String path) throws JMSException, MessageFactoryException - { - File tempFile = new File(path); - if (tempFile.isDirectory()) - { - // while more files in dir publish them - File[] files = tempFile.listFiles(); - - if ((files == null) || (files.length == 0)) - { - _logger.info("FileMessageDispatcher - No files to publish in input directory: " + tempFile); - } - else - { - for (File file : files) - { - // Create message factory passing in payload path - FileMessageFactory factory = new FileMessageFactory(getPublisher().getSession(), file.toString()); - - // Send the message generated from the payload using the _publisher - getPublisher().sendMessage(factory.createEventMessage()); - - } - } - } - else - { - // handle a single file - // Create message factory passing in payload path - FileMessageFactory factory = new FileMessageFactory(getPublisher().getSession(), tempFile.toString()); - - // Send the message generated from the payload using the _publisher - getPublisher().sendMessage(factory.createEventMessage()); - } - } - - /** - * Cleanup before exit - */ - public static void cleanup() - { - if (getPublisher() != null) - { - getPublisher().cleanup(); - } - } - - /** - * @return A Publisher instance - */ - private static Publisher getPublisher() - { - if (_publisher != null) - { - return _publisher; - } - - // Create a _publisher - _publisher = new Publisher(); - - return _publisher; - } - -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageFactory.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageFactory.java deleted file mode 100644 index 04339b2498..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/FileMessageFactory.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.qpid.example.publisher; - -import org.apache.qpid.util.FileUtils; -import org.apache.qpid.example.shared.Statics; - -import java.io.*; -import javax.jms.*; - -public class FileMessageFactory -{ - protected final Session _session; - protected final String _payload; - protected final String _filename; - - /** - * Contructs and instance using a filename from which content will be used to create message - * @param session - * @param filename - * @throws MessageFactoryException - */ - public FileMessageFactory(Session session, String filename) throws MessageFactoryException - { - try - { - _filename = filename; - _payload = FileUtils.readFileAsString(filename); - _session = session; - } - catch (Exception e) - { - MessageFactoryException mfe = new MessageFactoryException(e.toString(), e); - throw mfe; - } - } - - /** - * Creates a text message and sets filename property on it - * The filename property is purely intended to provide visibility - * of file content passing trhough the broker using example classes - * @return Message - a TextMessage with content from file - * @throws JMSException - */ - public Message createEventMessage() throws JMSException - { - TextMessage msg = _session.createTextMessage(); - msg.setText(_payload); - msg.setStringProperty(Statics.FILENAME_PROPERTY, new File(_filename).getName()); - - return msg; - } - - /** - * Creates message from a string for use by the monitor - * @param session - * @param textMsg - message content - * @return Message - TextMessage with content from String - * @throws JMSException - */ - public static Message createSimpleEventMessage(Session session, String textMsg) throws JMSException - { - TextMessage msg = session.createTextMessage(); - msg.setText(textMsg); - - return msg; - } - - public Message createShutdownMessage() throws JMSException - { - return _session.createTextMessage("SHUTDOWN"); - } - - public Message createReportRequestMessage() throws JMSException - { - return _session.createTextMessage("REPORT"); - } - - public Message createReportResponseMessage(String msg) throws JMSException - { - return _session.createTextMessage(msg); - } - - public boolean isShutdown(Message m) - { - return checkText(m, "SHUTDOWN"); - } - - public boolean isReport(Message m) - { - return checkText(m, "REPORT"); - } - - public Object getReport(Message m) - { - try - { - return ((TextMessage) m).getText(); - } - catch (JMSException e) - { - e.printStackTrace(System.out); - - return e.toString(); - } - } - - private static boolean checkText(Message m, String s) - { - try - { - return (m instanceof TextMessage) && ((TextMessage) m).getText().equals(s); - } - catch (JMSException e) - { - e.printStackTrace(System.out); - - return false; - } - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MessageFactoryException.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MessageFactoryException.java deleted file mode 100644 index d709da6432..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MessageFactoryException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.example.publisher; - -public class MessageFactoryException extends Exception -{ - public MessageFactoryException(String msg, Throwable t) - { - super(msg, t); - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorMessageDispatcher.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorMessageDispatcher.java deleted file mode 100644 index 3d16e01af4..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorMessageDispatcher.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.example.publisher; - - -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -import javax.jms.DeliveryMode; -import javax.jms.JMSException; - -/** - * Class that sends heartbeat messages to allow monitoring of message consumption Sends regular (currently 20 seconds - * apart) heartbeat message - */ -public class MonitorMessageDispatcher -{ - - private static final Logger _logger = LoggerFactory.getLogger(MonitorMessageDispatcher.class); - - protected static MonitorPublisher _monitorPublisher = null; - - protected static final String DEFAULT_MONITOR_PUB_NAME = "MonitorPublisher"; - - /** - * Easy entry point for running a message dispatcher for monitoring consumption - * Sends 1000 messages with no delay - * - * @param args - */ - public static void main(String[] args) - { - //Switch on logging appropriately for your app - try - { - int i =0; - while (i < 1000) - { - try - { - //endlessly publish messages to monitor queue - publish(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Dispatched monitor message"); - } - - //sleep for twenty seconds and then publish again - change if appropriate - //Thread.sleep(1000); - i++ ; - } - catch (UndeliveredMessageException a) - { - //trigger application specific failure handling here - _logger.error("Problem delivering monitor message"); - break; - } - } - } - catch (Exception e) - { - _logger.error("Error trying to dispatch AMS monitor message: " + e); - System.exit(1); - } - finally - { - if (getMonitorPublisher() != null) - { - getMonitorPublisher().cleanup(); - } - } - - System.exit(1); - } - - /** - * Publish heartbeat message - * - * @throws JMSException - * @throws UndeliveredMessageException - */ - public static void publish() throws JMSException, UndeliveredMessageException - { - //Send the message generated from the payload using the _publisher -// getMonitorPublisher().sendImmediateMessage -// (FileMessageFactory.createSimpleEventMessage(getMonitorPublisher().getSession(),"monitor:" +System.currentTimeMillis())); - - getMonitorPublisher().sendMessage - (getMonitorPublisher()._session, - FileMessageFactory.createSimpleEventMessage(getMonitorPublisher().getSession(), "monitor:" + System.currentTimeMillis()), - DeliveryMode.PERSISTENT, false, true); - - } - - /** Cleanup publishers */ - public static void cleanup() - { - if (getMonitorPublisher() != null) - { - getMonitorPublisher().cleanup(); - } - - if (getMonitorPublisher() != null) - { - getMonitorPublisher().cleanup(); - } - } - - //Returns a _publisher for the monitor queue - private static MonitorPublisher getMonitorPublisher() - { - if (_monitorPublisher != null) - { - return _monitorPublisher; - } - - //Create a _publisher using failover details and constant for monitor queue - _monitorPublisher = new MonitorPublisher(); - - _monitorPublisher.setName(MonitorMessageDispatcher.DEFAULT_MONITOR_PUB_NAME); - return _monitorPublisher; - } - -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorPublisher.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorPublisher.java deleted file mode 100644 index 750f57d9dc..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MonitorPublisher.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.example.publisher; - -import org.apache.qpid.client.BasicMessageProducer; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -import javax.jms.DeliveryMode; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Session; - -/** - * Subclass of Publisher which uses QPID functionality to send a heartbeat message Note immediate flag not available via - * JMS MessageProducer - */ -public class MonitorPublisher extends Publisher -{ - - private static final Logger _log = LoggerFactory.getLogger(Publisher.class); - - BasicMessageProducer _producer; - - public MonitorPublisher() - { - super(); - } - - /* - * Publishes a message using given details - */ - public boolean sendMessage(Session session, Message message, int deliveryMode, - boolean immediate, boolean commit) throws UndeliveredMessageException - { - try - { - _producer = (BasicMessageProducer) session.createProducer(_destination); - - _producer.send(message, deliveryMode, immediate); - - if (commit) - { - //commit the message send and close the transaction - _session.commit(); - } - - } - catch (JMSException e) - { - //Have to assume our commit failed but do not rollback here as channel closed - _log.error("JMSException", e); - e.printStackTrace(); - throw new UndeliveredMessageException("Cannot deliver immediate message", e); - } - - _log.info(_name + " finished sending message: " + message); - return true; - } - - /* - * Publishes a non-persistent message using transacted session - */ - public boolean sendImmediateMessage(Message message) throws UndeliveredMessageException - { - try - { - _producer = (BasicMessageProducer) _session.createProducer(_destination); - - //Send message via our producer which is not persistent and is immediate - //NB: not available via jms interface MessageProducer - _producer.send(message, DeliveryMode.NON_PERSISTENT, true); - - //commit the message send and close the transaction - _session.commit(); - - } - catch (JMSException e) - { - //Have to assume our commit failed but do not rollback here as channel closed - _log.error("JMSException", e); - e.printStackTrace(); - throw new UndeliveredMessageException("Cannot deliver immediate message", e); - } - - _log.info(_name + " finished sending message: " + message); - return true; - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MultiMessageDispatcher.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MultiMessageDispatcher.java deleted file mode 100644 index a92efe99ac..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/MultiMessageDispatcher.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.example.publisher; - -import java.io.File; - -import javax.jms.JMSException; -import javax.jms.TextMessage; - - -import org.apache.qpid.example.shared.FileUtils; -import org.apache.qpid.example.shared.Statics; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -/** - * Class that sends parameterised number of message files to the Publisher - * Must set properties for host in properties file or uses in vm broker - */ -public class MultiMessageDispatcher -{ - - protected static final Logger _logger = LoggerFactory.getLogger(FileMessageDispatcher.class); - - protected static Publisher _publisher = null; - - /** - * To use this main method you need to specify a path or file to use for input - * This class then uses file contents from the dir/file specified to generate - * messages to publish - * Intended to be a very simple way to get going with publishing using the broker - * @param args - must specify one value, the path to file(s) for publisher - */ - public static void main(String[] args) - { - - // Check command line args ok - must provide a path or file for us to dispatch - if (args.length < 2) - { - System.out.println("Usage: MultiMessageDispatcher <numberOfMessagesToSend> <topic(true|false)>" + ""); - } - else - { - boolean topicPublisher = true; - - try - { - // publish message(s) - topicPublisher = new Boolean(args[1]).booleanValue(); - publish(new Integer(args[0]).intValue(),topicPublisher); - - // Move payload file(s) to archive location as no error - FileUtils.moveFileToNewDir(args[0], System.getProperties().getProperty(Statics.ARCHIVE_PATH)); - } - catch (Exception e) - { - // log error and exit - _logger.error("Error trying to dispatch message: " + e); - System.exit(1); - } - finally - { - - cleanup(topicPublisher); - } - } - - if (_logger.isDebugEnabled()) - { - _logger.debug("Finished dispatching message"); - } - - System.exit(0); - } - - /** - * Publish the content of a file or files from a directory as messages - * @param numMessages - from main args - * @throws javax.jms.JMSException - * @throws org.apache.qpid.example.publisher.MessageFactoryException - if cannot create message from file content - */ - public static void publish(int numMessages, boolean topicPublisher) throws JMSException, MessageFactoryException - { - { - // Send the message generated from the payload using the _publisher - getPublisher(topicPublisher).sendMessage(numMessages); - } - } - - /** - * Cleanup before exit - */ - public static void cleanup(boolean topicPublisher) - { - if (getPublisher(topicPublisher) != null) - { - getPublisher(topicPublisher).cleanup(); - } - } - - /** - * @return A Publisher instance - */ - private static Publisher getPublisher(boolean topic) - { - if (_publisher != null) - { - return _publisher; - } - - if (!topic) - { - // Create a _publisher - _publisher = new Publisher(); - } - else - { - _publisher = new TopicPublisher(); - } - return _publisher; - } - -}
\ No newline at end of file diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/Publisher.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/Publisher.java deleted file mode 100644 index b5f44557a4..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/Publisher.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.example.publisher; - -import org.apache.qpid.client.AMQConnectionFactory; - -import javax.jms.*; - -import javax.naming.InitialContext; - -import org.apache.qpid.example.shared.InitialContextHelper; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -public class Publisher -{ - private static final Logger _log = LoggerFactory.getLogger(Publisher.class); - - protected InitialContextHelper _contextHelper; - - protected Connection _connection; - - protected Session _session; - - protected MessageProducer _producer; - - protected String _destinationDir; - - protected String _name = "Publisher"; - - protected Destination _destination; - - protected static final String _defaultDestinationDir = "/tmp"; - - /** - * Creates a Publisher instance using properties from example.properties - * See InitialContextHelper for details of how context etc created - */ - public Publisher() - { - try - { - //get an initial context from default properties - _contextHelper = new InitialContextHelper(null); - InitialContext ctx = _contextHelper.getInitialContext(); - - //then create a connection using the AMQConnectionFactory - AMQConnectionFactory cf = (AMQConnectionFactory) ctx.lookup("local"); - _connection = cf.createConnection(); - - _connection.setExceptionListener(new ExceptionListener() - { - public void onException(JMSException jmse) - { - // The connection may have broken invoke reconnect code if available. - // The connection may have broken invoke reconnect code if available. - System.err.println("ExceptionListener caught: " + jmse); - //System.exit(0); - } - }); - - //create a transactional session - _session = _connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - - //lookup the example queue and use it - //Queue is non-exclusive and not deleted when last consumer detaches - _destination = (Queue) ctx.lookup("MyQueue"); - - //create a message producer - _producer = _session.createProducer(_destination); - - //set destination dir for files that have been processed - _destinationDir = _defaultDestinationDir; - - _connection.start(); - } - catch (Exception e) - { - e.printStackTrace(); - _log.error("Exception", e); - } - } - - /** - * Creates and sends the number of messages specified in the param - */ - public void sendMessage(int numMessages) - { - try - { - TextMessage txtMessage = _session.createTextMessage("msg"); - for (int i=0;i<numMessages;i++) - { - sendMessage(txtMessage); - _log.info("Sent: " + i); - } - } - catch (JMSException j) - { - _log.error("Exception in sendMessage" + j); - } - - - } - - /** - * Publishes a non-persistent message using transacted session - * Note that persistent is the default mode for send - so need to specify for transient - */ - public boolean sendMessage(Message message) - { - try - { - //Send message via our producer which is not persistent - _producer.send(message, DeliveryMode.PERSISTENT, _producer.getPriority(), _producer.getTimeToLive()); - - //commit the message send and close the transaction - _session.commit(); - - } - catch (JMSException e) - { - //Have to assume our commit failed and rollback here - try - { - _session.rollback(); - _log.error("JMSException", e); - e.printStackTrace(); - return false; - } - catch (JMSException j) - { - _log.error("Unable to rollback publish transaction ",e); - return false; - } - } - - //_log.info(_name + " finished sending message: " + message); - return true; - } - - /** - * Cleanup resources before exit - */ - public void cleanup() - { - try - { - if (_connection != null) - { - _connection.stop(); - _connection.close(); - } - _connection = null; - _producer = null; - } - catch(Exception e) - { - _log.error("Error trying to cleanup publisher " + e); - System.exit(1); - } - } - - /** - * Exposes session - * @return Session - */ - public Session getSession() - { - return _session; - } - - public String getDestinationDir() - { - return _destinationDir; - } - - public void setDestinationDir(String destinationDir) - { - _destinationDir = destinationDir; - } - - public String getName() - { - return _name; - } - - public void setName(String _name) { - this._name = _name; - } -} - diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/TopicPublisher.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/TopicPublisher.java deleted file mode 100644 index 8645e41101..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/TopicPublisher.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.example.publisher; - -import org.apache.qpid.client.BasicMessageProducer; -import org.apache.qpid.example.shared.InitialContextHelper; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -import javax.jms.*; -import javax.naming.InitialContext; - -/** - * Subclass of Publisher which sends messages to a topic destination defined in example.properties - */ -public class TopicPublisher extends Publisher -{ - - private static final Logger _log = LoggerFactory.getLogger(Publisher.class); - - public TopicPublisher() - { - super(); - - try - { - _contextHelper = new InitialContextHelper(null); - InitialContext ctx = _contextHelper.getInitialContext(); - - //lookup the example topic and use it - _destination = (Topic) ctx.lookup("MyTopic"); - - //create a message producer - _producer = _session.createProducer(_destination); - } - catch (Exception e) - { - //argh - _log.error("Exception trying to construct TopicPublisher" + e); - } - - } -}
\ No newline at end of file diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/UndeliveredMessageException.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/UndeliveredMessageException.java deleted file mode 100644 index 245008b68a..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/publisher/UndeliveredMessageException.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.example.publisher; - -/** - * Exception thrown by monitor when cannot send a message marked for immediate delivery - */ -public class UndeliveredMessageException extends Exception -{ - public UndeliveredMessageException(String msg, Throwable t) - { - super(msg, t); - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Client.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Client.java deleted file mode 100644 index e32ee0ba73..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Client.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.example.pubsub; - -import javax.jms.Connection; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Session; -import javax.naming.NamingException; - -/** - * An abstract base class that wraps up the creation of a JMS client utilising JNDI - */ -public abstract class Client -{ - protected ConnectionSetup _setup; - - protected Connection _connection; - protected Destination _destination; - protected Session _session; - - public Client(String destination) - { - if (destination == null) - { - destination = ConnectionSetup.TOPIC_JNDI_NAME; - } - - try - { - _setup = new ConnectionSetup(); - } - catch (NamingException e) - { - //ignore - } - - if (_setup != null) - { - try - { - _connection = _setup.getConnectionFactory().createConnection(); - _destination = _setup.getDestination(destination); - } - catch (JMSException e) - { - System.err.println(e.getMessage()); - } - } - } - - public abstract void start(); - -}
\ No newline at end of file diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/ConnectionSetup.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/ConnectionSetup.java deleted file mode 100644 index 0734704e59..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/ConnectionSetup.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.example.pubsub; - -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import java.util.Properties; - -/** - * This ConnectionSetup is a wrapper around JNDI it creates a number of entries. - * - * It is equivalent to a PropertyFile of value: - * - * connectionfactory.local=amqp://guest:guest@clientid/test?brokerlist='localhost' - * - * queue.queue=example.MyQueue - * topic.topic=example.hierarical.topic - * - */ -public class ConnectionSetup -{ - final static String INITIAL_CONTEXT_FACTORY = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"; - - final static String CONNECTION_JNDI_NAME = "local"; - final static String CONNECTION_NAME = "amqp://guest:guest@clientid/test?brokerlist='localhost'"; - - public static final String QUEUE_JNDI_NAME = "queue"; - final static String QUEUE_NAME = "example.MyQueue"; - - public static final String TOPIC_JNDI_NAME = "topic"; - final static String TOPIC_NAME = "usa.news"; - - private Context _ctx; - - public ConnectionSetup() throws NamingException - { - - // Set the properties ... - Properties properties = new Properties(); - properties.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); - properties.put("connectionfactory." + CONNECTION_JNDI_NAME, CONNECTION_NAME); - - properties.put("queue." + QUEUE_JNDI_NAME, QUEUE_NAME); - properties.put("topic." + TOPIC_JNDI_NAME, TOPIC_NAME); - // Create the initial context - _ctx = new InitialContext(properties); - - } - - public ConnectionSetup(Properties properties) throws NamingException - { - _ctx = new InitialContext(properties); - } - - public ConnectionFactory getConnectionFactory() - { - - // Perform the lookups - try - { - return (ConnectionFactory) _ctx.lookup(CONNECTION_JNDI_NAME); - } - catch (NamingException e) - { - //ignore - } - return null; - } - - public Destination getDestination(String jndiName) - { - // Perform the lookups - try - { - return (Destination) _ctx.lookup(jndiName); - } - catch (ClassCastException cce) - { - //ignore - } - catch (NamingException ne) - { - //ignore - } - return null; - } - - - public void close() - { - try - { - _ctx.close(); - } - catch (NamingException e) - { - //ignore - } - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Publisher.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Publisher.java deleted file mode 100644 index ac3829d49e..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Publisher.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.example.pubsub; - -import javax.jms.JMSException; -import javax.jms.MessageProducer; -import javax.jms.Session; - -/** - * A simple Publisher example. - * - * The class can take two arguments. - * java Publisher <destination> <msgCount> - * Where: - * destination is either 'topic' or 'queue' (Default: topic) - * msgCount is the number of messages to send (Default : 100) - * - */ -public class Publisher extends Client -{ - int _msgCount; - - public Publisher(String destination, int msgCount) - { - super(destination); - _msgCount = msgCount; - } - - public void start() - { - try - { - _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - MessageProducer _producer = _session.createProducer(_destination); - - for (int msgCount = 0; msgCount < _msgCount; msgCount++) - { - _producer.send(_session.createTextMessage("msg:" + msgCount)); - System.out.println("Sent:" + msgCount); - } - - System.out.println("Done."); - _connection.close(); - } - catch (JMSException e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } - - - public static void main(String[] args) - { - - String destination = args.length > 2 ? args[1] : "usa.news"; - - int msgCount = args.length > 2 ? Integer.parseInt(args[2]) : 100; - - new Publisher(destination, msgCount).start(); - } - -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Subscriber.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Subscriber.java deleted file mode 100644 index f2d736701f..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/pubsub/Subscriber.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.example.pubsub; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageListener; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.jms.Topic; -import java.util.concurrent.CountDownLatch; - - -/** - * Simple client that listens for the specified number of msgs on the given Destinaton - * - * The class can take two arguments. - * java Subscriber <destination> <msgCount> - * Where: - * destination is either 'topic' or 'queue' (Default: topic) - * msgCount is the number of messages to send (Default : 100) - */ -public class Subscriber extends Client implements MessageListener -{ - - CountDownLatch _count; - - public Subscriber(String destination, int msgCount) - { - super(destination); - _count = new CountDownLatch(msgCount); - } - - - public void start() - { - try - { - _session = _connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - _session.createDurableSubscriber((Topic) _setup.getDestination(ConnectionSetup.TOPIC_JNDI_NAME), - "exampleClient").setMessageListener(this); - _connection.start(); - _count.await(); - - System.out.println("Done"); - - _connection.close(); - } - catch (JMSException e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - catch (InterruptedException e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } - - public static void main(String[] args) - { - String destination = args.length > 2 ? args[1] : null; - int msgCount = args.length > 2 ? Integer.parseInt(args[2]) : 100; - - new Subscriber(destination, msgCount).start(); - } - - public void onMessage(Message message) - { - try - { - _count.countDown(); - System.out.println("Received msg:" + ((TextMessage) message).getText()); - } - catch (JMSException e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/ConnectionException.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/ConnectionException.java deleted file mode 100644 index 1a3d596a24..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/ConnectionException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.example.shared; - -public class ConnectionException extends Exception -{ - public ConnectionException(String msg, Throwable t) - { - super(msg, t); - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/ContextException.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/ContextException.java deleted file mode 100644 index 2987a9559b..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/ContextException.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.example.shared; - -public class ContextException extends Exception -{ - public ContextException(String msg, Throwable t) - { - super(msg, t); - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/FileUtils.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/FileUtils.java deleted file mode 100644 index 54446cb6a7..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/FileUtils.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.example.shared; - -import java.io.*; - -/** - * Class that provides file related utility methods for utility use - */ -public class FileUtils { - - - //Reads file content into String - public static String getFileContent(String filePath) throws IOException - { - - BufferedReader reader = null; - String tempData = ""; - String eol = "\n\r"; - - try - { - String line; - reader = new BufferedReader(new FileReader(filePath)); - while ((line = reader.readLine()) != null) - { - if (!tempData.equals("")) - { - tempData = tempData + eol + line; - } - else - { - tempData = line; - } - } - } - finally - { - if (reader != null) - { - reader.close(); - } - } - return tempData; - } - - /* - * Reads xml from a file and returns it as an array of chars - */ - public static char[] getFileAsCharArray(String filePath) throws IOException - { - BufferedReader reader = null; - char[] tempChars = null; - String tempData = ""; - - try - { - String line; - reader = new BufferedReader(new FileReader(filePath)); - while ((line = reader.readLine()) != null) - { - tempData = tempData + line; - } - tempChars = tempData.toCharArray(); - } - finally - { - if (reader != null) - { - reader.close(); - } - } - return tempChars; - } - - /* - * Write String content to filename provided - */ - public static void writeStringToFile(String content, String path) throws IOException - { - - BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path))); - writer.write(content); - writer.flush(); - writer.close(); - } - - /* - * Allows moving of files to a new dir and preserves the last bit of the name only - */ - public static void moveFileToNewDir(String path, String newDir) throws IOException - { - //get file name from current path - //while more files in dir publish them - File pathFile = new File(path); - if (pathFile.isDirectory()) - { - File[] files = pathFile.listFiles(); - for (File file : files) - { - moveFileToNewDir(file,newDir); - } - } - } - - /* - * Allows moving of a file to a new dir and preserves the last bit of the name only - */ - public static void moveFileToNewDir(File fileToMove, String newDir) throws IOException - { - moveFile(fileToMove,getArchiveFileName(fileToMove,newDir)); - } - - /* - * Moves file from a given path to a new path with String params - */ - public static void moveFile(String fromPath, String dest) throws IOException - { - moveFile(new File(fromPath),new File(dest)); - } - - /* - * Moves file from a given path to a new path with mixed params - */ - public static void moveFile(File fileToMove, String dest) throws IOException - { - moveFile(fileToMove,new File(dest)); - } - - /* - * Moves file from a given path to a new path with File params - */ - public static void moveFile(File fileToMove, File dest) throws IOException - { - fileToMove.renameTo(dest); - } - - /* - * Deletes a given file - */ - public static void deleteFile(String filePath) throws IOException - { - new File(filePath).delete(); - } - - private static String getArchiveFileName(File fileToMove, String archiveDir) - { - //get file name from current path - String fileName = fileToMove.getName(); - return archiveDir + File.separator + fileName; - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/InitialContextHelper.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/InitialContextHelper.java deleted file mode 100644 index 16a185133a..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/InitialContextHelper.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.example.shared; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -import javax.naming.InitialContext; -import javax.naming.NamingException; - -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -/** - * Class that provides helper methods for JNDI - */ -public class InitialContextHelper -{ - - public static final String _defaultPropertiesName = "example.properties"; - protected Properties _fileProperties; - protected InitialContext _initialContext; - protected static final Logger _log = LoggerFactory.getLogger(InitialContextHelper.class); - - public InitialContextHelper(String propertiesName) throws ContextException - { - try - { - if ((propertiesName == null) || (propertiesName.length() == 0)) - { - propertiesName = _defaultPropertiesName; - } - - _fileProperties = new Properties(); - ClassLoader cl = this.getClass().getClassLoader(); - - // NB: Need to change path to reflect package if moving classes around ! - InputStream is = cl.getResourceAsStream("org/apache/qpid/example/shared/" + propertiesName); - _fileProperties.load(is); - _initialContext = new InitialContext(_fileProperties); - } - catch (IOException e) - { - throw new ContextException(e.toString(), e); - } - catch (NamingException n) - { - throw new ContextException(n.toString(), n); - } - } - - public Properties getFileProperties() - { - return _fileProperties; - } - - public InitialContext getInitialContext() - { - return _initialContext; - } - -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/Statics.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/Statics.java deleted file mode 100644 index c056f8a7da..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/Statics.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.example.shared; - -/** - * Constants used by AMS Publisher/Subscriber classes - */ -public class Statics { - - public static final String TOPIC_NAME = "EXAMPLE_TOPIC"; - - public static final String QUEUE_NAME = "EXAMPLE_QUEUE"; - - public static final String MONITOR_QUEUE_SUFFIX = "_MONITOR"; - - public static final String HOST_PROPERTY = "host"; - - public static final String PORT_PROPERTY = "port"; - - public static final String USER_PROPERTY = "user"; - - public static final String PWD_PROPERTY = "pwd"; - - public static final String TOPIC_PROPERTY = "topic"; - - public static final String QUEUE_PROPERTY = "queue"; - - public static final String VIRTUAL_PATH_PROPERTY = "virtualpath"; - - public static final String ARCHIVE_PATH = "archivepath"; - - public static final String CLIENT_PROPERTY = "client"; - - public static final String FILENAME_PROPERTY = "filename"; - - public static final String DEFAULT_USER = "guest"; - - public static final String DEFAULT_PWD = "guest"; - - -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/example.properties b/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/example.properties deleted file mode 100644 index c76acbd8b9..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/shared/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.PropertiesFileInitialContextFactory - -# use the following property to configure the default connector -#java.naming.provider.url - ignored. - -# register some connection factories -# connectionfactory.[jndiname] = [ConnectionURL] -connectionfactory.local = amqp://guest:guest@clientid/test?brokerlist='tcp://localhost:5672' - -# 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 -topic.MyTopic = example.MyTopic - -# Register an AMQP destination in JNDI -# NOTE: Qpid currently only supports direct,topics and headers -# destination.[jniName] = [BindingURL] -destination.direct = direct://amq.direct//directQueue diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Client.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Client.java deleted file mode 100644 index 8a0ff88448..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Client.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.simple.reqresp; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; - -public class Client implements MessageListener -{ - final String BROKER = "localhost"; - - final String INITIAL_CONTEXT_FACTORY = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"; - - final String CONNECTION_JNDI_NAME = "local"; - final String CONNECTION_NAME = "amqp://guest:guest@clientid/test?brokerlist='" + BROKER + "'"; - - final String QUEUE_JNDI_NAME = "queue"; - final String QUEUE_NAME = "example.RequestQueue"; - - - private InitialContext _ctx; - - private CountDownLatch _shutdownHook = new CountDownLatch(1); - - public Client() - { - setupJNDI(); - - Connection connection; - Session session; - Destination responseQueue; - - //Setup the connection. Create producer to sent message and consumer to receive the repsonse. - MessageProducer _producer; - try - { - connection = ((ConnectionFactory) lookupJNDI(CONNECTION_JNDI_NAME)).createConnection(); - - session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Destination requestQueue = (Queue) lookupJNDI(QUEUE_JNDI_NAME); - - closeJNDI(); - - //Setup a message _producer to send message to the queue the server is consuming from - _producer = session.createProducer(requestQueue); - - //Create a temporary queue that this client will listen for responses on then create a consumer - //that consumes message from this temporary queue. - responseQueue = session.createTemporaryQueue(); - - MessageConsumer responseConsumer = session.createConsumer(responseQueue); - - //Set a listener to asynchronously deal with responses. - responseConsumer.setMessageListener(this); - - // Now the connection is setup up start it. - connection.start(); - } - catch (JMSException e) - { - System.err.println("Unable to setup connection, client and producer on broker"); - return; - } - - // Setup the message to send - TextMessage txtMessage; - try - { - //Now create the actual message you want to send - txtMessage = session.createTextMessage("Request Process"); - - //Set the reply to field to the temp queue you created above, this is the queue the server will respond to - txtMessage.setJMSReplyTo(responseQueue); - - //Set a correlation ID so when you get a response you know which sent message the response is for - //If there is never more than one outstanding message to the server then the - //same correlation ID can be used for all the messages...if there is more than one outstanding - //message to the server you would presumably want to associate the correlation ID with this message - - txtMessage.setJMSCorrelationID(txtMessage.getJMSMessageID()); - } - catch (JMSException e) - { - System.err.println("Unable to create message"); - return; - - } - - try - { - _producer.send(txtMessage); - } - catch (JMSException e) - { - //Handle the exception appropriately - } - - try - { - System.out.println("Sent Request Message ID :" + txtMessage.getJMSMessageID()); - } - catch (JMSException e) - { - //Handle exception more appropriately. - } - - //Wait for the return message to arrive - try - { - _shutdownHook.await(); - } - catch (InterruptedException e) - { - // Ignore this as we are quitting anyway. - } - - //Close the connection - try - { - connection.close(); - } - catch (JMSException e) - { - System.err.println("A problem occured while shutting down the connection : " + e); - } - } - - - /** - * Implementation of the Message Listener interface. - * This is where message will be asynchronously delivered. - * - * @param message - */ - public void onMessage(Message message) - { - String messageText; - try - { - if (message instanceof TextMessage) - { - TextMessage textMessage = (TextMessage) message; - messageText = textMessage.getText(); - System.out.println("messageText = " + messageText); - System.out.println("Correlation ID " + message.getJMSCorrelationID()); - - _shutdownHook.countDown(); - } - else - { - System.err.println("Unexpected message delivered"); - } - } - catch (JMSException e) - { - //Handle the exception appropriately - } - } - - /** - * Lookup the specified name in the JNDI Context. - * - * @param name The string name of the object to lookup - * - * @return The object or null if nothing exists for specified name - */ - private Object lookupJNDI(String name) - { - try - { - return _ctx.lookup(name); - } - catch (NamingException e) - { - System.err.println("Error looking up '" + name + "' in JNDI Context:" + e); - } - - return null; - } - - /** - * Setup the JNDI context. - * - * In this case we are simply using a Properties object to store the pairing information. - * - * Further details can be found on the wiki site here: - * - * @see : http://cwiki.apache.org/qpid/how-to-use-jndi.html - */ - private void setupJNDI() - { - // Set the properties ... - Properties properties = new Properties(); - properties.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); - properties.put("connectionfactory." + CONNECTION_JNDI_NAME, CONNECTION_NAME); - properties.put("queue." + QUEUE_JNDI_NAME, QUEUE_NAME); - - // Create the initial context - Context ctx = null; - try - { - _ctx = new InitialContext(properties); - } - catch (NamingException e) - { - System.err.println("Error Setting up JNDI Context:" + e); - } - } - - /** Close the JNDI Context to keep everything happy. */ - private void closeJNDI() - { - try - { - _ctx.close(); - } - catch (NamingException e) - { - System.err.println("Unable to close JNDI Context : " + e); - } - } - - - public static void main(String[] args) - { - new Client(); - } -} - diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Server.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Server.java deleted file mode 100644 index 9c284eee97..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/simple/reqresp/Server.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.simple.reqresp; - -import javax.jms.Connection; -import javax.jms.ConnectionFactory; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.Queue; -import javax.jms.Session; -import javax.jms.TextMessage; -import javax.naming.Context; -import javax.naming.InitialContext; -import javax.naming.NamingException; -import java.util.Properties; -import java.util.concurrent.CountDownLatch; -import java.io.BufferedReader; -import java.io.BufferedInputStream; -import java.io.Reader; -import java.io.InputStreamReader; -import java.io.IOException; - -public class Server implements MessageListener -{ - final String BROKER = "localhost"; - - final String INITIAL_CONTEXT_FACTORY = "org.apache.qpid.jndi.PropertiesFileInitialContextFactory"; - - final String CONNECTION_JNDI_NAME = "local"; - final String CONNECTION_NAME = "amqp://guest:guest@clientid/test?brokerlist='" + BROKER + "'"; - - final String QUEUE_JNDI_NAME = "queue"; - final String QUEUE_NAME = "example.RequestQueue"; - - - private InitialContext _ctx; - private Session _session; - private MessageProducer _replyProducer; - private CountDownLatch _shutdownHook = new CountDownLatch(1); - - public Server() - { - setupJNDI(); - - Connection connection; - try - { - connection = ((ConnectionFactory) lookupJNDI(CONNECTION_JNDI_NAME)).createConnection(); - - _session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); - - Destination requestQueue = (Queue) lookupJNDI(QUEUE_JNDI_NAME); - - closeJNDI(); - - //Setup a message producer to respond to messages from clients, we will get the destination - //to send to from the JMSReplyTo header field from a Message so we MUST set the destination here to null. - this._replyProducer = _session.createProducer(null); - - //Set up a consumer to consume messages off of the request queue - MessageConsumer consumer = _session.createConsumer(requestQueue); - consumer.setMessageListener(this); - - //Now start the connection - connection.start(); - } - catch (JMSException e) - { - //Handle the exception appropriately - System.err.println("JMSException occured setting up server :" + e); - return; - } - - System.out.println("Server process started and waiting for messages."); - - //Wait to process an single message then quit. - while (_shutdownHook.getCount() != 0) - { - try - { - _shutdownHook.await(); - } - catch (InterruptedException e) - { - // Ignore this as we are quitting anyway. - } - } - - //Close the connection - try - { - connection.close(); - } - catch (JMSException e) - { - System.err.println("A problem occured while shutting down the connection : " + e); - } - } - - public void onMessage(Message message) - { - try - { - TextMessage response = this._session.createTextMessage(); - - //Check we have the right message type. - if (message instanceof TextMessage) - { - TextMessage txtMsg = (TextMessage) message; - String messageText = txtMsg.getText(); - - //Perform the request - System.out.println("Received request:" + messageText + " for message :" + message.getJMSMessageID()); - - //Set the response back to the client - response.setText("Response to Request:" + messageText); - } - - //Set the correlation ID from the received message to be the correlation id of the response message - //this lets the client identify which message this is a response to if it has more than - //one outstanding message to the server - response.setJMSCorrelationID(message.getJMSMessageID()); - - try - { - System.out.println("Received message press enter to send response...."); - new BufferedReader(new InputStreamReader(System.in)).readLine(); - } - catch (IOException e) - { - //Error attemptying to pause - } - - //Send the response to the Destination specified by the JMSReplyTo field of the received message. - _replyProducer.send(message.getJMSReplyTo(), response); - } - catch (JMSException e) - { - //Handle the exception appropriately - } - - _shutdownHook.countDown(); - } - - /** - * Lookup the specified name in the JNDI Context. - * - * @param name The string name of the object to lookup - * - * @return The object or null if nothing exists for specified name - */ - private Object lookupJNDI(String name) - { - try - { - return _ctx.lookup(name); - } - catch (NamingException e) - { - System.err.println("Error looking up '" + name + "' in JNDI Context:" + e); - } - - return null; - } - - /** - * Setup the JNDI context. - * - * In this case we are simply using a Properties object to store the pairing information. - * - * Further details can be found on the wiki site here: - * - * @see : http://cwiki.apache.org/qpid/how-to-use-jndi.html - */ - private void setupJNDI() - { - // Set the properties ... - Properties properties = new Properties(); - properties.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY); - properties.put("connectionfactory." + CONNECTION_JNDI_NAME, CONNECTION_NAME); - properties.put("queue." + QUEUE_JNDI_NAME, QUEUE_NAME); - - // Create the initial context - Context ctx = null; - try - { - _ctx = new InitialContext(properties); - } - catch (NamingException e) - { - System.err.println("Error Setting up JNDI Context:" + e); - } - } - - /** Close the JNDI Context to keep everything happy. */ - private void closeJNDI() - { - try - { - _ctx.close(); - } - catch (NamingException e) - { - System.err.println("Unable to close JNDI Context : " + e); - } - } - - - public static void main(String[] args) - { - new Server(); - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriber.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriber.java deleted file mode 100644 index e4eb5ac7f5..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriber.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.example.subscriber; - -import org.apache.qpid.example.shared.Statics; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -import javax.jms.*; -/** - * Subclass of Subscriber which consumes a heartbeat message - */ - -public class MonitoredSubscriber extends Subscriber -{ - protected String _monitorDestinationName; - - private static final Logger _logger = LoggerFactory.getLogger(MonitoredSubscriber.class); - - private MessageConsumer _monitorConsumer; - - public MonitoredSubscriber() - { - super(); - //lookup queue name and append suffix - _monitorDestinationName = _destination.toString() + Statics.MONITOR_QUEUE_SUFFIX; - } - - /** - * MessageListener implementation for this subscriber - */ - public static class MonitorMessageListener implements MessageListener - { - private String _name; - - public MonitorMessageListener(String name) - { - _name = name; - - } - - /** - * Listens for heartbeat messages and acknowledges them - * @param message - */ - public void onMessage(javax.jms.Message message) - { - _logger.info(_name + " monitor got message '" + message + "'"); - - try - { - _logger.debug("Monitor acknowledging recieved message"); - - //Now acknowledge the message to clear it from our queue - message.acknowledge(); - } - catch(JMSException j) - { - _logger.error("Monitor caught JMSException trying to acknowledge message receipt"); - j.printStackTrace(); - } - catch(Exception e) - { - _logger.error("Monitor caught unexpected exception trying to handle message"); - e.printStackTrace(); - } - } - } - - /** - * Subscribes to Queue and attaches additional monitor listener - */ - public void subscribeAndMonitor() - { - try - { - _connection = _connectionFactory.createConnection(); - - //create a transactional session - Session session = _connection.createSession(true, Session.AUTO_ACKNOWLEDGE); - - //Queue is non-exclusive and not deleted when last consumer detaches - Destination destination = session.createQueue(_monitorDestinationName); - - //Create a consumer with a destination of our queue which will use defaults for prefetch etc - _monitorConsumer = session.createConsumer(destination); - - //give the monitor message listener a name of it's own - _monitorConsumer.setMessageListener(new MonitoredSubscriber.MonitorMessageListener - ("MonitorListener " + System.currentTimeMillis())); - - MonitoredSubscriber._logger.info("Starting monitored subscription ..."); - - _connection.start(); - - //and now start ordinary consumption too - subscribe(); - } - catch (Throwable t) - { - _logger.error("Fatal error: " + t); - t.printStackTrace(); - } - } - - /** - * Stop consuming - */ - public void stopMonitor() - { - try - { - _monitorConsumer.close(); - _monitorConsumer = null; - stop(); - } - catch(JMSException j) - { - _logger.error("JMSException trying to Subscriber.stop: " + j.getStackTrace()); - } - } - -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriptionWrapper.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriptionWrapper.java deleted file mode 100644 index 5e78107182..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/MonitoredSubscriptionWrapper.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.example.subscriber; - - -/** - * Allows you to simply start a monitored subscriber - */ -public class MonitoredSubscriptionWrapper { - - private static MonitoredSubscriber _subscriber; - - /** - * Create a monitored subscriber and start it - * @param args - no params required - */ - public static void main(String args[]) - { - _subscriber = new MonitoredSubscriber(); - - _subscriber.subscribe(); - } - - /** - * Stop subscribing now ... - */ - public static void stop() - { - _subscriber.stop(); - } -} diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/Subscriber.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/Subscriber.java deleted file mode 100644 index c36668575f..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/Subscriber.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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.subscriber; - -import org.apache.qpid.client.AMQConnectionFactory; - -import javax.jms.*; -import javax.jms.Connection; -import javax.jms.MessageConsumer; -import javax.jms.Session; -import javax.naming.InitialContext; - -import org.apache.qpid.example.shared.InitialContextHelper; -import org.slf4j.LoggerFactory; -import org.slf4j.Logger; - -/** - * Subscriber which consumes messages from a queue - */ - -public class Subscriber -{ - private static final Logger _log = LoggerFactory.getLogger(Subscriber.class); - - protected Connection _connection; - - protected MessageConsumer _consumer; - - protected InitialContextHelper _contextHelper; - - protected AMQConnectionFactory _connectionFactory; - - protected Destination _destination; - - public Subscriber() - { - try - { - //get an initial context from default properties - _contextHelper = new InitialContextHelper(null); - InitialContext ctx = _contextHelper.getInitialContext(); - - //then create a connection using the AMQConnectionFactory - _connectionFactory = (AMQConnectionFactory) ctx.lookup("local"); - - //lookup queue from context - _destination = (Destination) ctx.lookup("MyQueue"); - - } - catch (Exception e) - { - e.printStackTrace(); - _log.error("Exception", e); - } - } - - /** - * Listener class that handles messages - */ - public static class ExampleMessageListener implements MessageListener - { - private String _name; - - public ExampleMessageListener(String name) - { - _name = name; - } - - /** - * Listens for message callbacks, handles and then acknowledges them - * @param message - the message received - */ - public void onMessage(javax.jms.Message message) - { - _log.info(_name + " got message '" + message + "'"); - - try - { - //NB: Handle your message appropriately for your application here - //do some stuff - - _log.debug("Acknowledging recieved message"); - - //Now acknowledge the message to clear it from our queue - message.acknowledge(); - } - catch(JMSException j) - { - _log.error("JMSException trying to acknowledge message receipt"); - j.printStackTrace(); - } - catch(Exception e) - { - _log.error("Unexpected exception trying to handle message"); - e.printStackTrace(); - } - } - } - - /** - * Subscribes to example Queue and attaches listener - */ - public void subscribe() - { - _log.info("Starting subscription ..."); - - try - { - _connection = _connectionFactory.createConnection(); - - //Non transactional session using client acknowledgement - Session session = _connection.createSession(false, Session.CLIENT_ACKNOWLEDGE); - - //Create a consumer with a destination of our queue which will use defaults for prefetch etc - _consumer = session.createConsumer(_destination); - - //give the message listener a name of it's own - _consumer.setMessageListener(new ExampleMessageListener("MessageListener " + System.currentTimeMillis())); - - _connection.start(); - } - catch (Throwable t) - { - _log.error("Fatal error: " + t); - t.printStackTrace(); - } - - _log.info("Waiting for messages ..."); - - //wait for messages and sleep to survive failover - try - { - while(true) - { - Thread.sleep(Long.MAX_VALUE); - } - } - catch (Exception e) - { - _log.warn("Exception while Subscriber sleeping",e); - } - } - - /** - * Stop consuming and close connection - */ - public void stop() - { - try - { - _consumer.close(); - _consumer = null; - _connection.stop(); - _connection.close(); - } - catch(JMSException j) - { - _log.error("JMSException trying to Subscriber.stop: " + j.getStackTrace()); - } - } - -} - - - - diff --git a/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/SubscriptionWrapper.java b/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/SubscriptionWrapper.java deleted file mode 100644 index f8fbf63037..0000000000 --- a/qpid/java/client/example/src/main/java/org/apache/qpid/example/subscriber/SubscriptionWrapper.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.example.subscriber; - -/** - * Allows you to simply start a subscriber - */ -public class SubscriptionWrapper { - - private static Subscriber _subscriber; - - /** - * Create a subscriber and start it - * @param args - */ - public static void main(String args[]) - { - _subscriber = new Subscriber(); - - _subscriber.subscribe(); - } - - /** - * Stop subscribing now ... - */ - public static void stop() - { - _subscriber.stop(); - } -} diff --git a/qpid/java/client/example/src/main/java/runSample.sh b/qpid/java/client/example/src/main/java/runSample.sh deleted file mode 100755 index 66338556a5..0000000000 --- a/qpid/java/client/example/src/main/java/runSample.sh +++ /dev/null @@ -1,72 +0,0 @@ -#!/bin/bash - -# -# Licensed to the Apache Software Foundation (ASF) under one -# or more contributor license agreements. See the NOTICE file -# distributed with this work for additional information -# regarding copyright ownership. The ASF licenses this file -# to you under the Apache License, Version 2.0 (the -# "License"); you may not use this file except in compliance -# with the License. You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, -# software distributed under the License is distributed on an -# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -# KIND, either express or implied. See the License for the -# specific language governing permissions and limitations -# under the License. -# - - -# Work out the CLASSPATH divider -UNAME=`uname -s` -case $UNAME in - CYGWIN*) - DIVIDER=";" - ;; - *) - DIVIDER=":" -;; -esac - -if test "'x$QPID_HOME'" != "'x'" -then - QPID_HOME=$QPID_HOME -else - QPID_HOME="/usr/share/java/" -fi -echo "Using QPID_HOME: $QPID_HOME" - -if test "'x$QPID_SAMPLE'" != "'x'" -then - QPID_SAMPLE=$QPID_SAMPLE -else - QPID_SAMPLE=$PWD -fi -echo "Using QPID_SAMPLE: $QPID_SAMPLE" - - -# set the CLASSPATH -CLASSPATH=`find "$QPID_HOME" -name '*.jar' | tr '\n' "$DIVIDER"` - - -# compile the samples -javac -cp "$CLASSPATH" -sourcepath "$QPID_SAMPLE" -d . `find $QPID_SAMPLE -name '*.java'` - -# Add output classes to CLASSPATH -CLASSPATH="$CLASSPATH$DIVIDER$." - -# Set VM parameters -QPID_PARAM="$QPID_PARAM -Dlog4j.configuration=file://$PWD/log4j.xml" - - -# Check if the user supplied a sample classname -if test "'x$1'" = "'x'" -then - echo "No sample classname specified" - exit; -else - java -cp $CLASSPATH $QPID_PARAM $* -fi diff --git a/qpid/java/client/src/main/grammar/SelectorParser.jj b/qpid/java/client/src/main/grammar/SelectorParser.jj deleted file mode 100644 index c811128073..0000000000 --- a/qpid/java/client/src/main/grammar/SelectorParser.jj +++ /dev/null @@ -1,609 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - // - // Original File from r450141 of the Apache ActiveMQ project <http://www.activemq.org/site/home.html> - // - -// ---------------------------------------------------------------------------- -// OPTIONS -// ---------------------------------------------------------------------------- -options { - STATIC = false; - UNICODE_INPUT = true; - - // some performance optimizations - OPTIMIZE_TOKEN_MANAGER = true; - ERROR_REPORTING = false; -} - -// ---------------------------------------------------------------------------- -// PARSER -// ---------------------------------------------------------------------------- - -PARSER_BEGIN(SelectorParser) -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package org.apache.qpid.filter.selector; - -import java.io.StringReader; -import java.util.ArrayList; - -import org.apache.qpid.AMQInternalException; -import org.apache.qpid.filter.ArithmeticExpression; -import org.apache.qpid.filter.BooleanExpression; -import org.apache.qpid.filter.ComparisonExpression; -import org.apache.qpid.filter.ConstantExpression; -import org.apache.qpid.filter.Expression; -import org.apache.qpid.filter.LogicExpression; -import org.apache.qpid.filter.PropertyExpression; -import org.apache.qpid.filter.UnaryExpression; - -/** - * JMS Selector Parser generated by JavaCC - * - * Do not edit this .java file directly - it is autogenerated from SelectorParser.jj - */ -public class SelectorParser { - - public SelectorParser() { - this(new StringReader("")); - } - - public BooleanExpression parse(String sql) throws AMQInternalException { - this.ReInit(new StringReader(sql)); - - try { - return this.JmsSelector(); - } - catch (Throwable e) { - throw new AMQInternalException(sql,e); - } - - } - - private BooleanExpression asBooleanExpression(Expression value) throws ParseException { - if (value instanceof BooleanExpression) { - return (BooleanExpression) value; - } - if (value instanceof PropertyExpression) { - return UnaryExpression.createBooleanCast( value ); - } - throw new ParseException("Expression will not result in a boolean value: " + value); - } - - -} - -PARSER_END(SelectorParser) - -// ---------------------------------------------------------------------------- -// Tokens -// ---------------------------------------------------------------------------- - -/* White Space */ -SPECIAL_TOKEN : -{ - " " | "\t" | "\n" | "\r" | "\f" -} - -/* Comments */ -SKIP: -{ - <LINE_COMMENT: "--" (~["\n","\r"])* ("\n"|"\r"|"\r\n") > -} - -SKIP: -{ - <BLOCK_COMMENT: "/*" (~["*"])* "*" ("*" | (~["*","/"] (~["*"])* "*"))* "/"> -} - -/* Reserved Words */ -TOKEN [IGNORE_CASE] : -{ - < NOT : "NOT"> - | < AND : "AND"> - | < OR : "OR"> - | < BETWEEN : "BETWEEN"> - | < LIKE : "LIKE"> - | < ESCAPE : "ESCAPE"> - | < IN : "IN"> - | < IS : "IS"> - | < TRUE : "TRUE" > - | < FALSE : "FALSE" > - | < NULL : "NULL" > -} - -/* Literals */ -TOKEN [IGNORE_CASE] : -{ - - < DECIMAL_LITERAL: ["1"-"9"] (["0"-"9"])* (["l","L"])? > - | < HEX_LITERAL: "0" ["x","X"] (["0"-"9","a"-"f","A"-"F"])+ > - | < OCTAL_LITERAL: "0" (["0"-"7"])* > - | < FLOATING_POINT_LITERAL: - (["0"-"9"])+ "." (["0"-"9"])* (<EXPONENT>)? // matches: 5.5 or 5. or 5.5E10 or 5.E10 - | "." (["0"-"9"])+ (<EXPONENT>)? // matches: .5 or .5E10 - | (["0"-"9"])+ <EXPONENT> // matches: 5E10 - > - | < #EXPONENT: "E" (["+","-"])? (["0"-"9"])+ > - | < STRING_LITERAL: "'" ( ("''") | ~["'"] )* "'" > -} - -TOKEN [IGNORE_CASE] : -{ - < ID : ["a"-"z", "_", "$"] (["a"-"z","0"-"9","_", "$"])* > - | < QUOTED_ID : "\"" ( ("\"\"") | ~["\""] )* "\"" > - -} - -// ---------------------------------------------------------------------------- -// Grammer -// ---------------------------------------------------------------------------- -BooleanExpression JmsSelector() : -{ - Expression left=null; -} -{ - ( - left = orExpression() - ) - { - return asBooleanExpression(left); - } - -} - -Expression orExpression() : -{ - Expression left; - Expression right; -} -{ - ( - left = andExpression() - ( - <OR> right = andExpression() - { - left = LogicExpression.createOR(asBooleanExpression(left), asBooleanExpression(right)); - } - )* - ) - { - return left; - } - -} - - -Expression andExpression() : -{ - Expression left; - Expression right; -} -{ - ( - left = equalityExpression() - ( - <AND> right = equalityExpression() - { - left = LogicExpression.createAND(asBooleanExpression(left), asBooleanExpression(right)); - } - )* - ) - { - return left; - } -} - -Expression equalityExpression() : -{ - Expression left; - Expression right; -} -{ - ( - left = comparisonExpression() - ( - - "=" right = comparisonExpression() - { - left = ComparisonExpression.createEqual(left, right); - } - | - "<>" right = comparisonExpression() - { - left = ComparisonExpression.createNotEqual(left, right); - } - | - LOOKAHEAD(2) - <IS> <NULL> - { - left = ComparisonExpression.createIsNull(left); - } - | - <IS> <NOT> <NULL> - { - left = ComparisonExpression.createIsNotNull(left); - } - )* - ) - { - return left; - } -} - -Expression comparisonExpression() : -{ - Expression left; - Expression right; - Expression low; - Expression high; - String t, u; - boolean not; - ArrayList list; -} -{ - ( - left = addExpression() - ( - - ">" right = addExpression() - { - left = ComparisonExpression.createGreaterThan(left, right); - } - | - ">=" right = addExpression() - { - left = ComparisonExpression.createGreaterThanEqual(left, right); - } - | - "<" right = addExpression() - { - left = ComparisonExpression.createLessThan(left, right); - } - | - "<=" right = addExpression() - { - left = ComparisonExpression.createLessThanEqual(left, right); - } - | - { - u=null; - } - <LIKE> t = stringLitteral() - [ <ESCAPE> u = stringLitteral() ] - { - left = ComparisonExpression.createLike(left, t, u); - } - | - LOOKAHEAD(2) - { - u=null; - } - <NOT> <LIKE> t = stringLitteral() [ <ESCAPE> u = stringLitteral() ] - { - left = ComparisonExpression.createNotLike(left, t, u); - } - | - <BETWEEN> low = addExpression() <AND> high = addExpression() - { - left = ComparisonExpression.createBetween(left, low, high); - } - | - LOOKAHEAD(2) - <NOT> <BETWEEN> low = addExpression() <AND> high = addExpression() - { - left = ComparisonExpression.createNotBetween(left, low, high); - } - | - <IN> - "(" - t = stringLitteral() - { - list = new ArrayList(); - list.add( t ); - } - ( - "," - t = stringLitteral() - { - list.add( t ); - } - - )* - ")" - { - left = ComparisonExpression.createInFilter(left, list); - } - | - LOOKAHEAD(2) - <NOT> <IN> - "(" - t = stringLitteral() - { - list = new ArrayList(); - list.add( t ); - } - ( - "," - t = stringLitteral() - { - list.add( t ); - } - - )* - ")" - { - left = ComparisonExpression.createNotInFilter(left, list); - } - - )* - ) - { - return left; - } -} - -Expression addExpression() : -{ - Expression left; - Expression right; -} -{ - left = multExpr() - ( - LOOKAHEAD( ("+"|"-") multExpr()) - ( - "+" right = multExpr() - { - left = ArithmeticExpression.createPlus(left, right); - } - | - "-" right = multExpr() - { - left = ArithmeticExpression.createMinus(left, right); - } - ) - - )* - { - return left; - } -} - -Expression multExpr() : -{ - Expression left; - Expression right; -} -{ - left = unaryExpr() - ( - "*" right = unaryExpr() - { - left = ArithmeticExpression.createMultiply(left, right); - } - | - "/" right = unaryExpr() - { - left = ArithmeticExpression.createDivide(left, right); - } - | - "%" right = unaryExpr() - { - left = ArithmeticExpression.createMod(left, right); - } - - )* - { - return left; - } -} - - -Expression unaryExpr() : -{ - String s=null; - Expression left=null; -} -{ - ( - LOOKAHEAD( "+" unaryExpr() ) - "+" left=unaryExpr() - | - "-" left=unaryExpr() - { - left = UnaryExpression.createNegate(left); - } - | - <NOT> left=unaryExpr() - { - left = UnaryExpression.createNOT( asBooleanExpression(left) ); - } - | - left = primaryExpr() - ) - { - return left; - } - -} - -Expression primaryExpr() : -{ - Expression left=null; -} -{ - ( - left = literal() - | - left = variable() - | - "(" left = orExpression() ")" - ) - { - return left; - } -} - - - -ConstantExpression literal() : -{ - Token t; - String s; - ConstantExpression left=null; -} -{ - ( - ( - s = stringLitteral() - { - left = new ConstantExpression(s); - } - ) - | - ( - t = <DECIMAL_LITERAL> - { - left = ConstantExpression.createFromDecimal(t.image); - } - ) - | - ( - t = <HEX_LITERAL> - { - left = ConstantExpression.createFromHex(t.image); - } - ) - | - ( - t = <OCTAL_LITERAL> - { - left = ConstantExpression.createFromOctal(t.image); - } - ) - | - ( - t = <FLOATING_POINT_LITERAL> - { - left = ConstantExpression.createFloat(t.image); - } - ) - | - ( - <TRUE> - { - left = ConstantExpression.TRUE; - } - ) - | - ( - <FALSE> - { - left = ConstantExpression.FALSE; - } - ) - | - ( - <NULL> - { - left = ConstantExpression.NULL; - } - ) - ) - { - return left; - } -} - -String stringLitteral() : -{ - Token t; - StringBuffer rc = new StringBuffer(); - boolean first=true; -} -{ - t = <STRING_LITERAL> - { - // Decode the sting value. - String image = t.image; - for( int i=1; i < image.length()-1; i++ ) { - char c = image.charAt(i); - if( c == '\'' ) - i++; - rc.append(c); - } - return rc.toString(); - } -} - -PropertyExpression variable() : -{ - Token t; - StringBuffer rc = new StringBuffer(); - PropertyExpression left=null; -} -{ - ( - t = <ID> - { - left = new PropertyExpression(t.image); - } - | - t = <QUOTED_ID> - { - // Decode the sting value. - String image = t.image; - for( int i=1; i < image.length()-1; i++ ) { - char c = image.charAt(i); - if( c == '"' ) - i++; - rc.append(c); - } - return new PropertyExpression(rc.toString()); - } - - ) - { - return left; - } -} diff --git a/qpid/java/client/src/main/java/client.bnd b/qpid/java/client/src/main/java/client.bnd index d92d582ec8..495ea6793f 100755 --- a/qpid/java/client/src/main/java/client.bnd +++ b/qpid/java/client/src/main/java/client.bnd @@ -17,7 +17,7 @@ # under the License. # -ver: 0.15.0 +ver: 0.17.0 Bundle-SymbolicName: qpid-client Bundle-Version: ${ver} 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 index 8311aa80ce..c324e22ab1 100644 --- 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 @@ -20,15 +20,14 @@ */ package org.apache.qpid.client; -import java.net.URISyntaxException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.messaging.Address; +import org.apache.qpid.url.BindingURL; 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; +import java.net.URISyntaxException; /** * In order to support JMS 1.0 the Qpid implementation maps the 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 index b343820d80..09cb9428fe 100644 --- 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 @@ -20,16 +20,16 @@ */ package org.apache.qpid.client; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.HashMap; -import java.util.Map; - import org.apache.qpid.jms.BrokerDetails; import org.apache.qpid.transport.ConnectionSettings; import org.apache.qpid.url.URLHelper; import org.apache.qpid.url.URLSyntaxException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.HashMap; +import java.util.Map; + public class AMQBrokerDetails implements BrokerDetails { private String _host; @@ -264,30 +264,12 @@ public class AMQBrokerDetails implements BrokerDetails 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; - } + if (_options.containsKey(propName)) + { + return Boolean.parseBoolean(_options.get(propName)); + } + + return false; } public void setTimeout(long timeout) @@ -319,18 +301,18 @@ public class AMQBrokerDetails implements BrokerDetails BrokerDetails bd = (BrokerDetails) o; - return _host.equalsIgnoreCase(bd.getHost()) && + return _host.toLowerCase().equals(bd.getHost() == null ? null : bd.getHost().toLowerCase()) && (_port == bd.getPort()) && - _transport.equalsIgnoreCase(bd.getTransport()); + _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.hashCode() : 0; + int result = _host != null ? _host.toLowerCase().hashCode() : 0; result = 31 * result + _port; - result = 31 * result + (_transport != null ? _transport.hashCode() : 0); + result = 31 * result + (_transport != null ? _transport.toLowerCase().hashCode() : 0); return result; } @@ -457,7 +439,7 @@ public class AMQBrokerDetails implements BrokerDetails if (getProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY) != null) { conSettings.setTcpNodelay( - getBooleanProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY,true)); + getBooleanProperty(BrokerDetails.OPTIONS_TCP_NO_DELAY)); } 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 index 6879fe0cfd..1f61e0d218 100644 --- 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 @@ -20,42 +20,14 @@ */ package org.apache.qpid.client; -import java.io.IOException; -import java.lang.reflect.InvocationTargetException; -import java.net.ConnectException; -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.TimeUnit; - -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.AMQDisconnectedException; import org.apache.qpid.client.failover.FailoverException; import org.apache.qpid.client.failover.FailoverProtectedOperation; import org.apache.qpid.client.protocol.AMQProtocolHandler; @@ -76,8 +48,36 @@ import org.apache.qpid.jms.ConnectionURL; import org.apache.qpid.jms.FailoverPolicy; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.url.URLSyntaxException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +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 java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.net.ConnectException; +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.TimeUnit; public class AMQConnection extends Closeable implements Connection, QueueConnection, TopicConnection, Referenceable { @@ -106,7 +106,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect * the handler deals with this. It also deals with the initial dispatch of any protocol frames to their appropriate * handler. */ - protected AMQProtocolHandler _protocolHandler; + private AMQProtocolHandler _protocolHandler; /** Maps from session id (Integer) to AMQSession instance */ private final ChannelToSessionMap _sessions = new ChannelToSessionMap(); @@ -122,7 +122,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect /** The virtual path to connect to on the AMQ server */ private String _virtualHost; - protected ExceptionListener _exceptionListener; + private ExceptionListener _exceptionListener; private ConnectionListener _connectionListener; @@ -132,15 +132,15 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect * Whether this connection is started, i.e. whether messages are flowing to consumers. It has no meaning for message * publication. */ - protected volatile boolean _started; + private volatile boolean _started; /** Policy dictating how to failover */ - protected FailoverPolicy _failoverPolicy; + private FailoverPolicy _failoverPolicy; /* * _Connected should be refactored with a suitable wait object. */ - protected boolean _connected; + private boolean _connected; /* * The connection meta data @@ -156,7 +156,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect private final ExecutorService _taskPool = Executors.newCachedThreadPool(); private static final long DEFAULT_TIMEOUT = 1000 * 30; - protected AMQConnectionDelegate _delegate; + private AMQConnectionDelegate _delegate; // this connection maximum number of prefetched messages private int _maxPrefetch; @@ -308,9 +308,9 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect _delegate = new AMQConnectionDelegate_0_10(this); } - if (_logger.isInfoEnabled()) + if (_logger.isDebugEnabled()) { - _logger.info("Connection:" + connectionURL); + _logger.debug("Connection:" + connectionURL); } _connectionURL = connectionURL; @@ -343,14 +343,17 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect _protocolHandler = new AMQProtocolHandler(this); - _logger.info("Connecting with ProtocolHandler Version:"+_protocolHandler.getProtocolVersion()); + if (_logger.isDebugEnabled()) + { + _logger.debug("Connecting with ProtocolHandler Version:"+_protocolHandler.getProtocolVersion()); + } // We are not currently connected - _connected = false; + setConnected(false); boolean retryAllowed = true; Exception connectionException = null; - while (!_connected && retryAllowed && brokerDetails != null) + while (!isConnected() && retryAllowed && brokerDetails != null) { ProtocolVersion pe = null; try @@ -374,7 +377,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect // broker initDelegate(pe); } - else if (!_connected) + else if (!isConnected()) { retryAllowed = _failoverPolicy.failoverAllowed(); brokerDetails = _failoverPolicy.getNextBrokerDetails(); @@ -384,10 +387,10 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect if (_logger.isDebugEnabled()) { - _logger.debug("Are we connected:" + _connected); + _logger.debug("Are we connected:" + isConnected()); } - if (!_connected) + if (!isConnected()) { if (_logger.isDebugEnabled()) { @@ -435,7 +438,10 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect throw new AMQConnectionFailureException(message, connectionException); } - _logger.info("Connected with ProtocolHandler Version:"+_protocolHandler.getProtocolVersion()); + if (_logger.isDebugEnabled()) + { + _logger.debug("Connected with ProtocolHandler Version:"+_protocolHandler.getProtocolVersion()); + } _sessions.setMaxChannelID(_delegate.getMaxChannelID()); _sessions.setMinChannelID(_delegate.getMinChannelID()); @@ -462,7 +468,10 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect String delegateClassName = String.format ("org.apache.qpid.client.AMQConnectionDelegate_%s_%s", pe.getMajorVersion(), pe.getMinorVersion()); - _logger.info("Looking up delegate '" + delegateClassName + "' Based on PE:" + pe); + 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; @@ -590,7 +599,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect public boolean failoverAllowed() { - if (!_connected) + if (!isConnected()) { return false; } @@ -729,6 +738,11 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect } + protected final ExceptionListener getExceptionListenerNoCheck() + { + return _exceptionListener; + } + public ExceptionListener getExceptionListener() throws JMSException { checkNotClosed(); @@ -804,13 +818,13 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect public void close(List<AMQSession> sessions, long timeout) throws JMSException { - if (!_closed.getAndSet(true)) + if (!setClosed()) { - _closing.set(true); + setClosing(true); try{ doClose(sessions, timeout); }finally{ - _closing.set(false); + setClosing(false); } } } @@ -963,7 +977,8 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect { checkNotClosed(); - return null; + throw new JmsNotImplementedException(); + } public ConnectionConsumer createConnectionConsumer(Queue queue, String messageSelector, ServerSessionPool sessionPool, @@ -971,7 +986,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect { checkNotClosed(); - return null; + throw new JmsNotImplementedException(); } public ConnectionConsumer createConnectionConsumer(Topic topic, String messageSelector, ServerSessionPool sessionPool, @@ -979,7 +994,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect { checkNotClosed(); - return null; + throw new JmsNotImplementedException(); } public ConnectionConsumer createDurableConnectionConsumer(Topic topic, String subscriptionName, String messageSelector, @@ -988,7 +1003,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect // TODO Auto-generated method stub checkNotClosed(); - return null; + throw new JmsNotImplementedException(); } public long getMaximumChannelCount() throws JMSException @@ -1048,16 +1063,26 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect return _virtualHost; } - public AMQProtocolHandler getProtocolHandler() + public final AMQProtocolHandler getProtocolHandler() { return _protocolHandler; } - public boolean started() + public final boolean started() { return _started; } + protected final boolean isConnected() + { + return _connected; + } + + protected final void setConnected(boolean connected) + { + _connected = connected; + } + public void bytesSent(long writtenBytes) { if (_connectionListener != null) @@ -1226,8 +1251,8 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect if (cause instanceof IOException || cause instanceof AMQDisconnectedException) { // If we have an IOE/AMQDisconnect there is no connection to close on. - _closing.set(false); - closer = !_closed.getAndSet(true); + setClosing(false); + closer = !setClosed(); _protocolHandler.getProtocolSession().notifyError(je); } @@ -1238,7 +1263,7 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect // decide if we are going to close the session if (hardError(cause)) { - closer = (!_closed.getAndSet(true)) || closer; + closer = (!setClosed()) || closer; { _logger.info("Closing AMQConnection due to :" + cause); } @@ -1489,4 +1514,8 @@ public class AMQConnection extends Closeable implements Connection, QueueConnect return _lastFailoverTime; } + protected AMQConnectionDelegate getDelegate() + { + return _delegate; + } } 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 index 7fc1d25c18..b6f25a2cef 100644 --- 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 @@ -20,11 +20,6 @@ */ 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; @@ -32,6 +27,10 @@ import org.apache.qpid.framing.ProtocolVersion; import org.apache.qpid.jms.BrokerDetails; import org.apache.qpid.jms.Session; +import javax.jms.JMSException; +import javax.jms.XASession; +import java.io.IOException; + public interface AMQConnectionDelegate { ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException, AMQException; 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 index 0ded689ea6..56ee56d178 100644 --- 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 @@ -21,16 +21,8 @@ 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 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; @@ -42,6 +34,7 @@ import org.apache.qpid.framing.ProtocolVersion; import org.apache.qpid.jms.BrokerDetails; import org.apache.qpid.jms.ChannelLimitReachedException; 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; @@ -53,8 +46,16 @@ import org.apache.qpid.transport.ProtocolVersionException; import org.apache.qpid.transport.SessionDetachCode; import org.apache.qpid.transport.SessionException; import org.apache.qpid.transport.TransportException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import javax.jms.ExceptionListener; +import javax.jms.JMSException; +import javax.jms.XASession; +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; public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, ConnectionListener { @@ -71,7 +72,7 @@ public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, Connec /** * The QpidConeection instance that is mapped with this JMS connection. */ - org.apache.qpid.transport.Connection _qpidConnection; + private org.apache.qpid.transport.Connection _qpidConnection; private ConnectionException exception = null; //--- constructor @@ -109,7 +110,7 @@ public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, Connec session = new AMQSession_0_10(_qpidConnection, _conn, channelId, transacted, acknowledgeMode, prefetchHigh, prefetchLow,name); _conn.registerSession(channelId, session); - if (_conn._started) + if (_conn.started()) { session.start(); } @@ -152,7 +153,7 @@ public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, Connec { session = new XASessionImpl(_qpidConnection, _conn, channelId, prefetchHigh, prefetchLow); _conn.registerSession(channelId, session); - if (_conn._started) + if (_conn.started()) { session.start(); } @@ -164,7 +165,6 @@ public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, Connec return session; } - @Override public XASession createXASession(int ackMode) throws JMSException { @@ -182,7 +182,7 @@ public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, Connec { session = new XASessionImpl(_qpidConnection, _conn, channelId, ackMode, (int)_conn.getMaxPrefetch(), (int)_conn.getMaxPrefetch() / 2); _conn.registerSession(channelId, session); - if (_conn._started) + if (_conn.started()) { session.start(); } @@ -218,10 +218,10 @@ public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, Connec _qpidConnection.setConnectionDelegate(new ClientConnectionDelegate(conSettings, _conn.getConnectionURL())); _qpidConnection.connect(conSettings); - _conn._connected = true; + _conn.setConnected(true); _conn.setUsername(_qpidConnection.getUserID()); _conn.setMaximumChannelCount(_qpidConnection.getChannelMax()); - _conn._failoverPolicy.attainedConnection(); + _conn.getFailoverPolicy().attainedConnection(); } catch (ProtocolVersionException pe) { @@ -327,7 +327,7 @@ public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, Connec } } - ExceptionListener listener = _conn._exceptionListener; + ExceptionListener listener = _conn.getExceptionListenerNoCheck(); if (listener == null) { _logger.error("connection exception: " + conn, exc); @@ -429,7 +429,7 @@ public class AMQConnectionDelegate_0_10 implements AMQConnectionDelegate, Connec Map<String, Object> clientProps = new HashMap<String, Object>(); try { - clientProps.put("clientName", _conn.getClientID()); + clientProps.put(ConnectionStartProperties.CLIENT_ID_0_10, _conn.getClientID()); conSettings.setClientProperties(clientProps); } catch (JMSException e) 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 index 74a0956933..08ee7c3705 100644 --- 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 @@ -20,19 +20,8 @@ */ package org.apache.qpid.client; -import java.io.IOException; -import java.net.ConnectException; -import java.nio.channels.UnresolvedAddressException; -import java.security.GeneralSecurityException; -import java.text.MessageFormat; -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.Set; - -import javax.jms.JMSException; -import javax.jms.XASession; -import javax.net.ssl.SSLContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.apache.qpid.AMQException; import org.apache.qpid.AMQTimeoutException; @@ -60,8 +49,19 @@ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import javax.jms.JMSException; +import javax.jms.XASession; +import javax.net.ssl.SSLContext; +import java.io.IOException; +import java.net.ConnectException; +import java.nio.channels.UnresolvedAddressException; +import java.security.GeneralSecurityException; +import java.text.MessageFormat; +import java.util.ArrayList; +import java.util.EnumSet; +import java.util.Iterator; +import java.util.Set; public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate { @@ -71,30 +71,7 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate public void closeConnection(long timeout) throws JMSException, AMQException { - final AMQStateManager stateManager = _conn.getProtocolHandler().getStateManager(); - final AMQState currentState = stateManager.getCurrentState(); - - if (currentState.equals(AMQState.CONNECTION_CLOSED)) - { - _logger.debug("Connection already closed."); - } - else if (currentState.equals(AMQState.CONNECTION_CLOSING)) - { - _logger.debug("Connection already closing, awaiting closed state."); - final StateWaiter closeWaiter = new StateWaiter(stateManager, currentState, EnumSet.of(AMQState.CONNECTION_CLOSED)); - try - { - closeWaiter.await(timeout); - } - catch (AMQTimeoutException te) - { - throw new AMQTimeoutException("Close did not complete in timely fashion", te); - } - } - else - { - _conn.getProtocolHandler().closeConnection(timeout); - } + _conn.getProtocolHandler().closeConnection(timeout); } public AMQConnectionDelegate_8_0(AMQConnection conn) @@ -120,7 +97,7 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate EnumSet.of(AMQState.CONNECTION_OPEN, AMQState.CONNECTION_CLOSED); - StateWaiter waiter = _conn._protocolHandler.createWaiter(openOrClosedStates); + StateWaiter waiter = _conn.getProtocolHandler().createWaiter(openOrClosedStates); ConnectionSettings settings = brokerDetail.buildConnectionSettings(); settings.setProtocol(brokerDetail.getTransport()); @@ -133,10 +110,10 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate sslContext = SSLContextFactory.buildClientContext( settings.getTrustStorePath(), settings.getTrustStorePassword(), - settings.getTrustStoreCertType(), + settings.getTrustManagerFactoryAlgorithm(), settings.getKeyStorePath(), settings.getKeyStorePassword(), - settings.getKeyStoreCertType(), + settings.getKeyManagerFactoryAlgorithm(), settings.getCertAlias()); } catch (GeneralSecurityException e) @@ -148,9 +125,9 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate SecurityLayer securityLayer = SecurityLayerFactory.newInstance(settings); OutgoingNetworkTransport transport = Transport.getOutgoingTransportInstance(getProtocolVersion()); - NetworkConnection network = transport.connect(settings, securityLayer.receiver(_conn._protocolHandler), sslContext); - _conn._protocolHandler.setNetworkConnection(network, securityLayer.sender(network.getSender())); - _conn._protocolHandler.getProtocolSession().init(); + NetworkConnection network = transport.connect(settings, securityLayer.receiver(_conn.getProtocolHandler()), sslContext); + _conn.getProtocolHandler().setNetworkConnection(network, securityLayer.sender(network.getSender())); + _conn.getProtocolHandler().getProtocolSession().init(); // this blocks until the connection has been set up or when an error // has prevented the connection being set up @@ -158,13 +135,13 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate if(state == AMQState.CONNECTION_OPEN) { - _conn._failoverPolicy.attainedConnection(); - _conn._connected = true; + _conn.getFailoverPolicy().attainedConnection(); + _conn.setConnected(true); return null; } else { - return _conn._protocolHandler.getSuggestedProtocolVersion(); + return _conn.getProtocolHandler().getSuggestedProtocolVersion(); } } @@ -213,7 +190,6 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate AMQSession session = new AMQSession_0_8(_conn, channelId, transacted, acknowledgeMode, prefetchHigh, prefetchLow); - // _protocolHandler.addSessionByChannel(channelId, session); _conn.registerSession(channelId, session); boolean success = false; @@ -237,7 +213,7 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate } } - if (_conn._started) + if (_conn.started()) { try { @@ -271,12 +247,12 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate { ChannelOpenBody channelOpenBody = _conn.getProtocolHandler().getMethodRegistry().createChannelOpenBody(null); // TODO: Be aware of possible changes to parameter order as versions change. - _conn._protocolHandler.syncWrite(channelOpenBody.generateFrame(channelId), ChannelOpenOkBody.class); + _conn.getProtocolHandler().syncWrite(channelOpenBody.generateFrame(channelId), ChannelOpenOkBody.class); // todo send low water mark when protocol allows. // todo Be aware of possible changes to parameter order as versions change. BasicQosBody basicQosBody = _conn.getProtocolHandler().getMethodRegistry().createBasicQosBody(0,prefetchHigh,false); - _conn._protocolHandler.syncWrite(basicQosBody.generateFrame(channelId),BasicQosOkBody.class); + _conn.getProtocolHandler().syncWrite(basicQosBody.generateFrame(channelId),BasicQosOkBody.class); if (transacted) { @@ -287,7 +263,7 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate TxSelectBody body = _conn.getProtocolHandler().getMethodRegistry().createTxSelectBody(); // TODO: Be aware of possible changes to parameter order as versions change. - _conn._protocolHandler.syncWrite(body.generateFrame(channelId), TxSelectOkBody.class); + _conn.getProtocolHandler().syncWrite(body.generateFrame(channelId), TxSelectOkBody.class); } } @@ -307,7 +283,6 @@ public class AMQConnectionDelegate_8_0 implements AMQConnectionDelegate for (Iterator it = sessions.iterator(); it.hasNext();) { AMQSession s = (AMQSession) it.next(); - // _protocolHandler.addSessionByChannel(s.getChannelId(), s); reopenChannel(s.getChannelId(), s.getDefaultPrefetchHigh(), s.getDefaultPrefetchLow(), s.isTransacted()); s.resubscribe(); } 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 index 700073488e..e684cf9074 100644 --- 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 @@ -20,12 +20,23 @@ */ package org.apache.qpid.client; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Hashtable; -import java.util.UUID; +import org.apache.qpid.jms.ConnectionURL; +import org.apache.qpid.url.AMQBindingURL; +import org.apache.qpid.url.URLSyntaxException; -import javax.jms.*; +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; @@ -34,10 +45,10 @@ import javax.naming.Reference; import javax.naming.Referenceable; import javax.naming.StringRefAddr; import javax.naming.spi.ObjectFactory; - -import org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.url.AMQBindingURL; -import org.apache.qpid.url.URLSyntaxException; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Hashtable; +import java.util.UUID; public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionFactory, TopicConnectionFactory, @@ -46,12 +57,6 @@ public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionF { private final ConnectionURL _connectionDetails; - // The default constructor is necessary to allow AMQConnectionFactory to be deserialised from JNDI - public AMQConnectionFactory() - { - _connectionDetails = null; - } - public AMQConnectionFactory(final String url) throws URLSyntaxException { if (url == null) @@ -119,35 +124,27 @@ public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionF public Connection createConnection(String userName, String password, String id) throws JMSException { - if (_connectionDetails != null) + try { - try + _connectionDetails.setUsername(userName); + _connectionDetails.setPassword(password); + + if (id != null && !id.equals("")) { - ConnectionURL connectionDetails = new AMQConnectionURL(_connectionDetails.toString()); - 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) + _connectionDetails.setClientName(id); + } + else if (_connectionDetails.getClientName() == null || _connectionDetails.getClientName().equals("")) { - JMSException jmse = new JMSException("Error creating connection: " + e.getMessage()); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; + _connectionDetails.setClientName(getUniqueClientID()); } + return new AMQConnection(_connectionDetails); } - else + catch (Exception e) { - throw new JMSException("The connection factory wasn't created with a proper URL, the connection details are empty"); + JMSException jmse = new JMSException("Error creating connection: " + e.getMessage()); + jmse.setLinkedException(e); + jmse.initCause(e); + throw jmse; } } @@ -266,7 +263,7 @@ public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionF * * @return A newly created XAConnection * @throws JMSException If creating the XAConnection fails due to some internal error. - * @throws JMSSecurityException If client authentication fails due to an invalid user name or password. + * @throws javax.jms.JMSSecurityException If client authentication fails due to an invalid user name or password. */ public XAConnection createXAConnection() throws JMSException { @@ -293,36 +290,25 @@ public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionF * @param password the caller's password * @return A newly created XAConnection. * @throws JMSException If creating the XAConnection fails due to some internal error. - * @throws JMSSecurityException If client authentication fails due to an invalid user name or password. + * @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) + _connectionDetails.setUsername(username); + _connectionDetails.setPassword(password); + + if (_connectionDetails.getClientName() == null || _connectionDetails.getClientName().equals("")) { - JMSException jmse = new JMSException("Error creating XA Connection: " + e.getMessage()); - jmse.setLinkedException(e); - jmse.initCause(e); - throw jmse; + _connectionDetails.setClientName(getUniqueClientID()); } } else { - throw new JMSException("The connection factory wasn't created with a proper URL, the connection details are empty"); - } + throw new JMSException("A URL must be specified to access XA connections"); + } + return createXAConnection(); } @@ -334,7 +320,7 @@ public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionF * * @return A newly created XATopicConnection * @throws JMSException If creating the XATopicConnection fails due to some internal error. - * @throws JMSSecurityException If client authentication fails due to an invalid user name or password. + * @throws javax.jms.JMSSecurityException If client authentication fails due to an invalid user name or password. */ public XATopicConnection createXATopicConnection() throws JMSException { @@ -351,7 +337,7 @@ public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionF * @param password the caller's password * @return A newly created XATopicConnection. * @throws JMSException If creating the XATopicConnection fails due to some internal error. - * @throws JMSSecurityException If client authentication fails due to an invalid user name or password. + * @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 { @@ -366,7 +352,7 @@ public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionF * * @return A newly created XAQueueConnection * @throws JMSException If creating the XAQueueConnection fails due to some internal error. - * @throws JMSSecurityException If client authentication fails due to an invalid user name or password. + * @throws javax.jms.JMSSecurityException If client authentication fails due to an invalid user name or password. */ public XAQueueConnection createXAQueueConnection() throws JMSException { @@ -383,7 +369,7 @@ public class AMQConnectionFactory implements ConnectionFactory, QueueConnectionF * @param password the caller's password * @return A newly created XAQueueConnection. * @throws JMSException If creating the XAQueueConnection fails due to some internal error. - * @throws JMSSecurityException If client authentication fails due to an invalid user name or password. + * @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 { 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 index ee55eb9ce9..d59f48542f 100644 --- 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 @@ -20,11 +20,6 @@ */ package org.apache.qpid.client; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - import org.apache.qpid.client.url.URLParser; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.jms.BrokerDetails; @@ -32,6 +27,11 @@ import org.apache.qpid.jms.ConnectionURL; import org.apache.qpid.url.URLHelper; import org.apache.qpid.url.URLSyntaxException; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + public class AMQConnectionURL implements ConnectionURL { private String _url; @@ -50,7 +50,10 @@ public class AMQConnectionURL implements ConnectionURL public AMQConnectionURL(String fullURL) throws URLSyntaxException { - if (fullURL == null) throw new IllegalArgumentException("URL cannot be null"); + if (fullURL == null) + { + throw new IllegalArgumentException("URL cannot be null"); + } _url = fullURL; _options = new HashMap<String, String>(); _brokers = new LinkedList<BrokerDetails>(); @@ -273,7 +276,8 @@ public class AMQConnectionURL implements ConnectionURL if (_failoverMethod != null) { sb.append(URLHelper.DEFAULT_OPTION_SEPERATOR); - sb.append(OPTIONS_FAILOVER + "='"); + sb.append(OPTIONS_FAILOVER); + sb.append("='"); sb.append(_failoverMethod); sb.append(URLHelper.printOptions(_failoverOptions)); sb.append("'"); 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 index 61fe722423..530186b1f9 100644 --- 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 @@ -20,15 +20,8 @@ */ package org.apache.qpid.client; -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; @@ -40,23 +33,30 @@ import org.apache.qpid.messaging.Address; import org.apache.qpid.url.AMQBindingURL; import org.apache.qpid.url.BindingURL; import org.apache.qpid.url.URLHelper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import javax.jms.Destination; +import javax.naming.NamingException; +import javax.naming.Reference; +import javax.naming.Referenceable; +import javax.naming.StringRefAddr; +import java.net.URISyntaxException; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; public abstract class AMQDestination implements Destination, Referenceable { private static final Logger _logger = LoggerFactory.getLogger(AMQDestination.class); - protected AMQShortString _exchangeName; + private AMQShortString _exchangeName; - protected AMQShortString _exchangeClass; + private AMQShortString _exchangeClass; - protected boolean _isDurable; + private boolean _isDurable; - protected boolean _isExclusive; + private boolean _isExclusive; - protected boolean _isAutoDelete; + private boolean _isAutoDelete; private boolean _browseOnly; @@ -81,6 +81,41 @@ public abstract class AMQDestination implements Destination, Referenceable 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; + } + + protected Link getTargetLink() + { + return _targetLink; + } + + protected void setTargetLink(Link targetLink) + { + _targetLink = targetLink; + } + // ----- Fields required to support new address syntax ------- public enum DestSyntax { @@ -109,31 +144,46 @@ public abstract class AMQDestination implements Destination, Referenceable 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"); + 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"); + } } } - protected final static DestSyntax defaultDestSyntax; + private final static DestSyntax defaultDestSyntax; - protected DestSyntax _destSyntax = DestSyntax.ADDR; + private DestSyntax _destSyntax = DestSyntax.ADDR; - protected AddressHelper _addrHelper; - protected Address _address; - protected int _addressType = AMQDestination.UNKNOWN_TYPE; - protected String _name; - protected String _subject; - protected AddressOption _create = AddressOption.NEVER; - protected AddressOption _assert = AddressOption.NEVER; - protected AddressOption _delete = AddressOption.NEVER; + 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; - protected Node _targetNode; - protected Node _sourceNode; - protected Link _targetLink; - protected Link _link; + private Node _targetNode; + private Node _sourceNode; + private Link _targetLink; + private Link _link; // ----- / Fields required to support new address syntax ------- @@ -543,7 +593,7 @@ public abstract class AMQDestination implements Destination, Referenceable { return true; } - if (o == null || getClass() != o.getClass()) + if (!(o instanceof AMQDestination)) { return false; } @@ -572,7 +622,6 @@ public abstract class AMQDestination implements Destination, Referenceable int result; result = _exchangeName == null ? "".hashCode() : _exchangeName.hashCode(); result = 29 * result + (_exchangeClass == null ? "".hashCode() :_exchangeClass.hashCode()); - //result = 29 * result + _destinationName.hashCode(); if (_queueName != null) { result = 29 * result + _queueName.hashCode(); @@ -631,10 +680,10 @@ public abstract class AMQDestination implements Destination, Referenceable public static class Binding { - String exchange; - String bindingKey; - String queue; - Map<String,Object> args; + private String exchange; + private String bindingKey; + private String queue; + private Map<String,Object> args; public Binding(String exchange, String queue, @@ -887,4 +936,5 @@ public abstract class AMQDestination implements Destination, Referenceable return _rejectBehaviour; } + } 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 index 5ecb5d5913..4e9b53c814 100644 --- 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 @@ -20,14 +20,13 @@ */ 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.url.BindingURL; +import javax.jms.Queue; +import java.net.URISyntaxException; + public class AMQQueue extends AMQDestination implements Queue { protected AMQQueue() @@ -156,7 +155,6 @@ public class AMQQueue extends AMQDestination implements Queue public AMQShortString getRoutingKey() { - //return getAMQQueueName(); if (getAMQQueueName() != null && getAMQQueueName().equals(super.getRoutingKey())) { return getAMQQueueName(); @@ -173,4 +171,10 @@ public class AMQQueue extends AMQDestination implements Queue //remain valid if we failover (see BLZ-24) return getQueueName() == null; } + + @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 index 3f9eadeef3..0c6031ea91 100644 --- 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 @@ -20,6 +20,12 @@ */ 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; @@ -39,21 +45,59 @@ public class AMQQueueBrowser implements QueueBrowser private AtomicBoolean _isClosed = new AtomicBoolean(); private final AMQSession _session; - private final AMQQueue _queue; + private final Queue _queue; private final ArrayList<BasicMessageConsumer> _consumers = new ArrayList<BasicMessageConsumer>(); private final String _messageSelector; - AMQQueueBrowser(AMQSession session, AMQQueue queue, String messageSelector) throws JMSException + AMQQueueBrowser(AMQSession session, Queue queue, String messageSelector) throws JMSException { _session = session; _queue = queue; _messageSelector = ((messageSelector == null) || (messageSelector.trim().length() == 0)) ? null : messageSelector; - // Create Consumer to verify message selector. - BasicMessageConsumer consumer = - (BasicMessageConsumer) _session.createBrowserConsumer(_queue, _messageSelector, false); - // Close this consumer as we are not looking to consume only to establish that, at least for now, - // the QB can be created - consumer.close(); + + + 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 @@ -88,6 +132,10 @@ public class AMQQueueBrowser implements QueueBrowser 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); @@ -108,7 +156,7 @@ public class AMQQueueBrowser implements QueueBrowser private class QueueBrowserEnumeration implements Enumeration { - Message _nextMessage; + private Message _nextMessage; private BasicMessageConsumer _consumer; public QueueBrowserEnumeration(BasicMessageConsumer consumer) throws JMSException @@ -118,12 +166,12 @@ public class AMQQueueBrowser implements QueueBrowser _consumer = consumer; prefetchMessage(); } - _logger.info("QB:created with first element:" + _nextMessage); + _logger.debug("QB:created with first element:" + _nextMessage); } public boolean hasMoreElements() { - _logger.info("QB:hasMoreElements:" + (_nextMessage != null)); + _logger.debug("QB:hasMoreElements:" + (_nextMessage != null)); return (_nextMessage != null); } @@ -136,9 +184,9 @@ public class AMQQueueBrowser implements QueueBrowser } try { - _logger.info("QB:nextElement about to receive"); + _logger.debug("QB:nextElement about to receive"); prefetchMessage(); - _logger.info("QB:nextElement received:" + _nextMessage); + _logger.debug("QB:nextElement received:" + _nextMessage); } catch (JMSException e) { 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 index a8c83d8868..c8cb49b53e 100644 --- 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 @@ -20,185 +20,64 @@ */ package org.apache.qpid.client; -import java.io.Serializable; - -import javax.jms.BytesMessage; -import javax.jms.Destination; +import javax.jms.*; import javax.jms.IllegalStateException; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.ObjectMessage; -import javax.jms.Queue; -import javax.jms.QueueBrowser; -import javax.jms.QueueReceiver; -import javax.jms.QueueSender; -import javax.jms.QueueSession; -import javax.jms.Session; -import javax.jms.StreamMessage; -import javax.jms.TemporaryQueue; -import javax.jms.TemporaryTopic; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; /** * Need this adaptor class to conform to JMS spec and throw IllegalStateException * from createDurableSubscriber, unsubscribe, createTopic & createTemporaryTopic */ -public class AMQQueueSessionAdaptor implements QueueSession, AMQSessionAdapter +class AMQQueueSessionAdaptor extends AMQSessionAdapter<QueueSession> implements QueueSession { - //holds a session for delegation - protected final AMQSession _session; - /** * Construct an adaptor with a session to wrap * @param session */ - public AMQQueueSessionAdaptor(Session session) + protected AMQQueueSessionAdaptor(QueueSession session) { - _session = (AMQSession) session; - } - - public TemporaryQueue createTemporaryQueue() throws JMSException { - return _session.createTemporaryQueue(); - } - - public Queue createQueue(String string) throws JMSException { - return _session.createQueue(string); - } - - public QueueReceiver createReceiver(Queue queue) throws JMSException { - return _session.createReceiver(queue); - } - - public QueueReceiver createReceiver(Queue queue, String string) throws JMSException { - return _session.createReceiver(queue, string); - } - - public QueueSender createSender(Queue queue) throws JMSException { - return _session.createSender(queue); - } - - public QueueBrowser createBrowser(Queue queue) throws JMSException { - return _session.createBrowser(queue); - } - - public QueueBrowser createBrowser(Queue queue, String string) throws JMSException { - return _session.createBrowser(queue, string); - } - - 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(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(String string) throws JMSException { - return _session.createTextMessage(string); - } - - 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(); + super(session); } - public void setMessageListener(MessageListener messageListener) throws JMSException { - _session.setMessageListener(messageListener); - } - - public void run() { - _session.run(); - } - - public MessageProducer createProducer(Destination destination) throws JMSException { - return _session.createProducer(destination); - } - - public MessageConsumer createConsumer(Destination destination) throws JMSException { - return _session.createConsumer(destination); + public QueueReceiver createReceiver(Queue queue) throws JMSException + { + return getSession().createReceiver(queue); } - public MessageConsumer createConsumer(Destination destination, String string) throws JMSException { - return _session.createConsumer(destination,string); + public QueueReceiver createReceiver(Queue queue, String string) throws JMSException + { + return getSession().createReceiver(queue, string); } - public MessageConsumer createConsumer(Destination destination, String string, boolean b) throws JMSException { - return _session.createConsumer(destination,string,b); + 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 { + public Topic createTopic(String string) throws JMSException + { throw new IllegalStateException("Cannot call createTopic from QueueSession"); } - public TopicSubscriber createDurableSubscriber(Topic topic, String string) throws JMSException { + 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 { + 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 { + public TemporaryTopic createTemporaryTopic() throws JMSException + { throw new IllegalStateException("Cannot call createTemporaryTopic from QueueSession"); } - public void unsubscribe(String string) throws JMSException { + public void unsubscribe(String string) throws JMSException + { throw new IllegalStateException("Cannot call unsubscribe from QueueSession"); } - public AMQSession getSession() - { - return _session; - } } 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 index 48c4e3e3e6..efc5982dac 100644 --- 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 @@ -20,50 +20,8 @@ */ 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.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.BytesMessage; -import javax.jms.Destination; -import javax.jms.IllegalStateException; -import javax.jms.InvalidDestinationException; -import javax.jms.InvalidSelectorException; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.ObjectMessage; -import javax.jms.Queue; -import javax.jms.QueueBrowser; -import javax.jms.QueueReceiver; -import javax.jms.QueueSender; -import javax.jms.QueueSession; -import javax.jms.StreamMessage; -import javax.jms.TemporaryQueue; -import javax.jms.TemporaryTopic; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.jms.TopicPublisher; -import javax.jms.TopicSession; -import javax.jms.TopicSubscriber; -import javax.jms.TransactionRolledBackException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.apache.qpid.AMQChannelClosedException; import org.apache.qpid.AMQDisconnectedException; @@ -89,7 +47,7 @@ import org.apache.qpid.client.message.UnprocessedMessage; import org.apache.qpid.client.protocol.AMQProtocolHandler; import org.apache.qpid.client.util.FlowControllingBlockingQueue; import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.filter.MessageFilter; +import org.apache.qpid.configuration.ClientProperties; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; import org.apache.qpid.framing.MethodRegistry; @@ -98,8 +56,27 @@ 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.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import javax.jms.*; +import javax.jms.IllegalStateException; +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.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; /** * <p/><table id="crc"><caption>CRC Card</caption> @@ -119,150 +96,65 @@ import org.slf4j.LoggerFactory; */ public abstract class AMQSession<C extends BasicMessageConsumer, P extends BasicMessageProducer> extends Closeable implements Session, QueueSession, TopicSession { - public static final class IdToConsumerMap<C extends BasicMessageConsumer> - { - private final BasicMessageConsumer[] _fastAccessConsumers = new BasicMessageConsumer[16]; - private final ConcurrentHashMap<Integer, C> _slowAccessConsumers = new ConcurrentHashMap<Integer, C>(); - - public C get(int id) - { - if ((id & 0xFFFFFFF0) == 0) - { - return (C) _fastAccessConsumers[id]; - } - else - { - return _slowAccessConsumers.get(id); - } - } - - public C put(int id, C consumer) - { - C oldVal; - if ((id & 0xFFFFFFF0) == 0) - { - oldVal = (C) _fastAccessConsumers[id]; - _fastAccessConsumers[id] = consumer; - } - else - { - oldVal = _slowAccessConsumers.put(id, consumer); - } - - return oldVal; - - } - - public C remove(int id) - { - C consumer; - if ((id & 0xFFFFFFF0) == 0) - { - consumer = (C) _fastAccessConsumers[id]; - _fastAccessConsumers[id] = null; - } - else - { - consumer = _slowAccessConsumers.remove(id); - } - - return consumer; - - } + /** Used for debugging. */ + private static final Logger _logger = LoggerFactory.getLogger(AMQSession.class); - public Collection<C> values() - { - ArrayList<C> values = new ArrayList<C>(); + /** System property to enable strict AMQP compliance. */ + public static final String STRICT_AMQP = "STRICT_AMQP"; - for (int i = 0; i < 16; i++) - { - if (_fastAccessConsumers[i] != null) - { - values.add((C) _fastAccessConsumers[i]); - } - } - values.addAll(_slowAccessConsumers.values()); + /** Strict AMQP default setting. */ + public static final String STRICT_AMQP_DEFAULT = "false"; - return values; - } + /** System property to enable failure if strict AMQP compliance is violated. */ + public static final String STRICT_AMQP_FATAL = "STRICT_AMQP_FATAL"; - public void clear() - { - _slowAccessConsumers.clear(); - for (int i = 0; i < 16; i++) - { - _fastAccessConsumers[i] = null; - } - } - } + /** Strickt AMQP failure default. */ + public static final String STRICT_AMQP_FATAL_DEFAULT = "true"; - final AMQSession<C, P> _thisSession = this; - - /** Used for debugging. */ - private static final Logger _logger = LoggerFactory.getLogger(AMQSession.class); + /** System property to enable immediate message prefetching. */ + public static final String IMMEDIATE_PREFETCH = "IMMEDIATE_PREFETCH"; - /** - * The default value for immediate flag used by producers created by this session is false. That is, a consumer does - * not need to be attached to a queue. - */ - protected final boolean DEFAULT_IMMEDIATE = Boolean.parseBoolean(System.getProperty("qpid.default_immediate", "false")); + /** Immediate message prefetch default. */ + public static final String IMMEDIATE_PREFETCH_DEFAULT = "false"; - /** - * The default value for mandatory flag used by producers created by this session is true. That is, server will not - * silently drop messages where no queue is connected to the exchange for the message. - */ - protected final boolean DEFAULT_MANDATORY = Boolean.parseBoolean(System.getProperty("qpid.default_mandatory", "true")); + public static final long DEFAULT_FLOW_CONTROL_WAIT_FAILURE = 120000L; /** * The period to wait while flow controlled before sending a log message confirming that the session is still * waiting on flow control being revoked */ - protected final long FLOW_CONTROL_WAIT_PERIOD = Long.getLong("qpid.flow_control_wait_notify_period",5000L); + private final long _flowControlWaitPeriod = Long.getLong("qpid.flow_control_wait_notify_period",5000L); /** * The period to wait while flow controlled before declaring a failure */ - public static final long DEFAULT_FLOW_CONTROL_WAIT_FAILURE = 120000L; - protected final long FLOW_CONTROL_WAIT_FAILURE = Long.getLong("qpid.flow_control_wait_failure", + private final long _flowControlWaitFailure = Long.getLong("qpid.flow_control_wait_failure", DEFAULT_FLOW_CONTROL_WAIT_FAILURE); - protected final boolean DECLARE_QUEUES = + private final boolean _delareQueues = Boolean.parseBoolean(System.getProperty("qpid.declare_queues", "true")); - protected final boolean DECLARE_EXCHANGES = + private final boolean _declareExchanges = Boolean.parseBoolean(System.getProperty("qpid.declare_exchanges", "true")); - - protected final boolean USE_AMQP_ENCODED_MAP_MESSAGE; - - /** 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"; - - /** Strickt 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"; + private final boolean _useAMQPEncodedMapMessage; - /** Immediate message prefetch default. */ - public static final String IMMEDIATE_PREFETCH_DEFAULT = "false"; + /** + * Flag indicating to start dispatcher as a daemon thread + */ + protected final boolean DEAMON_DISPATCHER_THREAD = Boolean.getBoolean(ClientProperties.DAEMON_DISPATCHER); /** The connection to which this session belongs. */ - protected AMQConnection _connection; + private AMQConnection _connection; /** Used to indicate whether or not this is a transactional session. */ - protected final boolean _transacted; + private final boolean _transacted; /** Holds the sessions acknowledgement mode. */ - protected final int _acknowledgeMode; + private final int _acknowledgeMode; /** Holds this session unique identifier, used to distinguish it from other sessions. */ - protected int _channelId; + private int _channelId; private int _ticket; @@ -278,55 +170,30 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic /** Used to indicate that this session has been started at least once. */ private AtomicBoolean _startedAtLeastOnce = new AtomicBoolean(false); - /** - * Used to reference durable subscribers so that requests for unsubscribe can be handled correctly. Note this only - * keeps a record of subscriptions which have been created in the current instance. It does not remember - * subscriptions between executions of the client. - */ - protected final ConcurrentHashMap<String, TopicSubscriberAdaptor<C>> _subscriptions = + private final ConcurrentHashMap<String, TopicSubscriberAdaptor<C>> _subscriptions = new ConcurrentHashMap<String, TopicSubscriberAdaptor<C>>(); - /** - * Holds a mapping from message consumers to their identifying names, so that their subscriptions may be looked - * up in the {@link #_subscriptions} map. - */ - protected final ConcurrentHashMap<C, String> _reverseSubscriptionMap = new ConcurrentHashMap<C, String>(); + private final ConcurrentHashMap<C, String> _reverseSubscriptionMap = new ConcurrentHashMap<C, String>(); - /** - * Locks to keep access to subscriber details atomic. - * <p> - * Added for QPID2418 - */ - protected final Lock _subscriberDetails = new ReentrantLock(true); - protected final Lock _subscriberAccess = new ReentrantLock(true); + private final Lock _subscriberDetails = new ReentrantLock(true); + private final Lock _subscriberAccess = new ReentrantLock(true); - /** - * Used to hold incoming messages. - * - * @todo Weaken the type once {@link FlowControllingBlockingQueue} implements Queue. - */ - protected final FlowControllingBlockingQueue _queue; + private final FlowControllingBlockingQueue _queue; - /** Holds the highest received delivery tag. */ - protected final AtomicLong _highestDeliveryTag = new AtomicLong(-1); + private final AtomicLong _highestDeliveryTag = new AtomicLong(-1); private final AtomicLong _rollbackMark = new AtomicLong(-1); - /** Pre-fetched message tags */ - protected ConcurrentLinkedQueue<Long> _prefetchedMessageTags = new ConcurrentLinkedQueue<Long>(); + private ConcurrentLinkedQueue<Long> _prefetchedMessageTags = new ConcurrentLinkedQueue<Long>(); - /** All the not yet acknowledged message tags */ - protected ConcurrentLinkedQueue<Long> _unacknowledgedMessageTags = new ConcurrentLinkedQueue<Long>(); + private ConcurrentLinkedQueue<Long> _unacknowledgedMessageTags = new ConcurrentLinkedQueue<Long>(); - /** All the delivered message tags */ - protected ConcurrentLinkedQueue<Long> _deliveredMessageTags = new ConcurrentLinkedQueue<Long>(); + private ConcurrentLinkedQueue<Long> _deliveredMessageTags = new ConcurrentLinkedQueue<Long>(); - /** Holds the dispatcher thread for this session. */ - protected Dispatcher _dispatcher; + private volatile Dispatcher _dispatcher; - protected Thread _dispatcherThread; + private volatile Thread _dispatcherThread; - /** Holds the message factory factory for this session. */ - protected MessageFactoryRegistry _messageFactoryRegistry; + private MessageFactoryRegistry _messageFactoryRegistry; /** Holds all of the producers created by this session, keyed by their unique identifiers. */ private Map<Long, MessageProducer> _producers = new ConcurrentHashMap<Long, MessageProducer>(); @@ -337,11 +204,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic */ private int _nextTag = 1; - /** - * Maps from identifying tags to message consumers, in order to pass dispatch incoming messages to the right - * consumer. - */ - protected final IdToConsumerMap<C> _consumers = new IdToConsumerMap<C>(); + private final IdToConsumerMap<C> _consumers = new IdToConsumerMap<C>(); /** * Contains a list of consumers which have been removed but which might still have @@ -367,10 +230,6 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic */ private volatile boolean _sessionInRecovery; - /** - * Set when the dispatcher should direct incoming messages straight into the UnackedMessage list instead of - * to the syncRecieveQueue or MessageListener. Used during cleanup, e.g. in Session.recover(). - */ private volatile boolean _usingDispatcherForCleanup; /** Used to indicates that the connection to which this session belongs, has been stopped. */ @@ -388,28 +247,163 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic */ private final Object _suspensionLock = new Object(); - /** - * Used to ensure that only the first call to start the dispatcher can unsuspend the channel. - * - * @todo This is accessed only within a synchronized method, so does not need to be atomic. - */ - protected final AtomicBoolean _firstDispatcher = new AtomicBoolean(true); + private final AtomicBoolean _firstDispatcher = new AtomicBoolean(true); - /** Used to indicate that the session should start pre-fetching messages as soon as it is started. */ - protected final boolean _immediatePrefetch; + private final boolean _immediatePrefetch; - /** Indicates that warnings should be generated on violations of the strict AMQP. */ - protected final boolean _strictAMQP; + private final boolean _strictAMQP; - /** Indicates that runtime exceptions should be generated on vilations of the strict AMQP. */ - protected final boolean _strictAMQPFATAL; + 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; - + + /** Flow control */ + private FlowControlIndicator _flowControl = new FlowControlIndicator(); + + + + /** 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; + } + + /** + * Maps from identifying tags to message consumers, in order to pass dispatch incoming messages to the right + * consumer. + */ + protected IdToConsumerMap<C> getConsumers() + { + return _consumers; + } + + 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; + } + + public static final class IdToConsumerMap<C extends BasicMessageConsumer> + { + private final BasicMessageConsumer[] _fastAccessConsumers = new BasicMessageConsumer[16]; + private final ConcurrentHashMap<Integer, C> _slowAccessConsumers = new ConcurrentHashMap<Integer, C>(); + + public C get(int id) + { + if ((id & 0xFFFFFFF0) == 0) + { + return (C) _fastAccessConsumers[id]; + } + else + { + return _slowAccessConsumers.get(id); + } + } + + public C put(int id, C consumer) + { + C oldVal; + if ((id & 0xFFFFFFF0) == 0) + { + oldVal = (C) _fastAccessConsumers[id]; + _fastAccessConsumers[id] = consumer; + } + else + { + oldVal = _slowAccessConsumers.put(id, consumer); + } + + return oldVal; + + } + + public C remove(int id) + { + C consumer; + if ((id & 0xFFFFFFF0) == 0) + { + consumer = (C) _fastAccessConsumers[id]; + _fastAccessConsumers[id] = null; + } + else + { + consumer = _slowAccessConsumers.remove(id); + } + + return consumer; + + } + + public Collection<C> values() + { + ArrayList<C> values = new ArrayList<C>(); + + for (int i = 0; i < 16; i++) + { + if (_fastAccessConsumers[i] != null) + { + values.add((C) _fastAccessConsumers[i]); + } + } + values.addAll(_slowAccessConsumers.values()); + + return values; + } + + public void clear() + { + _slowAccessConsumers.clear(); + for (int i = 0; i < 16; i++) + { + _fastAccessConsumers[i] = null; + } + } + } + private static final class FlowControlIndicator { private volatile boolean _flowControl = true; @@ -426,9 +420,6 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } } - /** Flow control */ - private FlowControlIndicator _flowControl = new FlowControlIndicator(); - /** * Creates a new session on a connection. * @@ -443,7 +434,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic protected AMQSession(AMQConnection con, int channelId, boolean transacted, int acknowledgeMode, MessageFactoryRegistry messageFactoryRegistry, int defaultPrefetchHighMark, int defaultPrefetchLowMark) { - USE_AMQP_ENCODED_MAP_MESSAGE = con == null ? true : !con.isUseLegacyMapMessageFormat(); + _useAMQPEncodedMapMessage = con == null ? true : !con.isUseLegacyMapMessageFormat(); _strictAMQP = Boolean.parseBoolean(System.getProperties().getProperty(STRICT_AMQP, STRICT_AMQP_DEFAULT)); _strictAMQPFATAL = Boolean.parseBoolean(System.getProperties().getProperty(STRICT_AMQP_FATAL, STRICT_AMQP_FATAL_DEFAULT)); @@ -479,7 +470,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic { // If the session has been closed don't waste time creating a thread to do // flow control - if (!(_thisSession.isClosed() || _thisSession.isClosing())) + if (!(AMQSession.this.isClosed() || AMQSession.this.isClosing())) { // Only execute change if previous state // was False @@ -507,7 +498,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic { // If the session has been closed don't waste time creating a thread to do // flow control - if (!(_thisSession.isClosed() || _thisSession.isClosing())) + if (!(AMQSession.this.isClosed() || AMQSession.this.isClosing())) { // Only execute change if previous state // was true @@ -539,9 +530,9 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } // Add creation logging to tie in with the existing close logging - if (_logger.isInfoEnabled()) + if (_logger.isDebugEnabled()) { - _logger.info("Created session:" + this); + _logger.debug("Created session:" + this); } } @@ -730,17 +721,15 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic private void close(long timeout, boolean sendClose) throws JMSException { - if (_logger.isInfoEnabled()) + if (_logger.isDebugEnabled()) { - // StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - _logger.info("Closing session: " + this); // + ":" - // Arrays.asList(stackTrace).subList(3, stackTrace.length - 1)); + _logger.debug("Closing session: " + this); } // Ensure we only try and close an open session. - if (!_closed.getAndSet(true)) + if (!setClosed()) { - _closing.set(true); + setClosing(true); synchronized (getFailoverMutex()) { // We must close down all producers and consumers in an orderly fashion. This is the only method @@ -808,7 +797,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic if (e instanceof AMQDisconnectedException) { - if (_dispatcher != null) + if (_dispatcherThread != null) { // Failover failed and ain't coming back. Knife the dispatcher. _dispatcherThread.interrupt(); @@ -817,9 +806,9 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } //if we don't have an exception then we can perform closing operations - _closing.set(e == null); + setClosing(e == null); - if (!_closed.getAndSet(true)) + if (!setClosed()) { synchronized (_messageDeliveryLock) { @@ -903,11 +892,11 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic // Flush any pending messages for this consumerTag if (_dispatcher != null) { - _logger.info("Dispatcher is not null"); + _logger.debug("Dispatcher is not null"); } else { - _logger.info("Dispatcher is null so created stopped dispatcher"); + _logger.debug("Dispatcher is null so created stopped dispatcher"); startDispatcherIfNecessary(true); } @@ -918,18 +907,16 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic // 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. - - // consumer.markClosed(); + // 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.isInfoEnabled()) + if (_logger.isDebugEnabled()) { - _logger.info("Closing consumer:" + consumer.debugIdentity()); + _logger.debug("Closing consumer:" + consumer.debugIdentity()); } deregisterConsumer(consumer); @@ -953,6 +940,9 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic 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()) @@ -963,7 +953,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic checkNotClosed(); checkValidQueue(queue); - return new AMQQueueBrowser(this, (AMQQueue) queue, messageSelector); + return new AMQQueueBrowser(this, queue, messageSelector); } protected MessageConsumer createBrowserConsumer(Destination destination, String messageSelector, boolean noLocal) @@ -1043,7 +1033,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic { try { - handleAddressBasedDestination(dest,false,true); + handleAddressBasedDestination(dest,false,noLocal,true); if (dest.getAddressType() != AMQDestination.TOPIC_TYPE) { throw new JMSException("Durable subscribers can only be created for Topics"); @@ -1099,6 +1089,10 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic // 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. @@ -1159,7 +1153,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public MapMessage createMapMessage() throws JMSException { checkNotClosed(); - if (USE_AMQP_ENCODED_MAP_MESSAGE) + if (_useAMQPEncodedMapMessage) { AMQPEncodedMapMessage msg = new AMQPEncodedMapMessage(getMessageDelegateFactory()); msg.setAMQSession(this); @@ -1196,12 +1190,12 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public P createProducer(Destination destination) throws JMSException { - return createProducerImpl(destination, DEFAULT_MANDATORY, DEFAULT_IMMEDIATE); + return createProducerImpl(destination, null, null); } public P createProducer(Destination destination, boolean immediate) throws JMSException { - return createProducerImpl(destination, DEFAULT_MANDATORY, immediate); + return createProducerImpl(destination, null, immediate); } public P createProducer(Destination destination, boolean mandatory, boolean immediate) @@ -1600,7 +1594,6 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public MessageListener getMessageListener() throws JMSException { - // checkNotClosed(); return _messageListener; } @@ -1648,6 +1641,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic return (counter != null) && (counter.get() != 0); } + /** Indicates that warnings should be generated on violations of the strict AMQP. */ public boolean isStrictAMQP() { return _strictAMQP; @@ -1690,7 +1684,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic { AMQProtocolHandler protocolHandler = getProtocolHandler(); declareExchange(amqd, protocolHandler, false); - AMQShortString queueName = declareQueue(amqd, protocolHandler, false); + AMQShortString queueName = declareQueue(amqd, false); bindQueue(queueName, amqd.getRoutingKey(), new FieldTable(), amqd.getExchangeName(), amqd); } @@ -1886,31 +1880,6 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public void setMessageListener(MessageListener listener) throws JMSException { - // checkNotClosed(); - // - // if (_dispatcher != null && !_dispatcher.connectionStopped()) - // { - // throw new javax.njms.IllegalStateException("Attempt to set listener while session is started."); - // } - // - // // We are stopped - // for (Iterator<BasicMessageConsumer> i = _consumers.values().iterator(); i.hasNext();) - // { - // BasicMessageConsumer consumer = i.next(); - // - // if (consumer.isReceiving()) - // { - // throw new javax.njms.IllegalStateException("Another thread is already receiving synchronously."); - // } - // } - // - // _messageListener = listener; - // - // for (Iterator<BasicMessageConsumer> i = _consumers.values().iterator(); i.hasNext();) - // { - // i.next().setMessageListener(_messageListener); - // } - } /** @@ -2184,7 +2153,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic */ void markClosed() { - _closed.set(true); + setClosed(); _connection.deregisterSession(_channelId); markClosedProducersAndConsumers(); @@ -2199,7 +2168,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic { if (Thread.currentThread() == _dispatcherThread) { - while (!_closed.get() && !_queue.isEmpty()) + while (!super.isClosed() && !_queue.isEmpty()) { Dispatchable disp; try @@ -2247,6 +2216,58 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } } + void drainDispatchQueue() + { + if (Thread.currentThread() == _dispatcherThread) + { + while (!super.isClosed() && !_queue.isEmpty()) + { + Dispatchable disp; + try + { + disp = (Dispatchable) _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. * @@ -2289,7 +2310,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic */ void start() throws AMQException { - // Check if the session has perviously been started and suspended, in which case it must be unsuspended. + // Check if the session has previously been started and suspended, in which case it must be unsuspended. if (_startedAtLeastOnce.getAndSet(true)) { suspendChannel(false); @@ -2323,7 +2344,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } catch (AMQException e) { - _logger.info("Unsuspending channel threw an exception:" + e); + _logger.info("Unsuspending channel threw an exception:", e); } } } @@ -2346,12 +2367,12 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic throw new Error("Error creating Dispatcher thread",e); } _dispatcherThread.setName("Dispatcher-Channel-" + _channelId); - _dispatcherThread.setDaemon(true); + _dispatcherThread.setDaemon(DEAMON_DISPATCHER_THREAD); _dispatcher.setConnectionStopped(initiallyStopped); _dispatcherThread.start(); - if (_dispatcherLogger.isInfoEnabled()) + if (_dispatcherLogger.isDebugEnabled()) { - _dispatcherLogger.info(_dispatcherThread.getName() + " created"); + _dispatcherLogger.debug(_dispatcherThread.getName() + " created"); } } else @@ -2371,32 +2392,6 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } } - /* - * 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. - */ - /*private void bindQueue(AMQDestination amqd, AMQShortString queueName, AMQProtocolHandler protocolHandler, FieldTable ft) - throws AMQException, FailoverException - { - AMQFrame queueBind = - QueueBindBody.createAMQFrame(_channelId, getProtocolMajorVersion(), getProtocolMinorVersion(), ft, // arguments - amqd.getExchangeName(), // exchange - false, // nowait - queueName, // queue - amqd.getRoutingKey(), // routingKey - getTicket()); // ticket - - protocolHandler.syncWrite(queueBind, QueueBindOkBody.class); - }*/ - private void checkNotTransacted() throws JMSException { if (getTransacted()) @@ -2580,7 +2575,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic * @param queueName */ private void consumeFromQueue(C consumer, AMQShortString queueName, - AMQProtocolHandler protocolHandler, boolean nowait, MessageFilter messageSelector) throws AMQException, FailoverException + AMQProtocolHandler protocolHandler, boolean nowait) throws AMQException, FailoverException { int tagId = _nextTag++; @@ -2597,7 +2592,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic try { - sendConsume(consumer, queueName, protocolHandler, nowait, messageSelector, tagId); + sendConsume(consumer, queueName, protocolHandler, nowait, tagId); } catch (AMQException e) { @@ -2608,9 +2603,9 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } public abstract void sendConsume(C consumer, AMQShortString queueName, - AMQProtocolHandler protocolHandler, boolean nowait, MessageFilter messageSelector, int tag) throws AMQException, FailoverException; + AMQProtocolHandler protocolHandler, boolean nowait, int tag) throws AMQException, FailoverException; - private P createProducerImpl(final Destination destination, final boolean mandatory, final boolean immediate) + private P createProducerImpl(final Destination destination, final Boolean mandatory, final Boolean immediate) throws JMSException { return new FailoverRetrySupport<P, JMSException>( @@ -2639,8 +2634,8 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic }, _connection).execute(); } - public abstract P createMessageProducer(final Destination destination, final boolean mandatory, - final boolean immediate, final long producerId) throws JMSException; + public abstract P createMessageProducer(final Destination destination, final Boolean mandatory, + final Boolean immediate, final long producerId) throws JMSException; private void declareExchange(AMQDestination amqd, AMQProtocolHandler protocolHandler, boolean nowait) throws AMQException { @@ -2661,18 +2656,38 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public long getQueueDepth(final AMQDestination amqd) throws AMQException { - return new FailoverNoopSupport<Long, AMQException>( - new FailoverProtectedOperation<Long, AMQException>() - { - public Long execute() throws AMQException, FailoverException - { - return requestQueueDepth(amqd); - } - }, _connection).execute(); + 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) throws AMQException, FailoverException; + protected abstract Long requestQueueDepth(AMQDestination amqd, boolean sync) throws AMQException, FailoverException; /** * Declares the named exchange and type of exchange. @@ -2703,6 +2718,12 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public abstract void sendExchangeDeclare(final AMQShortString name, final AMQShortString type, final AMQProtocolHandler protocolHandler, final boolean nowait) throws AMQException, FailoverException; + + void declareQueuePassive(AMQDestination queue) throws AMQException + { + declareQueue(queue,false,false,true); + } + /** * Declares a queue for a JMS destination. * @@ -2712,27 +2733,35 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic * * <p/>Note that this operation automatically retries in the event of fail-over. * - * @param amqd The destination to declare as a queue. - * @param protocolHandler The protocol handler to communicate through. * + * @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 AMQProtocolHandler protocolHandler, + protected AMQShortString declareQueue(final AMQDestination amqd, final boolean noLocal) throws AMQException { - return declareQueue(amqd, protocolHandler, noLocal, false); + return declareQueue(amqd, noLocal, false); } - protected AMQShortString declareQueue(final AMQDestination amqd, final AMQProtocolHandler protocolHandler, + protected AMQShortString declareQueue(final AMQDestination amqd, final boolean noLocal, final boolean nowait) + throws AMQException + { + return declareQueue(amqd, noLocal, nowait, false); + } + + protected AMQShortString declareQueue(final AMQDestination amqd, + final boolean noLocal, final boolean nowait, final boolean passive) throws AMQException { - /*return new FailoverRetrySupport<AMQShortString, AMQException>(*/ + final AMQProtocolHandler protocolHandler = getProtocolHandler(); return new FailoverNoopSupport<AMQShortString, AMQException>( new FailoverProtectedOperation<AMQShortString, AMQException>() { @@ -2744,7 +2773,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic amqd.setQueueName(protocolHandler.generateQueueName()); } - sendQueueDeclare(amqd, protocolHandler, nowait); + sendQueueDeclare(amqd, protocolHandler, nowait, passive); return amqd.getAMQQueueName(); } @@ -2752,7 +2781,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } public abstract void sendQueueDeclare(final AMQDestination amqd, final AMQProtocolHandler protocolHandler, - final boolean nowait) throws AMQException, FailoverException; + final boolean nowait, boolean passive) throws AMQException, FailoverException; /** * Undeclares the specified queue. @@ -2882,18 +2911,18 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic if (amqd.getDestSyntax() == DestSyntax.ADDR) { - handleAddressBasedDestination(amqd,true,nowait); + handleAddressBasedDestination(amqd,true,consumer.isNoLocal(),nowait); } else { - if (DECLARE_EXCHANGES) + if (_declareExchanges) { declareExchange(amqd, protocolHandler, nowait); } - if (DECLARE_QUEUES || amqd.isNameRequired()) + if (_delareQueues || amqd.isNameRequired()) { - declareQueue(amqd, protocolHandler, consumer.isNoLocal(), nowait); + declareQueue(amqd, consumer.isNoLocal(), nowait); } bindQueue(amqd.getAMQQueueName(), amqd.getRoutingKey(), consumer.getArguments(), amqd.getExchangeName(), amqd, nowait); } @@ -2916,24 +2945,24 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic try { suspendChannel(true); - _logger.info( + _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); + _logger.info("Suspending channel threw an exception:", e); } } } } else { - _logger.info("Immediately prefetching existing messages to new consumer."); + _logger.debug("Immediately prefetching existing messages to new consumer."); } try { - consumeFromQueue(consumer, queueName, protocolHandler, nowait, consumer.getMessageSelectorFilter()); + consumeFromQueue(consumer, queueName, protocolHandler, nowait); } catch (FailoverException e) { @@ -2943,6 +2972,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public abstract void handleAddressBasedDestination(AMQDestination dest, boolean isConsumer, + boolean noLocal, boolean noWait) throws AMQException; private void registerProducer(long producerId, MessageProducer producer) @@ -2959,18 +2989,18 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic private void rejectMessagesForConsumerTag(int consumerTag, boolean requeue, boolean rejectAllConsumers) { Iterator messages = _queue.iterator(); - if (_logger.isInfoEnabled()) + if (_logger.isDebugEnabled()) { - _logger.info("Rejecting messages from _queue for Consumer tag(" + consumerTag + ") (PDispatchQ) requeue:" + _logger.debug("Rejecting messages from _queue for Consumer tag(" + consumerTag + ") (PDispatchQ) requeue:" + requeue); if (messages.hasNext()) { - _logger.info("Checking all messages in _queue for Consumer tag(" + consumerTag + ")"); + _logger.debug("Checking all messages in _queue for Consumer tag(" + consumerTag + ")"); } else { - _logger.info("No messages in _queue to reject"); + _logger.debug("No messages in _queue to reject"); } } while (messages.hasNext()) @@ -3013,7 +3043,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic private void resubscribeProducers() throws AMQException { ArrayList producers = new ArrayList(_producers.values()); - _logger.info(MessageFormat.format("Resubscribing producers = {0} producers.size={1}", producers, producers.size())); // FIXME: removeKey + _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(); @@ -3103,7 +3133,10 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public void setFlowControl(final boolean active) { _flowControl.setFlowControl(active); - _logger.warn("Broker enforced flow control " + (active ? "no longer in effect" : "has been enforced")); + if (_logger.isInfoEnabled()) + { + _logger.info("Broker enforced flow control " + (active ? "no longer in effect" : "has been enforced")); + } } public void checkFlowControl() throws InterruptedException, JMSException @@ -3112,17 +3145,20 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic synchronized (_flowControl) { while (!_flowControl.getFlowControl() && - (expiryTime == 0L ? (expiryTime = System.currentTimeMillis() + FLOW_CONTROL_WAIT_FAILURE) + (expiryTime == 0L ? (expiryTime = System.currentTimeMillis() + _flowControlWaitFailure) : expiryTime) >= System.currentTimeMillis() ) { - _flowControl.wait(FLOW_CONTROL_WAIT_PERIOD); - _logger.warn("Message send delayed by " + (System.currentTimeMillis() + FLOW_CONTROL_WAIT_FAILURE - expiryTime)/1000 + "s due to broker enforced flow control"); + _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 " + FLOW_CONTROL_WAIT_FAILURE/1000 + " seconds due to broker enforced flow control"); + throw new JMSException("Unable to send message for " + _flowControlWaitFailure /1000 + " seconds due to broker enforced flow control"); } } @@ -3154,7 +3190,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic private final AtomicBoolean _closed = new AtomicBoolean(false); private final Object _lock = new Object(); - private String dispatcherID = "" + System.identityHashCode(this); + private final String dispatcherID = "" + System.identityHashCode(this); public Dispatcher() { @@ -3169,6 +3205,11 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } + private AtomicBoolean getClosed() + { + return _closed; + } + public void rejectPending(C consumer) { synchronized (_lock) @@ -3220,7 +3261,6 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic else { // should perhaps clear the _SQ here. - // consumer._synchronousQueue.clear(); consumer.clearReceiveQueue(); } @@ -3266,13 +3306,11 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public void run() { - if (_dispatcherLogger.isInfoEnabled()) + if (_dispatcherLogger.isDebugEnabled()) { - _dispatcherLogger.info(_dispatcherThread.getName() + " started"); + _dispatcherLogger.debug(_dispatcherThread.getName() + " started"); } - UnprocessedMessage message; - // Allow disptacher to start stopped synchronized (_lock) { @@ -3284,7 +3322,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } catch (InterruptedException e) { - // ignore + Thread.currentThread().interrupt(); } } } @@ -3299,12 +3337,12 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } catch (InterruptedException e) { - // ignore + // ignored as run will exit immediately } - if (_dispatcherLogger.isInfoEnabled()) + if (_dispatcherLogger.isDebugEnabled()) { - _dispatcherLogger.info(_dispatcherThread.getName() + " thread terminating for channel " + _channelId + ":" + _thisSession); + _dispatcherLogger.debug(_dispatcherThread.getName() + " thread terminating for channel " + _channelId + ":" + AMQSession.this); } } @@ -3350,7 +3388,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } catch (InterruptedException e) { - // pass + Thread.currentThread().interrupt(); } if (!(message instanceof CloseConsumerMessage) @@ -3425,7 +3463,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic if (_logger.isDebugEnabled()) { _logger.debug("Rejecting message with delivery tag " + message.getDeliveryTag() - + " for closing consumer " + String.valueOf(consumer == null? null: consumer._consumerTag)); + + " for closing consumer " + String.valueOf(consumer == null? null: consumer.getConsumerTag())); } rejectMessage(message, true); } @@ -3443,30 +3481,6 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public abstract AMQMessageDelegateFactory getMessageDelegateFactory(); - /*public void requestAccess(AMQShortString realm, boolean exclusive, boolean passive, boolean active, boolean write, - boolean read) throws AMQException - { - getProtocolHandler().writeCommandFrameAndWaitForReply(AccessRequestBody.createAMQFrame(getChannelId(), - getProtocolMajorVersion(), getProtocolMinorVersion(), active, exclusive, passive, read, realm, write), - new BlockingMethodFrameListener(_channelId) - { - - public boolean processMethod(int channelId, AMQMethodBody frame) // throws AMQException - { - if (frame instanceof AccessRequestOkBody) - { - setTicket(((AccessRequestOkBody) frame).getTicket()); - - return true; - } - else - { - return false; - } - } - }); - }*/ - private class SuspenderRunner implements Runnable { private AtomicBoolean _suspend; @@ -3484,7 +3498,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic { // If the session has closed by the time we get here // then we should not attempt to write to the sesion/channel. - if (!(_thisSession.isClosed() || _thisSession.isClosing())) + if (!(AMQSession.this.isClosed() || AMQSession.this.isClosing())) { suspendChannel(_suspend.get()); } @@ -3492,11 +3506,11 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic } catch (AMQException e) { - _logger.warn("Unable to " + (_suspend.get() ? "suspend" : "unsuspend") + " session " + _thisSession + " due to: " + 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._closed)); + _logger.debug("Is the dispatcher closed?" + (_dispatcher == null ? "it's Null" : _dispatcher.getClosed())); } } } @@ -3510,7 +3524,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic @Override public boolean isClosed() { - return _closed.get() || _connection.isClosed(); + return super.isClosed() || _connection.isClosed(); } /** @@ -3522,12 +3536,12 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic @Override public boolean isClosing() { - return _closing.get()|| _connection.isClosing(); + return super.isClosing() || _connection.isClosing(); } public boolean isDeclareExchanges() { - return DECLARE_EXCHANGES; + return _declareExchanges; } JMSException toJMSException(String message, TransportException e) 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 index 7e257e0c20..e94099f066 100644 --- 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 @@ -20,7 +20,172 @@ */ package org.apache.qpid.client; -public interface AMQSessionAdapter +import javax.jms.*; +import java.io.Serializable; + +public abstract class AMQSessionAdapter<T extends Session> implements Session { - public AMQSession getSession(); + 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/AMQSession_0_10.java b/qpid/java/client/src/main/java/org/apache/qpid/client/AMQSession_0_10.java index 8395c8f4b7..3902c726f3 100644 --- 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 @@ -17,11 +17,6 @@ */ 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.Collections; @@ -34,10 +29,8 @@ 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.apache.qpid.AMQException; import org.apache.qpid.client.AMQDestination.AddressOption; import org.apache.qpid.client.AMQDestination.Binding; @@ -55,11 +48,14 @@ import org.apache.qpid.client.messaging.address.Node.ExchangeNode; import org.apache.qpid.client.messaging.address.Node.QueueNode; import org.apache.qpid.client.protocol.AMQProtocolHandler; import org.apache.qpid.exchange.ExchangeDefaults; -import org.apache.qpid.filter.MessageFilter; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.FieldTable; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.transport.*; +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 org.apache.qpid.util.Serial; import org.apache.qpid.util.Strings; import org.slf4j.Logger; @@ -78,6 +74,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic private static final Logger _logger = LoggerFactory.getLogger(AMQSession_0_10.class); private static Timer timer = new Timer("ack-flusher", true); + private static class Flusher extends TimerTask { @@ -120,7 +117,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic private AMQException _currentException; // a ref on the qpid connection - protected org.apache.qpid.transport.Connection _qpidConnection; + private org.apache.qpid.transport.Connection _qpidConnection; private long maxAckDelay = Long.getLong("qpid.session.max_ack_delay", 1000); private TimerTask flushTask = null; @@ -163,7 +160,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic _qpidSession = _qpidConnection.createSession(name,1); } _qpidSession.setSessionListener(this); - if (_transacted) + if (isTransacted()) { _qpidSession.txSelect(); _qpidSession.setTransacted(true); @@ -214,6 +211,11 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic } } + protected Connection getQpidConnection() + { + return _qpidConnection; + } + //------- overwritten methods of class AMQSession void failoverPrep() @@ -234,17 +236,17 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic { if (_logger.isDebugEnabled()) { - _logger.debug("Sending ack for delivery tag " + deliveryTag + " on session " + _channelId); + _logger.debug("Sending ack for delivery tag " + deliveryTag + " on session " + getChannelId()); } // acknowledge this message if (multiple) { - for (Long messageTag : _unacknowledgedMessageTags) + for (Long messageTag : getUnacknowledgedMessageTags()) { if( messageTag <= deliveryTag ) { addUnacked(messageTag.intValue()); - _unacknowledgedMessageTags.remove(messageTag); + getUnacknowledgedMessageTags().remove(messageTag); } } //empty the list of unack messages @@ -253,12 +255,12 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic else { addUnacked((int) deliveryTag); - _unacknowledgedMessageTags.remove(deliveryTag); + getUnacknowledgedMessageTags().remove(deliveryTag); } long prefetch = getAMQConnection().getMaxPrefetch(); - if (unackedCount >= prefetch/2 || maxAckDelay <= 0 || _acknowledgeMode == javax.jms.Session.AUTO_ACKNOWLEDGE) + if (unackedCount >= prefetch/2 || maxAckDelay <= 0 || getAcknowledgeMode() == javax.jms.Session.AUTO_ACKNOWLEDGE) { flushAcknowledgments(); } @@ -276,7 +278,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic if (unackedCount > 0) { messageAcknowledge - (unacked, _acknowledgeMode != org.apache.qpid.jms.Session.NO_ACKNOWLEDGE,setSyncBit); + (unacked, getAcknowledgeMode() != org.apache.qpid.jms.Session.NO_ACKNOWLEDGE,setSyncBit); clearUnacked(); } } @@ -444,8 +446,8 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic { // release all unacked messages RangeSet all = RangeSetFactory.createRangeSet(); - RangeSet delivered = gatherRangeSet(_unacknowledgedMessageTags); - RangeSet prefetched = gatherRangeSet(_prefetchedMessageTags); + RangeSet delivered = gatherRangeSet(getUnacknowledgedMessageTags()); + RangeSet prefetched = gatherRangeSet(getPrefetchedMessageTags()); for (Iterator<Range> deliveredIter = delivered.iterator(); deliveredIter.hasNext();) { Range range = deliveredIter.next(); @@ -526,9 +528,9 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic { final AMQProtocolHandler protocolHandler = getProtocolHandler(); - return new BasicMessageConsumer_0_10(_channelId, _connection, destination, messageSelector, noLocal, - _messageFactoryRegistry, this, protocolHandler, rawSelector, prefetchHigh, - prefetchLow, exclusive, _acknowledgeMode, noConsume, autoClose); + return new BasicMessageConsumer_0_10(getChannelId(), getAMQConnection(), destination, messageSelector, noLocal, + getMessageFactoryRegistry(), this, protocolHandler, rawSelector, prefetchHigh, + prefetchLow, exclusive, getAcknowledgeMode(), noConsume, autoClose); } /** @@ -593,7 +595,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic * Registers the consumer with the broker */ public void sendConsume(BasicMessageConsumer_0_10 consumer, AMQShortString queueName, AMQProtocolHandler protocolHandler, - boolean nowait, MessageFilter messageSelector, int tag) + boolean nowait, int tag) throws AMQException, FailoverException { boolean preAcquire = consumer.isPreAcquire(); @@ -630,7 +632,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic getQpidSession().messageFlow(consumerTag, MessageCreditUnit.BYTE, 0xFFFFFFFF, Option.UNRELIABLE); - if(capacity > 0 && _dispatcher != null && (isStarted() || _immediatePrefetch)) + if(capacity > 0 && getDispatcher() != null && (isStarted() || isImmediatePrefetch())) { // set the flow getQpidSession().messageFlow(consumerTag, @@ -648,12 +650,12 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic /** * 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 + 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(_connection, (AMQDestination) destination, _transacted, _channelId, this, + return new BasicMessageProducer_0_10(getAMQConnection(), (AMQDestination) destination, isTransacted(), getChannelId(), this, getProtocolHandler(), producerId, immediate, mandatory); } catch (AMQException e) @@ -719,7 +721,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic * Declare a queue with the given queueName */ public void sendQueueDeclare(final AMQDestination amqd, final AMQProtocolHandler protocolHandler, - final boolean nowait) + final boolean nowait, boolean passive) throws AMQException, FailoverException { // do nothing this is only used by 0_8 @@ -729,7 +731,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic * Declare a queue with the given queueName */ public AMQShortString send0_10QueueDeclare(final AMQDestination amqd, final AMQProtocolHandler protocolHandler, - final boolean noLocal, final boolean nowait) + final boolean noLocal, final boolean nowait, boolean passive) throws AMQException { AMQShortString queueName; @@ -755,13 +757,20 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic getQpidSession().queueDeclare(queueName.toString(), "" , arguments, amqd.isAutoDelete() ? Option.AUTO_DELETE : Option.NONE, amqd.isDurable() ? Option.DURABLE : Option.NONE, - amqd.isExclusive() ? Option.EXCLUSIVE : Option.NONE); + amqd.isExclusive() ? Option.EXCLUSIVE : Option.NONE, + passive ? Option.PASSIVE : Option.NONE); } else { QueueNode node = (QueueNode)amqd.getSourceNode(); + 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() , - node.getDeclareArgs(), + arguments, node.isAutoDelete() ? Option.AUTO_DELETE : Option.NONE, node.isDurable() ? Option.DURABLE : Option.NONE, node.isExclusive() ? Option.EXCLUSIVE : Option.NONE); @@ -795,15 +804,16 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic { if (suspend) { - for (BasicMessageConsumer consumer : _consumers.values()) + for (BasicMessageConsumer consumer : getConsumers().values()) { getQpidSession().messageStop(String.valueOf(consumer.getConsumerTag()), Option.UNRELIABLE); } + sync(); } else { - for (BasicMessageConsumer_0_10 consumer : _consumers.values()) + for (BasicMessageConsumer_0_10 consumer : getConsumers().values()) { String consumerTag = String.valueOf(consumer.getConsumerTag()); //only set if msg list is null @@ -918,11 +928,12 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic return getCurrentException(); } - protected AMQShortString declareQueue(final AMQDestination amqd, final AMQProtocolHandler protocolHandler, - final boolean noLocal, final boolean nowait) + protected AMQShortString declareQueue(final AMQDestination amqd, + final boolean noLocal, final boolean nowait, final boolean passive) throws AMQException { - /*return new FailoverRetrySupport<AMQShortString, AMQException>(*/ + final AMQProtocolHandler protocolHandler = getProtocolHandler(); + return new FailoverNoopSupport<AMQShortString, AMQException>( new FailoverProtectedOperation<AMQShortString, AMQException>() { @@ -939,14 +950,18 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic amqd.setQueueName(new AMQShortString( binddingKey + "@" + amqd.getExchangeName().toString() + "_" + UUID.randomUUID())); } - return send0_10QueueDeclare(amqd, protocolHandler, noLocal, nowait); + return send0_10QueueDeclare(amqd, protocolHandler, noLocal, nowait, passive); } - }, _connection).execute(); + }, getAMQConnection()).execute(); } - protected Long requestQueueDepth(AMQDestination amqd) + protected Long requestQueueDepth(AMQDestination amqd, boolean sync) { flushAcknowledgments(); + if (sync) + { + getQpidSession().sync(); + } return getQpidSession().queueQuery(amqd.getQueueName()).get().getMessageCount(); } @@ -968,8 +983,8 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic protected void sendTxCompletionsIfNecessary() { // this is a heuristic, we may want to have that configurable - if (_txSize > 0 && (_connection.getMaxPrefetch() == 1 || - _connection.getMaxPrefetch() != 0 && _txSize % (_connection.getMaxPrefetch() / 2) == 0)) + 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); @@ -1039,7 +1054,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic AMQException amqe = new AMQException(AMQConstant.getConstant(code), se.getMessage(), se.getCause()); _currentException = amqe; } - _connection.exceptionReceived(_currentException); + getAMQConnection().exceptionReceived(_currentException); } public AMQMessageDelegateFactory getMessageDelegateFactory() @@ -1156,13 +1171,14 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic @SuppressWarnings("deprecation") public void handleAddressBasedDestination(AMQDestination dest, boolean isConsumer, + boolean noLocal, boolean noWait) throws AMQException { - if (dest.isAddressResolved() && dest.isResolvedAfter(_connection.getLastFailoverTime())) + if (dest.isAddressResolved() && dest.isResolvedAfter(getAMQConnection().getLastFailoverTime())) { if (isConsumer && AMQDestination.TOPIC_TYPE == dest.getAddressType()) { - createSubscriptionQueue(dest); + createSubscriptionQueue(dest,noLocal); } } else @@ -1191,7 +1207,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic else if(createNode) { setLegacyFiledsForQueueType(dest); - send0_10QueueDeclare(dest,null,false,noWait); + send0_10QueueDeclare(dest,null,noLocal,noWait, false); sendQueueBind(dest.getAMQQueueName(), dest.getRoutingKey(), null,dest.getExchangeName(),dest, false); break; @@ -1206,7 +1222,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic verifySubject(dest); if (isConsumer && !isQueueExist(dest,(QueueNode)dest.getSourceNode(),true)) { - createSubscriptionQueue(dest); + createSubscriptionQueue(dest, noLocal); } break; } @@ -1221,7 +1237,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic false); if (isConsumer && !isQueueExist(dest,(QueueNode)dest.getSourceNode(),true)) { - createSubscriptionQueue(dest); + createSubscriptionQueue(dest,noLocal); } break; } @@ -1284,7 +1300,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic } } - private void createSubscriptionQueue(AMQDestination dest) throws AMQException + private void createSubscriptionQueue(AMQDestination dest, boolean noLocal) throws AMQException { QueueNode node = (QueueNode)dest.getSourceNode(); // source node is never null @@ -1297,11 +1313,11 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic } node.setExclusive(true); node.setAutoDelete(!node.isDurable()); - send0_10QueueDeclare(dest,null,false,true); - node.addBinding(new Binding(dest.getAddressName(), - dest.getQueueName(),// should have one by now - dest.getSubject(), - Collections.<String,Object>emptyMap())); + send0_10QueueDeclare(dest,null,noLocal,true, false); + getQpidSession().exchangeBind(dest.getQueueName(), + dest.getAddressName(), + dest.getSubject(), + Collections.<String,Object>emptyMap()); sendQueueBind(dest.getAMQQueueName(), dest.getRoutingKey(), null,dest.getExchangeName(),dest, false); } @@ -1328,7 +1344,7 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic protected void acknowledgeImpl() { - RangeSet ranges = gatherRangeSet(_unacknowledgedMessageTags); + RangeSet ranges = gatherRangeSet(getUnacknowledgedMessageTags()); if(ranges.size() > 0 ) { @@ -1344,15 +1360,53 @@ public class AMQSession_0_10 extends AMQSession<BasicMessageConsumer_0_10, Basic // return the first <total number of msgs received on session> // messages sent by the brokers following the first rollback // after failover - _highestDeliveryTag.set(-1); + 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; - _unacknowledgedMessageTags.clear(); - _prefetchedMessageTags.clear(); + getUnacknowledgedMessageTags().clear(); + getPrefetchedMessageTags().clear(); super.resubscribe(); getQpidSession().sync(); } + + @Override + void stop() throws AMQException + { + super.stop(); + setUsingDispatcherForCleanup(true); + drainDispatchQueue(); + setUsingDispatcherForCleanup(false); + + for (BasicMessageConsumer consumer : getConsumers().values()) + { + 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(); + } + } 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 index 7daebbff04..8ab23a240e 100644 --- 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 @@ -21,13 +21,8 @@ package org.apache.qpid.client; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.ArrayList; -import java.util.Map; - -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; @@ -43,44 +38,20 @@ 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.filter.MessageFilter; -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.BasicConsumeBody; -import org.apache.qpid.framing.BasicConsumeOkBody; -import org.apache.qpid.framing.BasicQosBody; -import org.apache.qpid.framing.BasicQosOkBody; -import org.apache.qpid.framing.BasicRecoverBody; -import org.apache.qpid.framing.BasicRecoverOkBody; -import org.apache.qpid.framing.BasicRecoverSyncBody; -import org.apache.qpid.framing.BasicRecoverSyncOkBody; -import org.apache.qpid.framing.BasicRejectBody; -import org.apache.qpid.framing.ChannelCloseOkBody; -import org.apache.qpid.framing.ChannelFlowBody; -import org.apache.qpid.framing.ChannelFlowOkBody; -import org.apache.qpid.framing.ExchangeBoundOkBody; -import org.apache.qpid.framing.ExchangeDeclareBody; -import org.apache.qpid.framing.ExchangeDeclareOkBody; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.ProtocolVersion; -import org.apache.qpid.framing.QueueBindOkBody; -import org.apache.qpid.framing.QueueDeclareBody; -import org.apache.qpid.framing.QueueDeclareOkBody; -import org.apache.qpid.framing.QueueDeleteBody; -import org.apache.qpid.framing.QueueDeleteOkBody; -import org.apache.qpid.framing.TxCommitOkBody; -import org.apache.qpid.framing.TxRollbackBody; -import org.apache.qpid.framing.TxRollbackOkBody; +import org.apache.qpid.framing.*; import org.apache.qpid.framing.amqp_0_9.MethodRegistry_0_9; import org.apache.qpid.framing.amqp_0_91.MethodRegistry_0_91; 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.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import javax.jms.Destination; +import javax.jms.JMSException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMessageProducer_0_8> { @@ -131,7 +102,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe { while (true) { - Long tag = _unacknowledgedMessageTags.poll(); + Long tag = getUnacknowledgedMessageTags().poll(); if (tag == null) { break; @@ -145,15 +116,15 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe { BasicAckBody body = getMethodRegistry().createBasicAckBody(deliveryTag, multiple); - final AMQFrame ackFrame = body.generateFrame(_channelId); + final AMQFrame ackFrame = body.generateFrame(getChannelId()); if (_logger.isDebugEnabled()) { - _logger.debug("Sending ack for delivery tag " + deliveryTag + " on channel " + _channelId); + _logger.debug("Sending ack for delivery tag " + deliveryTag + " on channel " + getChannelId()); } getProtocolHandler().writeFrame(ackFrame, !isTransacted()); - _unacknowledgedMessageTags.remove(deliveryTag); + getUnacknowledgedMessageTags().remove(deliveryTag); } public void sendQueueBind(final AMQShortString queueName, final AMQShortString routingKey, final FieldTable arguments, @@ -162,7 +133,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe { getProtocolHandler().syncWrite(getProtocolHandler().getMethodRegistry().createQueueBindBody (getTicket(),queueName,exchangeName,routingKey,false,arguments). - generateFrame(_channelId), QueueBindOkBody.class); + generateFrame(getChannelId()), QueueBindOkBody.class); } public void sendClose(long timeout) throws AMQException, FailoverException @@ -179,7 +150,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe getProtocolHandler().closeSession(this); getProtocolHandler().syncWrite(getProtocolHandler().getMethodRegistry().createChannelCloseBody(AMQConstant.REPLY_SUCCESS.getCode(), - new AMQShortString("JMS client closing channel"), 0, 0).generateFrame(_channelId), + 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. @@ -191,7 +162,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe // Acknowledge all delivered messages while (true) { - Long tag = _deliveredMessageTags.poll(); + Long tag = getDeliveredMessageTags().poll(); if (tag == null) { break; @@ -202,7 +173,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe final AMQProtocolHandler handler = getProtocolHandler(); - handler.syncWrite(getProtocolHandler().getMethodRegistry().createTxCommitBody().generateFrame(_channelId), TxCommitOkBody.class); + handler.syncWrite(getProtocolHandler().getMethodRegistry().createTxCommitBody().generateFrame(getChannelId()), TxCommitOkBody.class); } public void sendCreateQueue(AMQShortString name, final boolean autoDelete, final boolean durable, final boolean exclusive, final Map<String, Object> arguments) throws AMQException, @@ -218,22 +189,22 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe } } QueueDeclareBody body = getMethodRegistry().createQueueDeclareBody(getTicket(),name,false,durable,exclusive,autoDelete,false,table); - AMQFrame queueDeclare = body.generateFrame(_channelId); + AMQFrame queueDeclare = body.generateFrame(getChannelId()); getProtocolHandler().syncWrite(queueDeclare, QueueDeclareOkBody.class); } public void sendRecover() throws AMQException, FailoverException { enforceRejectBehaviourDuringRecover(); - _prefetchedMessageTags.clear(); - _unacknowledgedMessageTags.clear(); + 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); - _connection.getProtocolHandler().writeFrame(body.generateFrame(_channelId)); + getAMQConnection().getProtocolHandler().writeFrame(body.generateFrame(getChannelId())); _logger.warn("Session Recover cannot be guaranteed with STRICT_AMQP. Messages may arrive out of order."); } else @@ -243,17 +214,17 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe if(getProtocolHandler().getProtocolVersion().equals(ProtocolVersion.v8_0)) { BasicRecoverBody body = getMethodRegistry().createBasicRecoverBody(false); - _connection.getProtocolHandler().syncWrite(body.generateFrame(_channelId), BasicRecoverOkBody.class); + getAMQConnection().getProtocolHandler().syncWrite(body.generateFrame(getChannelId()), BasicRecoverOkBody.class); } else if(getProtocolVersion().equals(ProtocolVersion.v0_9)) { BasicRecoverSyncBody body = ((MethodRegistry_0_9)getMethodRegistry()).createBasicRecoverSyncBody(false); - _connection.getProtocolHandler().syncWrite(body.generateFrame(_channelId), BasicRecoverSyncOkBody.class); + getAMQConnection().getProtocolHandler().syncWrite(body.generateFrame(getChannelId()), BasicRecoverSyncOkBody.class); } else if(getProtocolVersion().equals(ProtocolVersion.v0_91)) { BasicRecoverSyncBody body = ((MethodRegistry_0_91)getMethodRegistry()).createBasicRecoverSyncBody(false); - _connection.getProtocolHandler().syncWrite(body.generateFrame(_channelId), BasicRecoverSyncOkBody.class); + getAMQConnection().getProtocolHandler().syncWrite(body.generateFrame(getChannelId()), BasicRecoverSyncOkBody.class); } else { @@ -266,9 +237,9 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe { if (_logger.isDebugEnabled()) { - _logger.debug("Prefetched message: _unacknowledgedMessageTags :" + _unacknowledgedMessageTags); + _logger.debug("Prefetched message: _unacknowledgedMessageTags :" + getUnacknowledgedMessageTags()); } - ArrayList<BasicMessageConsumer_0_8> consumersToCheck = new ArrayList<BasicMessageConsumer_0_8>(_consumers.values()); + ArrayList<BasicMessageConsumer_0_8> consumersToCheck = new ArrayList<BasicMessageConsumer_0_8>(getConsumers().values()); boolean messageListenerFound = false; boolean serverRejectBehaviourFound = false; for(BasicMessageConsumer_0_8 consumer : consumersToCheck) @@ -287,7 +258,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe if (serverRejectBehaviourFound) { //reject(false) any messages we don't want returned again - switch(_acknowledgeMode) + switch(getAcknowledgeMode()) { case Session.DUPS_OK_ACKNOWLEDGE: case Session.AUTO_ACKNOWLEDGE: @@ -296,7 +267,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe break; } case Session.CLIENT_ACKNOWLEDGE: - for(Long tag : _unacknowledgedMessageTags) + for(Long tag : getUnacknowledgedMessageTags()) { rejectMessage(tag, false); } @@ -314,7 +285,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe // 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 : _consumers.values()) + for (BasicMessageConsumer_0_8 consumer : getConsumers().values()) { if(RejectBehaviour.SERVER.equals(consumer.getRejectBehaviour())) { @@ -326,7 +297,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe while (true) { - Long tag = _deliveredMessageTags.poll(); + Long tag = getDeliveredMessageTags().poll(); if (tag == null) { break; @@ -338,8 +309,8 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe public void rejectMessage(long deliveryTag, boolean requeue) { - if ((_acknowledgeMode == CLIENT_ACKNOWLEDGE) || (_acknowledgeMode == SESSION_TRANSACTED)|| - ((_acknowledgeMode == AUTO_ACKNOWLEDGE || _acknowledgeMode == DUPS_OK_ACKNOWLEDGE ) && hasMessageListeners())) + if ((getAcknowledgeMode() == CLIENT_ACKNOWLEDGE) || (getAcknowledgeMode() == SESSION_TRANSACTED)|| + ((getAcknowledgeMode() == AUTO_ACKNOWLEDGE || getAcknowledgeMode() == DUPS_OK_ACKNOWLEDGE ) && hasMessageListeners())) { if (_logger.isDebugEnabled()) { @@ -347,9 +318,9 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe } BasicRejectBody body = getMethodRegistry().createBasicRejectBody(deliveryTag, requeue); - AMQFrame frame = body.generateFrame(_channelId); + AMQFrame frame = body.generateFrame(getChannelId()); - _connection.getProtocolHandler().writeFrame(frame); + getAMQConnection().getProtocolHandler().writeFrame(frame); } } @@ -370,12 +341,12 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe public AMQMethodEvent execute() throws AMQException, FailoverException { AMQFrame boundFrame = getProtocolHandler().getMethodRegistry().createExchangeBoundBody - (exchangeName, routingKey, queueName).generateFrame(_channelId); + (exchangeName, routingKey, queueName).generateFrame(getChannelId()); return getProtocolHandler().syncWrite(boundFrame, ExchangeBoundOkBody.class); } - }, _connection).execute(); + }, getAMQConnection()).execute(); // Extract and return the response code from the query. ExchangeBoundOkBody responseBody = (ExchangeBoundOkBody) response.getMethod(); @@ -392,7 +363,6 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe AMQShortString queueName, AMQProtocolHandler protocolHandler, boolean nowait, - MessageFilter messageSelector, int tag) throws AMQException, FailoverException { @@ -406,7 +376,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe consumer.getArguments()); - AMQFrame jmsConsume = body.generateFrame(_channelId); + AMQFrame jmsConsume = body.generateFrame(getChannelId()); if (nowait) { @@ -424,17 +394,25 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe ExchangeDeclareBody body = getMethodRegistry().createExchangeDeclareBody(getTicket(),name,type, name.toString().startsWith("amq."), false,false,false,false,null); - AMQFrame exchangeDeclare = body.generateFrame(_channelId); + AMQFrame exchangeDeclare = body.generateFrame(getChannelId()); protocolHandler.syncWrite(exchangeDeclare, ExchangeDeclareOkBody.class); } public void sendQueueDeclare(final AMQDestination amqd, final AMQProtocolHandler protocolHandler, - final boolean nowait) throws AMQException, FailoverException + final boolean nowait, boolean passive) throws AMQException, FailoverException { - QueueDeclareBody body = getMethodRegistry().createQueueDeclareBody(getTicket(),amqd.getAMQQueueName(),false,amqd.isDurable(),amqd.isExclusive(),amqd.isAutoDelete(),false,null); + QueueDeclareBody body = + getMethodRegistry().createQueueDeclareBody(getTicket(), + amqd.getAMQQueueName(), + passive, + amqd.isDurable(), + amqd.isExclusive(), + amqd.isAutoDelete(), + false, + null); - AMQFrame queueDeclare = body.generateFrame(_channelId); + AMQFrame queueDeclare = body.generateFrame(getChannelId()); protocolHandler.syncWrite(queueDeclare, QueueDeclareOkBody.class); } @@ -446,7 +424,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe false, false, true); - AMQFrame queueDeleteFrame = body.generateFrame(_channelId); + AMQFrame queueDeleteFrame = body.generateFrame(getChannelId()); getProtocolHandler().syncWrite(queueDeleteFrame, QueueDeleteOkBody.class); } @@ -454,8 +432,8 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe public void sendSuspendChannel(boolean suspend) throws AMQException, FailoverException { ChannelFlowBody body = getMethodRegistry().createChannelFlowBody(!suspend); - AMQFrame channelFlowFrame = body.generateFrame(_channelId); - _connection.getProtocolHandler().syncWrite(channelFlowFrame, ChannelFlowOkBody.class); + AMQFrame channelFlowFrame = body.generateFrame(getChannelId()); + getAMQConnection().getProtocolHandler().syncWrite(channelFlowFrame, ChannelFlowOkBody.class); } public BasicMessageConsumer_0_8 createMessageConsumer(final AMQDestination destination, final int prefetchHigh, @@ -464,18 +442,18 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe { final AMQProtocolHandler protocolHandler = getProtocolHandler(); - return new BasicMessageConsumer_0_8(_channelId, _connection, destination, messageSelector, noLocal, - _messageFactoryRegistry,this, protocolHandler, arguments, prefetchHigh, prefetchLow, - exclusive, _acknowledgeMode, noConsume, autoClose); + return new BasicMessageConsumer_0_8(getChannelId(), getAMQConnection(), destination, messageSelector, noLocal, + getMessageFactoryRegistry(),this, protocolHandler, 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 + public BasicMessageProducer_0_8 createMessageProducer(final Destination destination, final Boolean mandatory, + final Boolean immediate, long producerId) throws JMSException { try { - return new BasicMessageProducer_0_8(_connection, (AMQDestination) destination, _transacted, _channelId, + return new BasicMessageProducer_0_8(getAMQConnection(), (AMQDestination) destination, isTransacted(), getChannelId(), this, getProtocolHandler(), producerId, immediate, mandatory); } catch (AMQException e) @@ -505,7 +483,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe private void returnBouncedMessage(final ReturnMessage msg) { - _connection.performConnectionTask(new Runnable() + getAMQConnection().performConnectionTask(new Runnable() { public void run() { @@ -513,8 +491,8 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe { // Bounced message is processed here, away from the mina thread AbstractJMSMessage bouncedMessage = - _messageFactoryRegistry.createMessage(0, false, msg.getExchange(), - msg.getRoutingKey(), msg.getContentHeader(), msg.getBodies(),_queueDestinationCache,_topicDestinationCache); + getMessageFactoryRegistry().createMessage(0, false, msg.getExchange(), + msg.getRoutingKey(), msg.getContentHeader(), msg.getBodies(), _queueDestinationCache, _topicDestinationCache); AMQConstant errorCode = AMQConstant.getConstant(msg.getReplyCode()); AMQShortString reason = msg.getReplyText(); _logger.debug("Message returned with error code " + errorCode + " (" + reason + ")"); @@ -522,20 +500,17 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe // @TODO should this be moved to an exception handler of sorts. Somewhere errors are converted to correct execeptions. if (errorCode == AMQConstant.NO_CONSUMERS) { - _connection.exceptionReceived(new AMQNoConsumersException("Error: " + reason, bouncedMessage, null)); - } - else if (errorCode == AMQConstant.NO_ROUTE) + getAMQConnection().exceptionReceived(new AMQNoConsumersException("Error: " + reason, bouncedMessage, null)); + } else if (errorCode == AMQConstant.NO_ROUTE) { - _connection.exceptionReceived(new AMQNoRouteException("Error: " + reason, bouncedMessage, null)); - } - else + getAMQConnection().exceptionReceived(new AMQNoRouteException("Error: " + reason, bouncedMessage, null)); + } else { - _connection.exceptionReceived( + getAMQConnection().exceptionReceived( new AMQUndeliveredException(errorCode, "Error: " + reason, bouncedMessage, null)); } - } - catch (Exception e) + } catch (Exception e) { _logger.error( "Caught exception trying to raise undelivered message exception (dump follows) - ignoring...", @@ -571,7 +546,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe return null; } - }, _connection).execute(); + }, getAMQConnection()).execute(); } public DestinationCache<AMQQueue> getQueueDestinationCache() @@ -607,9 +582,18 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe return matches; } + public long getMessageCount() + { + return _messageCount; + } + + public long getConsumerCount() + { + return _consumerCount; + } } - protected Long requestQueueDepth(AMQDestination amqd) throws AMQException, FailoverException + protected Long requestQueueDepth(AMQDestination amqd, boolean sync) throws AMQException, FailoverException { AMQFrame queueDeclare = getMethodRegistry().createQueueDeclareBody(getTicket(), @@ -619,10 +603,10 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe amqd.isExclusive(), amqd.isAutoDelete(), false, - null).generateFrame(_channelId); + null).generateFrame(getChannelId()); QueueDeclareOkHandler okHandler = new QueueDeclareOkHandler(); getProtocolHandler().writeCommandFrameAndWaitForReply(queueDeclare, okHandler); - return okHandler._messageCount; + return okHandler.getMessageCount(); } protected boolean tagLE(long tag1, long tag2) @@ -647,6 +631,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe public void handleAddressBasedDestination(AMQDestination dest, boolean isConsumer, + boolean noLocal, boolean noWait) throws AMQException { throw new UnsupportedOperationException("The new addressing based sytanx is " @@ -683,7 +668,7 @@ public class AMQSession_0_8 extends AMQSession<BasicMessageConsumer_0_8, BasicMe { // if the Connection has closed then we should throw any exception that // has occurred that we were not waiting for - AMQStateManager manager = _connection.getProtocolHandler() + AMQStateManager manager = getAMQConnection().getProtocolHandler() .getStateManager(); Exception e = manager.getLastException(); 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 index 28f838057e..11145e17b2 100644 --- 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 @@ -20,12 +20,11 @@ */ package org.apache.qpid.client; -import java.util.UUID; +import org.apache.qpid.framing.AMQShortString; import javax.jms.JMSException; import javax.jms.TemporaryQueue; - -import org.apache.qpid.framing.AMQShortString; +import java.util.UUID; /** AMQ implementation of a TemporaryQueue. */ final class AMQTemporaryQueue extends AMQQueue implements TemporaryQueue, TemporaryDestination 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 index 5969d9a5a5..f09ef5e01d 100644 --- 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 @@ -20,17 +20,16 @@ */ 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; +import javax.jms.InvalidDestinationException; +import javax.jms.JMSException; +import javax.jms.Topic; +import java.net.URISyntaxException; + public class AMQTopic extends AMQDestination implements Topic { public AMQTopic(String address) throws URISyntaxException @@ -175,7 +174,7 @@ public class AMQTopic extends AMQDestination implements Topic } else { - return _exchangeName; + return super.getExchangeName(); } } 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 index ec482a8f79..0f44ac5501 100644 --- 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 @@ -20,182 +20,30 @@ */ package org.apache.qpid.client; -import java.io.Serializable; - -import javax.jms.BytesMessage; -import javax.jms.Destination; +import javax.jms.*; import javax.jms.IllegalStateException; -import javax.jms.JMSException; -import javax.jms.MapMessage; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.MessageProducer; -import javax.jms.ObjectMessage; -import javax.jms.Queue; -import javax.jms.QueueBrowser; -import javax.jms.Session; -import javax.jms.StreamMessage; -import javax.jms.TemporaryQueue; -import javax.jms.TemporaryTopic; -import javax.jms.TextMessage; -import javax.jms.Topic; -import javax.jms.TopicPublisher; -import javax.jms.TopicSession; -import javax.jms.TopicSubscriber; -public class AMQTopicSessionAdaptor implements TopicSession, AMQSessionAdapter +class AMQTopicSessionAdaptor extends AMQSessionAdapter<TopicSession> implements TopicSession { - protected final AMQSession _session; - - public AMQTopicSessionAdaptor(Session session) - { - _session = (AMQSession) session; - } - public Topic createTopic(String string) throws JMSException + public AMQTopicSessionAdaptor(TopicSession session) { - return _session.createTopic(string); + super(session); } public TopicSubscriber createSubscriber(Topic topic) throws JMSException { - return _session.createSubscriber(topic); + return getSession().createSubscriber(topic); } public TopicSubscriber createSubscriber(Topic topic, String string, boolean b) throws JMSException { - return _session.createSubscriber(topic, string, b); - } - - public TopicSubscriber createDurableSubscriber(Topic topic, String string) throws JMSException - { - return _session.createDurableSubscriber(topic, string); - } - - public TopicSubscriber createDurableSubscriber(Topic topic, String string, String string1, boolean b) throws JMSException - { - return _session.createDurableSubscriber(topic, string, string1, b); + return getSession().createSubscriber(topic, string, b); } public TopicPublisher createPublisher(Topic topic) throws JMSException { - return _session.createPublisher(topic); - } - - public TemporaryTopic createTemporaryTopic() throws JMSException - { - return _session.createTemporaryTopic(); - } - - public void unsubscribe(String string) throws JMSException - { - _session.unsubscribe(string); - } - - 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(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(String string) throws JMSException - { - return _session.createTextMessage(string); - } - - 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(MessageListener messageListener) throws JMSException - { - _session.setMessageListener(messageListener); - } - - public void run() - { - _session.run(); - } - - public MessageProducer createProducer(Destination destination) throws JMSException - { - return _session.createProducer(destination); - } - - public MessageConsumer createConsumer(Destination destination) throws JMSException - { - return _session.createConsumer(destination); - } - - public MessageConsumer createConsumer(Destination destination, String string) throws JMSException - { - return _session.createConsumer(destination, string); - } - - public MessageConsumer createConsumer(Destination destination, String string, boolean b) throws JMSException - { - return _session.createConsumer(destination, string, b); + return getSession().createPublisher(topic); } //The following methods cannot be called from a TopicSession as per JMS spec @@ -219,8 +67,4 @@ public class AMQTopicSessionAdaptor implements TopicSession, AMQSessionAdapter throw new IllegalStateException("Cannot call createTemporaryQueue from TopicSession"); } - public AMQSession getSession() - { - return _session; - } } 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 index c6e5fbb019..0d717a3216 100644 --- 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 @@ -20,29 +20,35 @@ */ package org.apache.qpid.client; -import org.apache.qpid.AMQInternalException; -import org.apache.qpid.filter.JMSSelectorFilter; -import org.apache.qpid.filter.MessageFilter; +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.message.*; +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.client.protocol.AMQProtocolHandler; import org.apache.qpid.common.AMQPFilterTypes; -import org.apache.qpid.framing.*; +import org.apache.qpid.client.filter.JMSSelectorFilter; +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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import javax.jms.InvalidSelectorException; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; +import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; -import java.util.ArrayList; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingQueue; @@ -54,14 +60,13 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa { private static final Logger _logger = LoggerFactory.getLogger(BasicMessageConsumer.class); - /** The connection being used by this consumer */ - protected final AMQConnection _connection; + private final AMQConnection _connection; - protected final MessageFilter _messageSelectorFilter; + private final MessageFilter _messageSelectorFilter; private final boolean _noLocal; - protected AMQDestination _destination; + private AMQDestination _destination; /** * When true indicates that a blocking receive call is in progress @@ -72,23 +77,17 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa */ private final AtomicReference<MessageListener> _messageListener = new AtomicReference<MessageListener>(); - /** The consumer tag allows us to close the consumer by sending a jmsCancel method to the broker */ - protected int _consumerTag; + private int _consumerTag; - /** We need to know the channel id when constructing frames */ - protected final int _channelId; + private final int _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 final BlockingQueue _synchronousQueue; + private final BlockingQueue _synchronousQueue; - protected final MessageFactoryRegistry _messageFactory; + private final MessageFactoryRegistry _messageFactory; - protected final AMQSession _session; + private final AMQSession _session; - protected final AMQProtocolHandler _protocolHandler; + private final AMQProtocolHandler _protocolHandler; /** * We need to store the "raw" field table so that we can resubscribe in the event of failover being required @@ -107,17 +106,9 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa */ private final int _prefetchLow; - /** - * We store the exclusive field in order to be able to reuse it when resubscribing in the event of failover - */ - protected boolean _exclusive; + private boolean _exclusive; - /** - * 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. - */ - protected final int _acknowledgeMode; + private final int _acknowledgeMode; /** * List of tags delievered, The last of which which should be acknowledged on commit in transaction mode. @@ -208,6 +199,10 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa // 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; @@ -232,6 +227,11 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa 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; @@ -279,7 +279,10 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa throw new javax.jms.IllegalStateException("Attempt to alter listener while session is started."); } - _logger.debug("Message listener set for destination " + _destination); + if (_logger.isDebugEnabled()) + { + _logger.debug("Message listener set for destination " + _destination); + } if (messageListener != null) { @@ -371,6 +374,9 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa 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() { return _exclusive; @@ -537,7 +543,7 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa } else if (o instanceof CloseConsumerMessage) { - _closed.set(true); + setClosed(); deregisterConsumer(); return null; } @@ -554,14 +560,14 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa public void close(boolean sendClose) throws JMSException { - if (_logger.isInfoEnabled()) + if (_logger.isDebugEnabled()) { - _logger.info("Closing consumer:" + debugIdentity()); + _logger.debug("Closing consumer:" + debugIdentity()); } - if (!_closed.getAndSet(true)) + if (!setClosed()) { - _closing.set(true); + setClosing(true); if (_logger.isDebugEnabled()) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); @@ -607,12 +613,8 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa } else { - // FIXME: wow this is ugly - // //fixme this probably is not right - // if (!isNoConsume()) - { // done in BasicCancelOK Handler but not sending one so just deregister. - deregisterConsumer(); - } + // FIXME? + deregisterConsumer(); } // This will occur if session.close is called closing all consumers we may be blocked waiting for a receive @@ -641,7 +643,7 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa { // synchronized (_closed) { - _closed.set(true); + setClosed(); if (_logger.isDebugEnabled()) { @@ -818,7 +820,7 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa { // synchronized (_closed) { - _closed.set(true); + setClosed(); if (_logger.isDebugEnabled()) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); @@ -859,6 +861,7 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa _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; @@ -1002,10 +1005,44 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa public void failedOverPre() { clearReceiveQueue(); - // TGM FIXME: think this should just be removed - // clearUnackedMessages(); } 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 AMQProtocolHandler getProtocolHandler() + { + return _protocolHandler; + } + } 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 index 3b6179dd07..26bb51b821 100644 --- 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 @@ -19,21 +19,32 @@ package org.apache.qpid.client; 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.failover.FailoverException; -import org.apache.qpid.client.message.*; +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.client.protocol.AMQProtocolHandler; import org.apache.qpid.common.ServerPropertyNames; import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.AMQException; -import org.apache.qpid.protocol.AMQConstant; -import org.apache.qpid.transport.*; 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; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; - import java.util.Iterator; import java.util.concurrent.atomic.AtomicBoolean; @@ -46,7 +57,7 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM /** * This class logger */ - protected final Logger _logger = LoggerFactory.getLogger(getClass()); + private final Logger _logger = LoggerFactory.getLogger(getClass()); /** * The underlying QpidSession @@ -67,7 +78,7 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM private final long _capacity; /** Flag indicating if the server supports message selectors */ - protected final boolean _serverJmsSelectorSupport; + private final boolean _serverJmsSelectorSupport; protected BasicMessageConsumer_0_10(int channelId, AMQConnection connection, AMQDestination destination, String messageSelector, boolean noLocal, MessageFactoryRegistry messageFactory, @@ -80,11 +91,10 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM rawSelector, prefetchHigh, prefetchLow, exclusive, acknowledgeMode, browseOnly, autoClose); _0_10session = (AMQSession_0_10) session; - _preAcquire = evaluatePreAcquire(browseOnly, destination); - - _capacity = evaluateCapacity(destination); _serverJmsSelectorSupport = connection.isSupportedServerFeature(ServerPropertyNames.FEATURE_QPID_JMS_SELECTOR); + _preAcquire = evaluatePreAcquire(browseOnly, destination, _serverJmsSelectorSupport); + _capacity = evaluateCapacity(destination); if (destination.isAddressResolved() && AMQDestination.TOPIC_TYPE == destination.getAddressType()) { @@ -92,8 +102,8 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM if (!namedQueue) { - _destination = destination.copyDestination(); - _destination.setQueueName(null); + setDestination(destination.copyDestination()); + getDestination().setQueueName(null); } } } @@ -181,14 +191,14 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM { super.preDeliver(jmsMsg); - if (_acknowledgeMode == org.apache.qpid.jms.Session.NO_ACKNOWLEDGE) + 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. - _session.addUnacknowledgedMessage(jmsMsg.getDeliveryTag()); + getSession().addUnacknowledgedMessage(jmsMsg.getDeliveryTag()); } } @@ -196,7 +206,7 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM AMQMessageDelegateFactory delegateFactory, UnprocessedMessage_0_10 msg) throws Exception { AMQMessageDelegate_0_10.updateExchangeTypeMapping(msg.getMessageTransfer().getHeader(), ((AMQSession_0_10)getSession()).getQpidSession()); - return _messageFactory.createMessage(msg.getMessageTransfer()); + return getMessageFactory().createMessage(msg.getMessageTransfer()); } /** @@ -211,9 +221,9 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM boolean messageOk = true; try { - if (_messageSelectorFilter != null && !_serverJmsSelectorSupport) + if (!_serverJmsSelectorSupport && getMessageSelectorFilter() != null) { - messageOk = _messageSelectorFilter.matches(message); + messageOk = getMessageSelectorFilter().matches(message); } } catch (Exception e) @@ -274,7 +284,7 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM { _0_10session.messageAcknowledge (Range.newInstance((int) message.getDeliveryTag()), - _acknowledgeMode != org.apache.qpid.jms.Session.NO_ACKNOWLEDGE); + getAcknowledgeMode() != org.apache.qpid.jms.Session.NO_ACKNOWLEDGE); final AMQException amqe = _0_10session.getCurrentException(); if (amqe != null) @@ -338,20 +348,20 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM { messageFlow(); } - if (messageListener != null && !_synchronousQueue.isEmpty()) + if (messageListener != null && !getSynchronousQueue().isEmpty()) { - Iterator messages=_synchronousQueue.iterator(); + Iterator messages= getSynchronousQueue().iterator(); while (messages.hasNext()) { AbstractJMSMessage message=(AbstractJMSMessage) messages.next(); messages.remove(); - _session.rejectMessage(message, true); + getSession().rejectMessage(message, true); } } } catch(TransportException e) { - throw _session.toJMSException("Exception while setting message listener:"+ e.getMessage(), e); + throw getSession().toJMSException("Exception while setting message listener:" + e.getMessage(), e); } } @@ -378,7 +388,7 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM { _syncReceive.set(true); } - if (_0_10session.isStarted() && _capacity == 0 && _synchronousQueue.isEmpty()) + if (_0_10session.isStarted() && _capacity == 0 && getSynchronousQueue().isEmpty()) { messageFlow(); } @@ -415,19 +425,19 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM { super.postDeliver(msg); - switch (_acknowledgeMode) + switch (getAcknowledgeMode()) { case Session.SESSION_TRANSACTED: _0_10session.sendTxCompletionsIfNecessary(); break; case Session.NO_ACKNOWLEDGE: - if (!_session.isInRecovery()) + if (!getSession().isInRecovery()) { - _session.acknowledgeMessage(msg.getDeliveryTag(), false); + getSession().acknowledgeMessage(msg.getDeliveryTag(), false); } break; case Session.AUTO_ACKNOWLEDGE: - if (!_session.isInRecovery() && _session.getAMQConnection().getSyncAck()) + if (!getSession().isInRecovery() && getSession().getAMQConnection().getSyncAck()) { ((AMQSession_0_10) getSession()).getQpidSession().sync(); } @@ -443,10 +453,10 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM @Override public void rollbackPendingMessages() { - if (_synchronousQueue.size() > 0) + if (getSynchronousQueue().size() > 0) { RangeSet ranges = RangeSetFactory.createRangeSet(); - Iterator iterator = _synchronousQueue.iterator(); + Iterator iterator = getSynchronousQueue().iterator(); while (iterator.hasNext()) { @@ -486,7 +496,7 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM } else { - return _exclusive; + return super.isExclusive(); } } @@ -514,7 +524,7 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM return _preAcquire; } - private boolean evaluatePreAcquire(boolean browseOnly, AMQDestination destination) + private boolean evaluatePreAcquire(boolean browseOnly, AMQDestination destination, boolean serverJmsSelectorSupport) { boolean preAcquire; if (browseOnly) @@ -524,7 +534,7 @@ public class BasicMessageConsumer_0_10 extends BasicMessageConsumer<UnprocessedM else { boolean isQueue = (destination instanceof AMQQueue || getDestination().getAddressType() == AMQDestination.QUEUE_TYPE); - if (isQueue && getMessageSelectorFilter() != null) + if (!serverJmsSelectorSupport && isQueue && getMessageSelectorFilter() != null) { preAcquire = false; } 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 index b2f4fcef84..b00f9dd98a 100644 --- 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 @@ -20,24 +20,31 @@ */ package org.apache.qpid.client; -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.failover.FailoverException; -import org.apache.qpid.client.message.*; +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.client.protocol.AMQProtocolHandler; import org.apache.qpid.common.AMQPFilterTypes; import org.apache.qpid.configuration.ClientProperties; -import org.apache.qpid.framing.*; +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; -import org.apache.qpid.url.BindingURL; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import javax.jms.JMSException; +import javax.jms.Message; public class BasicMessageConsumer_0_8 extends BasicMessageConsumer<UnprocessedMessage_0_8> { - protected final Logger _logger = LoggerFactory.getLogger(getClass()); + private final Logger _logger = LoggerFactory.getLogger(getClass()); private AMQSession_0_8.DestinationCache<AMQTopic> _topicDestinationCache; private AMQSession_0_8.DestinationCache<AMQQueue> _queueDestinationCache; @@ -88,11 +95,11 @@ public class BasicMessageConsumer_0_8 extends BasicMessageConsumer<UnprocessedMe void sendCancel() throws AMQException, FailoverException { - BasicCancelBody body = getSession().getMethodRegistry().createBasicCancelBody(new AMQShortString(String.valueOf(_consumerTag)), false); + BasicCancelBody body = getSession().getMethodRegistry().createBasicCancelBody(new AMQShortString(String.valueOf(getConsumerTag())), false); - final AMQFrame cancelFrame = body.generateFrame(_channelId); + final AMQFrame cancelFrame = body.generateFrame(getChannelId()); - _protocolHandler.syncWrite(cancelFrame, BasicCancelOkBody.class); + getProtocolHandler().syncWrite(cancelFrame, BasicCancelOkBody.class); if (_logger.isDebugEnabled()) { @@ -103,9 +110,9 @@ public class BasicMessageConsumer_0_8 extends BasicMessageConsumer<UnprocessedMe public AbstractJMSMessage createJMSMessageFromUnprocessedMessage(AMQMessageDelegateFactory delegateFactory, UnprocessedMessage_0_8 messageFrame)throws Exception { - return _messageFactory.createMessage(messageFrame.getDeliveryTag(), - messageFrame.isRedelivered(), messageFrame.getExchange(), - messageFrame.getRoutingKey(), messageFrame.getContentHeader(), messageFrame.getBodies(), + return getMessageFactory().createMessage(messageFrame.getDeliveryTag(), + messageFrame.isRedelivered(), messageFrame.getExchange(), + messageFrame.getRoutingKey(), messageFrame.getContentHeader(), messageFrame.getBodies(), _queueDestinationCache, _topicDestinationCache); } 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 index bf4de782a5..9b3b2ce0e9 100644 --- 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 @@ -22,7 +22,6 @@ package org.apache.qpid.client; import java.io.UnsupportedEncodingException; import java.util.UUID; - import javax.jms.BytesMessage; import javax.jms.DeliveryMode; import javax.jms.Destination; @@ -33,12 +32,11 @@ import javax.jms.Message; import javax.jms.ObjectMessage; import javax.jms.StreamMessage; import javax.jms.TextMessage; - +import javax.jms.Topic; import org.apache.qpid.AMQException; import org.apache.qpid.client.message.AbstractJMSMessage; import org.apache.qpid.client.message.MessageConverter; import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.framing.ContentBody; import org.apache.qpid.transport.TransportException; import org.apache.qpid.util.UUIDGen; import org.apache.qpid.util.UUIDs; @@ -49,14 +47,11 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac { enum PublishMode { ASYNC_PUBLISH_ALL, SYNC_PUBLISH_PERSISTENT, SYNC_PUBLISH_ALL }; - protected final Logger _logger = LoggerFactory.getLogger(getClass()); + private final Logger _logger ; private AMQConnection _connection; - /** - * If true, messages will not get a timestamp. - */ - protected boolean _disableTimestamps; + private boolean _disableTimestamps; /** * Priority of messages created by this producer. @@ -73,10 +68,7 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac */ private int _deliveryMode = DeliveryMode.PERSISTENT; - /** - * The Destination used for this consumer, if specified upon creation. - */ - protected AMQDestination _destination; + private AMQDestination _destination; /** * Default encoding used for messages produced by this producer. @@ -88,14 +80,14 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac */ private String _mimeType; - protected AMQProtocolHandler _protocolHandler; + private AMQProtocolHandler _protocolHandler; /** * True if this producer was created from a transacted session */ private boolean _transacted; - protected int _channelId; + private int _channelId; /** * This is an id generated by the session and is used to tie individual producers to the session. This means we @@ -105,29 +97,49 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac */ private long _producerId; - /** - * The session used to create this producer - */ - protected AMQSession _session; + private AMQSession _session; private final boolean _immediate; - private final boolean _mandatory; + private final Boolean _mandatory; private boolean _disableMessageId; private UUIDGen _messageIdGenerator = UUIDs.newGenerator(); - protected String _userID; // ref user id used in the connection. + private String _userID; // ref user id used in the connection. - private static final ContentBody[] NO_CONTENT_BODIES = new ContentBody[0]; - protected PublishMode publishMode = PublishMode.ASYNC_PUBLISH_ALL; + /** + * 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")); - protected BasicMessageProducer(AMQConnection connection, AMQDestination destination, boolean transacted, int channelId, - AMQSession session, AMQProtocolHandler protocolHandler, long producerId, boolean immediate, boolean mandatory) throws AMQException + /** + * 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, AMQProtocolHandler protocolHandler, long producerId, + Boolean immediate, Boolean mandatory) throws AMQException { - _connection = connection; + _logger = logger; + _connection = connection; _destination = destination; _transacted = transacted; _protocolHandler = protocolHandler; @@ -139,8 +151,14 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac declareDestination(destination); } - _immediate = immediate; - _mandatory = mandatory; + _immediate = immediate == null ? _defaultImmediateValue : immediate; + _mandatory = mandatory == null + ? destination == null ? null + : destination instanceof Topic + ? _defaultMandatoryTopicValue + : _defaultMandatoryValue + : mandatory; + _userID = connection.getUsername(); setPublishMode(); } @@ -161,7 +179,10 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac publishMode = PublishMode.SYNC_PUBLISH_ALL; } - _logger.info("MessageProducer " + toString() + " using publish mode : " + publishMode); + if (_logger.isDebugEnabled()) + { + _logger.debug("MessageProducer " + toString() + " using publish mode : " + publishMode); + } } void resubscribe() throws AMQException @@ -256,6 +277,14 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac return _timeToLive; } + protected AMQDestination getAMQDestination() + { + return _destination; + } + + /** + * The Destination used for this consumer, if specified upon creation. + */ public Destination getDestination() throws JMSException { checkNotClosed(); @@ -265,7 +294,7 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac public void close() throws JMSException { - _closed.set(true); + setClosed(); _session.deregisterProducer(_producerId); } @@ -319,7 +348,12 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac synchronized (_connection.getFailoverMutex()) { validateDestination(destination); - sendImpl((AMQDestination) destination, message, _deliveryMode, _messagePriority, _timeToLive, _mandatory, + sendImpl((AMQDestination) destination, message, _deliveryMode, _messagePriority, _timeToLive, + _mandatory == null + ? destination instanceof Topic + ? _defaultMandatoryTopicValue + : _defaultMandatoryValue + : _mandatory, _immediate); } } @@ -332,7 +366,13 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac synchronized (_connection.getFailoverMutex()) { validateDestination(destination); - sendImpl((AMQDestination) destination, message, deliveryMode, priority, timeToLive, _mandatory, _immediate); + sendImpl((AMQDestination) destination, message, deliveryMode, priority, timeToLive, + _mandatory == null + ? destination instanceof Topic + ? _defaultMandatoryTopicValue + : _defaultMandatoryValue + : _mandatory, + _immediate); } } @@ -480,7 +520,10 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac _logger.debug("Updating original message"); origMessage.setJMSPriority(message.getJMSPriority()); origMessage.setJMSTimestamp(message.getJMSTimestamp()); - _logger.debug("Setting JMSExpiration:" + message.getJMSExpiration()); + if (_logger.isDebugEnabled()) + { + _logger.debug("Setting JMSExpiration:" + message.getJMSExpiration()); + } origMessage.setJMSExpiration(message.getJMSExpiration()); origMessage.setJMSMessageID(message.getJMSMessageID()); } @@ -564,6 +607,9 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac } + /** + * The session used to create this producer + */ public AMQSession getSession() { return _session; @@ -580,4 +626,73 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac 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 AMQProtocolHandler getProtocolHandler() + { + return _protocolHandler; + } + + protected void setProtocolHandler(AMQProtocolHandler protocolHandler) + { + _protocolHandler = protocolHandler; + } + + 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) + { + this.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 index 16afa51c74..a3a1e9c28b 100644 --- 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 @@ -17,18 +17,8 @@ */ 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.AddressOption; @@ -48,8 +38,18 @@ import org.apache.qpid.transport.MessageProperties; import org.apache.qpid.transport.Option; import org.apache.qpid.transport.TransportException; import org.apache.qpid.util.Strings; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +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 javax.jms.DeliveryMode; +import javax.jms.JMSException; +import javax.jms.Message; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; /** * This is a 0_10 message producer. @@ -61,11 +61,11 @@ public class BasicMessageProducer_0_10 extends BasicMessageProducer BasicMessageProducer_0_10(AMQConnection connection, AMQDestination destination, boolean transacted, int channelId, AMQSession session, AMQProtocolHandler protocolHandler, long producerId, - boolean immediate, boolean mandatory) throws AMQException + Boolean immediate, Boolean mandatory) throws AMQException { - super(connection, destination, transacted, channelId, session, protocolHandler, producerId, immediate, mandatory); + super(_logger, connection, destination, transacted, channelId, session, protocolHandler, producerId, immediate, mandatory); - userIDBytes = Strings.toUTF8(_userID); + userIDBytes = Strings.toUTF8(getUserID()); } void declareDestination(AMQDestination destination) throws AMQException @@ -86,7 +86,7 @@ public class BasicMessageProducer_0_10 extends BasicMessageProducer { try { - getSession().handleAddressBasedDestination(destination,false,false); + getSession().handleAddressBasedDestination(destination,false,false,false); } catch(Exception e) { @@ -125,7 +125,7 @@ public class BasicMessageProducer_0_10 extends BasicMessageProducer } long currentTime = 0; - if (timeToLive > 0 || !_disableTimestamps) + if (timeToLive > 0 || !isDisableTimestamps()) { currentTime = System.currentTimeMillis(); } @@ -136,7 +136,7 @@ public class BasicMessageProducer_0_10 extends BasicMessageProducer message.setJMSExpiration(currentTime + timeToLive); } - if (!_disableTimestamps) + if (!isDisableTimestamps()) { deliveryProp.setTimestamp(currentTime); @@ -213,8 +213,8 @@ public class BasicMessageProducer_0_10 extends BasicMessageProducer // if true, we need to sync the delivery of this message boolean sync = false; - sync = ( (publishMode == PublishMode.SYNC_PUBLISH_ALL) || - (publishMode == PublishMode.SYNC_PUBLISH_PERSISTENT && + sync = ( (getPublishMode() == PublishMode.SYNC_PUBLISH_ALL) || + (getPublishMode() == PublishMode.SYNC_PUBLISH_PERSISTENT && deliveryMode == DeliveryMode.PERSISTENT) ); @@ -248,14 +248,14 @@ public class BasicMessageProducer_0_10 extends BasicMessageProducer @Override public boolean isBound(AMQDestination destination) throws JMSException { - return _session.isQueueBound(destination); + return getSession().isQueueBound(destination); } @Override public void close() throws JMSException { super.close(); - AMQDestination dest = _destination; + AMQDestination dest = getAMQDestination(); if (dest != null && dest.getDestSyntax() == AMQDestination.DestSyntax.ADDR) { if (dest.getDelete() == AddressOption.ALWAYS || @@ -264,7 +264,7 @@ public class BasicMessageProducer_0_10 extends BasicMessageProducer try { ((AMQSession_0_10) getSession()).getQpidSession().queueDelete( - _destination.getQueueName()); + getAMQDestination().getQueueName()); } catch(TransportException e) { 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 index b2f998cb2c..21ff6c877a 100644 --- 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 @@ -20,18 +20,9 @@ */ package org.apache.qpid.client; -import java.util.UUID; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.Topic; -import javax.jms.Queue; - -import java.nio.ByteBuffer; - import org.apache.qpid.AMQException; -import org.apache.qpid.client.message.AbstractJMSMessage; import org.apache.qpid.client.message.AMQMessageDelegate_0_8; +import org.apache.qpid.client.message.AbstractJMSMessage; import org.apache.qpid.client.protocol.AMQProtocolHandler; import org.apache.qpid.framing.AMQFrame; import org.apache.qpid.framing.BasicContentHeaderProperties; @@ -42,13 +33,24 @@ import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.framing.ExchangeDeclareBody; import org.apache.qpid.framing.MethodRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.jms.JMSException; +import javax.jms.Message; +import javax.jms.Queue; +import javax.jms.Topic; +import java.nio.ByteBuffer; +import java.util.UUID; + public class BasicMessageProducer_0_8 extends BasicMessageProducer { + private static final Logger _logger = LoggerFactory.getLogger(BasicMessageProducer_0_8.class); BasicMessageProducer_0_8(AMQConnection connection, AMQDestination destination, boolean transacted, int channelId, - AMQSession session, AMQProtocolHandler protocolHandler, long producerId, boolean immediate, boolean mandatory) throws AMQException + AMQSession session, AMQProtocolHandler protocolHandler, long producerId, Boolean immediate, Boolean mandatory) throws AMQException { - super(connection, destination,transacted,channelId,session, protocolHandler, producerId, immediate, mandatory); + super(_logger,connection, destination,transacted,channelId,session, protocolHandler, producerId, immediate, mandatory); } void declareDestination(AMQDestination destination) @@ -56,7 +58,7 @@ public class BasicMessageProducer_0_8 extends BasicMessageProducer final MethodRegistry methodRegistry = getSession().getMethodRegistry(); ExchangeDeclareBody body = - methodRegistry.createExchangeDeclareBody(_session.getTicket(), + methodRegistry.createExchangeDeclareBody(getSession().getTicket(), destination.getExchangeName(), destination.getExchangeClass(), destination.getExchangeName().toString().startsWith("amq."), @@ -68,29 +70,29 @@ public class BasicMessageProducer_0_8 extends BasicMessageProducer // Declare the exchange // Note that the durable and internal arguments are ignored since passive is set to false - AMQFrame declare = body.generateFrame(_channelId); + AMQFrame declare = body.generateFrame(getChannelId()); - _protocolHandler.writeFrame(declare); + 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 { - BasicPublishBody body = getSession().getMethodRegistry().createBasicPublishBody(_session.getTicket(), + BasicPublishBody body = getSession().getMethodRegistry().createBasicPublishBody(getSession().getTicket(), destination.getExchangeName(), destination.getRoutingKey(), mandatory, immediate); - AMQFrame publishFrame = body.generateFrame(_channelId); + AMQFrame publishFrame = body.generateFrame(getChannelId()); message.prepareForSending(); ByteBuffer payload = message.getData(); AMQMessageDelegate_0_8 delegate = (AMQMessageDelegate_0_8) message.getDelegate(); BasicContentHeaderProperties contentHeaderProperties = delegate.getContentHeaderProperties(); - contentHeaderProperties.setUserId(_userID); + contentHeaderProperties.setUserId(getUserID()); //Set the JMS_QPID_DESTTYPE for 0-8/9 messages int type; @@ -110,7 +112,7 @@ public class BasicMessageProducer_0_8 extends BasicMessageProducer //Set JMS_QPID_DESTTYPE delegate.getContentHeaderProperties().getHeaders().setInteger(CustomJMSXProperty.JMS_QPID_DESTTYPE.getShortStringName(), type); - if (!_disableTimestamps) + if (!isDisableTimestamps()) { final long currentTime = System.currentTimeMillis(); contentHeaderProperties.setTimestamp(currentTime); @@ -134,12 +136,12 @@ public class BasicMessageProducer_0_8 extends BasicMessageProducer if (payload != null) { - createContentBodies(payload, frames, 2, _channelId); + createContentBodies(payload, frames, 2, getChannelId()); } - if ((contentBodyFrameCount != 0) && _logger.isDebugEnabled()) + if ((contentBodyFrameCount != 0) && getLogger().isDebugEnabled()) { - _logger.debug("Sending content body frames to " + destination); + getLogger().debug("Sending content body frames to " + destination); } @@ -147,11 +149,11 @@ public class BasicMessageProducer_0_8 extends BasicMessageProducer int classIfForBasic = getSession().getMethodRegistry().createBasicQosOkBody().getClazz(); AMQFrame contentHeaderFrame = - ContentHeaderBody.createAMQFrame(_channelId, + ContentHeaderBody.createAMQFrame(getChannelId(), classIfForBasic, 0, contentHeaderProperties, size); - if (_logger.isDebugEnabled()) + if (getLogger().isDebugEnabled()) { - _logger.debug("Sending content header frame to " + destination); + getLogger().debug("Sending content header frame to " + destination); } frames[0] = publishFrame; @@ -160,7 +162,7 @@ public class BasicMessageProducer_0_8 extends BasicMessageProducer try { - _session.checkFlowControl(); + getSession().checkFlowControl(); } catch (InterruptedException e) { @@ -170,7 +172,7 @@ public class BasicMessageProducer_0_8 extends BasicMessageProducer throw jmse; } - _protocolHandler.writeFrame(compositeFrame); + getProtocolHandler().writeFrame(compositeFrame); } /** @@ -194,7 +196,7 @@ public class BasicMessageProducer_0_8 extends BasicMessageProducer else { - final long framePayloadMax = _session.getAMQConnection().getMaximumFrameSize() - 1; + final long framePayloadMax = getSession().getAMQConnection().getMaximumFrameSize() - 1; long remaining = payload.remaining(); for (int i = offset; i < frames.length; i++) { @@ -224,7 +226,7 @@ public class BasicMessageProducer_0_8 extends BasicMessageProducer else { int dataLength = payload.remaining(); - final long framePayloadMax = _session.getAMQConnection().getMaximumFrameSize() - 1; + final long framePayloadMax = getSession().getAMQConnection().getMaximumFrameSize() - 1; int lastFrame = ((dataLength % framePayloadMax) > 0) ? 1 : 0; frameCount = (int) (dataLength / framePayloadMax) + lastFrame; } 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 index e6771e122c..ba26bfc485 100644 --- 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 @@ -22,7 +22,6 @@ package org.apache.qpid.client; import javax.jms.IllegalStateException; import javax.jms.JMSException; - import java.util.concurrent.atomic.AtomicBoolean; /** @@ -49,14 +48,14 @@ 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. */ - protected final AtomicBoolean _closed = new AtomicBoolean(false); + 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. */ - protected final AtomicBoolean _closing = new AtomicBoolean(false); + private final AtomicBoolean _closing = new AtomicBoolean(false); /** * Checks if this is closed, and raises a JMSException if it is. @@ -91,6 +90,15 @@ public abstract class Closeable return _closing.get(); } + protected boolean setClosed() + { + return _closed.getAndSet(true); + } + + protected void setClosing(boolean closing) + { + _closing.set(closing); + } /** * Closes this object. 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 index e81e754da2..b2d1072e2b 100644 --- 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 @@ -20,13 +20,13 @@ */ 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; -import org.apache.qpid.framing.AMQShortString; - public enum CustomJMSXProperty { JMS_AMQP_NULL, diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java b/qpid/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.java deleted file mode 100644 index 81a55006ed..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/DispatcherCallback.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.client; - -import java.util.Queue; - -public abstract class DispatcherCallback -{ - BasicMessageConsumer _consumer; - - public DispatcherCallback(BasicMessageConsumer mc) - { - _consumer = mc; - } - - abstract public void whilePaused(Queue<MessageConsumerPair> reprocessQueue); - -} 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 index 585d6db3fd..134159afe1 100644 --- 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 @@ -22,8 +22,8 @@ package org.apache.qpid.client; public class MessageConsumerPair { - BasicMessageConsumer _consumer; - Object _item; + private BasicMessageConsumer _consumer; + private Object _item; public MessageConsumerPair(BasicMessageConsumer consumer, Object 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 index 5cf767ac35..03574ceab3 100644 --- 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 @@ -20,12 +20,11 @@ */ package org.apache.qpid.client; -import java.util.Enumeration; +import org.apache.qpid.common.QpidProperties; import javax.jms.ConnectionMetaData; import javax.jms.JMSException; - -import org.apache.qpid.common.QpidProperties; +import java.util.Enumeration; public class QpidConnectionMetaData implements ConnectionMetaData { 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 index 7059588367..b778ee22d6 100644 --- 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 @@ -33,8 +33,8 @@ import javax.jms.QueueReceiver; */ public class QueueReceiverAdaptor implements QueueReceiver { - protected MessageConsumer _consumer; - protected Queue _queue; + private MessageConsumer _consumer; + private Queue _queue; protected QueueReceiverAdaptor(Queue queue, MessageConsumer consumer) { 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 index 295c6a4091..0b797df9dd 100644 --- 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 @@ -202,7 +202,7 @@ public class QueueSenderAdapter implements QueueSender { if (_delegate.getSession().isStrictAMQP()) { - _delegate._logger.warn("AMQP does not support destination validation before publish, "); + _delegate.getLogger().warn("AMQP does not support destination validation before publish, "); destination.setCheckedForQueueBinding(true); } else 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 index ca137f5a51..6da3825359 100644 --- 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 @@ -21,11 +21,11 @@ package org.apache.qpid.client; +import org.apache.qpid.framing.AMQShortString; + import javax.jms.Destination; import javax.jms.JMSException; -import org.apache.qpid.framing.AMQShortString; - /** * Provides support for convenience interface implemented by both AMQTemporaryTopic and AMQTemporaryQueue * so that operations related to their "temporary-ness" can be abstracted out. 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 index 509aa25bd5..d9514338ce 100644 --- 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 @@ -17,10 +17,16 @@ */ package org.apache.qpid.client; -import org.apache.qpid.jms.ConnectionURL; import org.apache.qpid.AMQException; +import org.apache.qpid.jms.ConnectionURL; -import javax.jms.*; +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.njms.XAConnection interface @@ -47,7 +53,7 @@ public class XAConnectionImpl extends AMQConnection implements XAConnection, XAQ public synchronized XASession createXASession() throws JMSException { checkNotClosed(); - return _delegate.createXASession(); + return getDelegate().createXASession(); } //-- Interface XAQueueConnection @@ -80,6 +86,6 @@ public class XAConnectionImpl extends AMQConnection implements XAConnection, XAQ public XASession createXASession(int ackMode) throws JMSException { checkNotClosed(); - return _delegate.createXASession(ackMode); + 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 index 5b94b342eb..af9048f1f5 100644 --- 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 @@ -17,9 +17,8 @@ */ package org.apache.qpid.client; -import javax.transaction.xa.XAException; -import javax.transaction.xa.XAResource; -import javax.transaction.xa.Xid; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.apache.qpid.dtx.XidImpl; import org.apache.qpid.transport.DtxXaStatus; @@ -29,8 +28,10 @@ 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; + +import javax.transaction.xa.XAException; +import javax.transaction.xa.XAResource; +import javax.transaction.xa.Xid; /** * This is an implementation of javax.njms.XAResource. @@ -307,13 +308,16 @@ public class XAResourceImpl implements XAResource _xaSession.createSession(); convertExecutionErrorToXAErr( e.getException().getErrorCode()); } - Xid[] result = new Xid[res.getInDoubt().size()]; - int i = 0; - for (Object obj : res.getInDoubt()) + Xid[] result = new Xid[res.getInDoubt() != null ? res.getInDoubt().size() : 0]; + if(result.length != 0) { - org.apache.qpid.transport.Xid xid = (org.apache.qpid.transport.Xid) obj; - result[i] = new XidImpl(xid.getBranchId(), (int) xid.getFormat(), xid.getGlobalId()); - i++; + 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; } @@ -435,6 +439,16 @@ public class XAResourceImpl implements XAResource } } + /** + * 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 //------------------------------------------------------------------------ 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 index aaabf613fc..6d5bf9ad67 100644 --- 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 @@ -18,8 +18,16 @@ package org.apache.qpid.client; import org.apache.qpid.client.message.MessageFactoryRegistry; - -import javax.jms.*; +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; /** @@ -79,7 +87,7 @@ public class XASessionImpl extends AMQSession_0_10 implements XASession, XATopic */ public void createSession() { - _qpidDtxSession = _qpidConnection.createSession(0); + _qpidDtxSession = getQpidConnection().createSession(0); _qpidDtxSession.setSessionListener(this); _qpidDtxSession.dtxSelect(); } @@ -171,4 +179,17 @@ public class XASessionImpl extends AMQSession_0_10 implements XASession, XATopic { return (TopicSession) getSession(); } + + @Override + protected void acknowledgeImpl() + { + if (_xaResource.isEnlisted()) + { + acknowledgeMessage(Long.MAX_VALUE, true) ; + } + else + { + super.acknowledgeImpl() ; + } + } } 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 index f74dbba939..4099da18d2 100644 --- 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 @@ -20,13 +20,13 @@ */ package org.apache.qpid.client.failover; +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.AMQStateManager; import org.apache.qpid.client.state.AMQState; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.qpid.client.state.AMQStateManager; import java.util.concurrent.CountDownLatch; @@ -231,14 +231,7 @@ public class FailoverHandler implements Runnable { _logger.info("Failover process failed - exception being propagated by protocol handler"); _amqProtocolHandler.setFailoverState(FailoverState.FAILED); - /*try - {*/ _amqProtocolHandler.exception(e); - /*} - catch (Exception ex) - { - _logger.error("Error notifying protocol session of error: " + ex, ex); - }*/ } } } 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 index 51cc94965a..a69e808880 100644 --- 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 @@ -38,10 +38,10 @@ import org.apache.qpid.client.AMQConnection; 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. */ - FailoverProtectedOperation<T, E> operation; + private FailoverProtectedOperation<T, E> operation; /** The connection on which the fail-over protected operation is to be performed. */ - AMQConnection connection; + private AMQConnection connection; /** * Creates an automatic retrying fail-over handler for the specified operation. 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 index 28d19ce817..d3d33d3c75 100644 --- 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 @@ -20,11 +20,11 @@ */ package org.apache.qpid.client.failover; -import org.apache.qpid.client.AMQConnection; - 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 @@ -73,10 +73,10 @@ public class FailoverRetrySupport<T, E extends Exception> implements FailoverSup private static final Logger _log = LoggerFactory.getLogger(FailoverRetrySupport.class); /** The protected operation that is to be retried in the event of fail-over. */ - FailoverProtectedOperation<T, E> operation; + private FailoverProtectedOperation<T, E> operation; /** The connection on which the fail-over protected operation is to be performed. */ - AMQConnection connection; + private AMQConnection connection; /** * Creates an automatic retrying fail-over handler for the specified operation. 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 index 14cce0aa59..bab518b0ec 100644 --- 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 @@ -55,6 +55,10 @@ public class JMSSelectorFilter implements MessageFilter { _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); 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 index af47673a43..3a3ddae52f 100644 --- 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 @@ -24,10 +24,10 @@ package org.apache.qpid.client.handler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.apache.qpid.framing.*; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.client.protocol.AMQProtocolSession; 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> { 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 index 5cb9412d51..9b5eea3bba 100644 --- 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 @@ -20,14 +20,14 @@ */ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class BasicCancelOkMethodHandler implements StateAwareMethodListener<BasicCancelOkBody> { private static final Logger _logger = LoggerFactory.getLogger(BasicCancelOkMethodHandler.class); 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 index 33ca584b34..3f57e180e7 100644 --- 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 @@ -20,13 +20,14 @@ */ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class BasicDeliverMethodHandler implements StateAwareMethodListener<BasicDeliverBody> { 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 index 3bbc9209c5..a09d298ae8 100644 --- 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 @@ -20,15 +20,15 @@ */ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class BasicReturnMethodHandler implements StateAwareMethodListener<BasicReturnBody> { private static final Logger _logger = LoggerFactory.getLogger(BasicReturnMethodHandler.class); 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 index b9d4d6fa95..85328d78ea 100644 --- 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 @@ -20,6 +20,9 @@ */ 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; @@ -32,8 +35,6 @@ import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ChannelCloseBody; import org.apache.qpid.framing.ChannelCloseOkBody; import org.apache.qpid.protocol.AMQConstant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class ChannelCloseMethodHandler implements StateAwareMethodListener<ChannelCloseBody> { 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 index 72936779c2..058484c339 100644 --- 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 @@ -20,13 +20,14 @@ */ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; public class ChannelCloseOkMethodHandler implements StateAwareMethodListener<ChannelCloseOkBody> { 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 index 2153b9cc8c..919c5f6d67 100644 --- 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 @@ -1,12 +1,13 @@ package org.apache.qpid.client.handler; -import org.apache.qpid.framing.ChannelFlowBody; -import org.apache.qpid.client.state.StateAwareMethodListener; -import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.AMQException; 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; + /* * * Licensed to the Apache Software Foundation (ASF) under one 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 index 6f66a972d5..c15404ea08 100644 --- 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 @@ -20,14 +20,14 @@ */ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class ChannelFlowOkMethodHandler implements StateAwareMethodListener<ChannelFlowOkBody> { private static final Logger _logger = LoggerFactory.getLogger(ChannelFlowOkMethodHandler.class); 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 index ec98783a8a..e1a0e18262 100644 --- 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 @@ -20,16 +20,17 @@ */ package org.apache.qpid.client.handler; -import java.util.Map; -import java.util.HashMap; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import org.apache.qpid.framing.*; import org.apache.qpid.AMQException; -import org.apache.qpid.client.state.AMQStateManager; -import org.apache.qpid.client.state.AMQMethodNotImplementedException; import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.qpid.client.state.AMQMethodNotImplementedException; +import org.apache.qpid.client.state.AMQStateManager; +import org.apache.qpid.framing.*; + +import java.util.HashMap; +import java.util.Map; public class ClientMethodDispatcherImpl implements MethodDispatcher { @@ -94,16 +95,16 @@ public class ClientMethodDispatcherImpl implements MethodDispatcher public static ClientMethodDispatcherImpl newMethodDispatcher(ProtocolVersion version, AMQProtocolSession session) { - if (_logger.isInfoEnabled()) + if (_logger.isDebugEnabled()) { - _logger.info("New Method Dispatcher:" + session); + _logger.debug("New Method Dispatcher:" + session); } DispatcherFactory factory = _dispatcherFactories.get(version); return factory.createMethodDispatcher(session); } - AMQProtocolSession _session; + private AMQProtocolSession _session; public ClientMethodDispatcherImpl(AMQProtocolSession session) { 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 index d3e9fba8ed..f4fc3a4715 100644 --- 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 @@ -20,13 +20,11 @@ */ package org.apache.qpid.client.handler; -import org.apache.qpid.framing.*; -import org.apache.qpid.framing.amqp_0_9.MethodDispatcher_0_9; - import org.apache.qpid.AMQException; -import org.apache.qpid.client.state.AMQStateManager; -import org.apache.qpid.client.state.AMQMethodNotImplementedException; import org.apache.qpid.client.protocol.AMQProtocolSession; +import org.apache.qpid.client.state.AMQMethodNotImplementedException; +import org.apache.qpid.framing.*; +import org.apache.qpid.framing.amqp_0_9.MethodDispatcher_0_9; public class ClientMethodDispatcherImpl_0_9 extends ClientMethodDispatcherImpl implements MethodDispatcher_0_9 { 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 index f15340ae00..5f33561a8f 100644 --- 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 @@ -20,13 +20,11 @@ */ package org.apache.qpid.client.handler; -import org.apache.qpid.framing.*; -import org.apache.qpid.framing.amqp_0_91.MethodDispatcher_0_91; - import org.apache.qpid.AMQException; -import org.apache.qpid.client.state.AMQStateManager; -import org.apache.qpid.client.state.AMQMethodNotImplementedException; import org.apache.qpid.client.protocol.AMQProtocolSession; +import org.apache.qpid.client.state.AMQMethodNotImplementedException; +import org.apache.qpid.framing.*; +import org.apache.qpid.framing.amqp_0_91.MethodDispatcher_0_91; public class ClientMethodDispatcherImpl_0_91 extends ClientMethodDispatcherImpl implements MethodDispatcher_0_91 { 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 index 19f758817d..28ad6037d4 100644 --- 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 @@ -20,11 +20,19 @@ */ package org.apache.qpid.client.handler; -import org.apache.qpid.framing.*; -import org.apache.qpid.framing.amqp_8_0.MethodDispatcher_8_0; - import org.apache.qpid.AMQException; import org.apache.qpid.client.protocol.AMQProtocolSession; +import org.apache.qpid.framing.BasicRecoverOkBody; +import org.apache.qpid.framing.ChannelAlertBody; +import org.apache.qpid.framing.TestContentBody; +import org.apache.qpid.framing.TestContentOkBody; +import org.apache.qpid.framing.TestIntegerBody; +import org.apache.qpid.framing.TestIntegerOkBody; +import org.apache.qpid.framing.TestStringBody; +import org.apache.qpid.framing.TestStringOkBody; +import org.apache.qpid.framing.TestTableBody; +import org.apache.qpid.framing.TestTableOkBody; +import org.apache.qpid.framing.amqp_8_0.MethodDispatcher_8_0; public class ClientMethodDispatcherImpl_8_0 extends ClientMethodDispatcherImpl implements MethodDispatcher_8_0 { 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 index b392604822..2cf7b089eb 100644 --- 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 @@ -20,21 +20,20 @@ */ 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.AMQState; 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.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class ConnectionCloseMethodHandler implements StateAwareMethodListener<ConnectionCloseBody> { private static final Logger _logger = LoggerFactory.getLogger(ConnectionCloseMethodHandler.class); @@ -55,9 +54,6 @@ public class ConnectionCloseMethodHandler implements StateAwareMethodListener<Co { _logger.info("ConnectionClose frame received"); - // does it matter - // stateManager.changeState(AMQState.CONNECTION_CLOSING); - AMQConstant errorCode = AMQConstant.getConstant(method.getReplyCode()); AMQShortString reason = method.getReplyText(); 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 index e40cafd72f..1b197de910 100644 --- 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 @@ -20,11 +20,10 @@ */ package org.apache.qpid.client.handler; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.ConnectionOpenOkBody; 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> { 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 index 472c471fd6..0ccb9b72b1 100644 --- 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 @@ -20,14 +20,14 @@ */ 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.ConnectionRedirectBody; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class ConnectionRedirectMethodHandler implements StateAwareMethodListener<ConnectionRedirectBody> { private static final Logger _logger = LoggerFactory.getLogger(ConnectionRedirectMethodHandler.class); 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 index 9a9bee757b..8afb6ffcb4 100644 --- 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 @@ -20,15 +20,15 @@ */ package org.apache.qpid.client.handler; -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslException; - 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(); 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 index 939bd181a3..66c4821f60 100644 --- 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 @@ -20,12 +20,8 @@ */ 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; @@ -33,16 +29,21 @@ 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.ClientProperties; 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.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.qpid.properties.ConnectionStartProperties; + +import javax.security.sasl.Sasl; +import javax.security.sasl.SaslClient; +import javax.security.sasl.SaslException; +import java.io.UnsupportedEncodingException; +import java.util.StringTokenizer; public class ConnectionStartMethodHandler implements StateAwareMethodListener<ConnectionStartBody> { @@ -148,14 +149,18 @@ public class ConnectionStartMethodHandler implements StateAwareMethodListener<Co session.getStateManager().changeState(AMQState.CONNECTION_NOT_TUNED); FieldTable clientProperties = FieldTableFactory.newFieldTable(); - clientProperties.setString(new AMQShortString(ClientProperties.instance.toString()), - session.getClientID()); - clientProperties.setString(new AMQShortString(ClientProperties.product.toString()), - QpidProperties.getProductName()); - clientProperties.setString(new AMQShortString(ClientProperties.version.toString()), - QpidProperties.getReleaseVersion()); - clientProperties.setString(new AMQShortString(ClientProperties.platform.toString()), getFullSystemInfo()); - + 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()); 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) @@ -178,20 +183,6 @@ public class ConnectionStartMethodHandler implements StateAwareMethodListener<Co } } - private String getFullSystemInfo() - { - StringBuffer fullSystemInfo = new StringBuffer(); - fullSystemInfo.append(System.getProperty("java.runtime.name")); - fullSystemInfo.append(", " + System.getProperty("java.runtime.version")); - fullSystemInfo.append(", " + System.getProperty("java.vendor")); - fullSystemInfo.append(", " + System.getProperty("os.arch")); - fullSystemInfo.append(", " + System.getProperty("os.name")); - fullSystemInfo.append(", " + System.getProperty("os.version")); - fullSystemInfo.append(", " + System.getProperty("sun.os.patch.level")); - - return fullSystemInfo.toString(); - } - private String chooseMechanism(byte[] availableMechanisms) throws UnsupportedEncodingException { final String mechanisms = new String(availableMechanisms, "utf8"); 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 index d1b2caf987..f77718672e 100644 --- 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 @@ -20,15 +20,18 @@ */ package org.apache.qpid.client.handler; -import org.apache.qpid.AMQException; +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.*; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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> { 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 index 690d782b40..b60127cf93 100644 --- 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 @@ -20,14 +20,14 @@ */ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @author Apache Software Foundation */ 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 index 01d82c9b55..3c76a8ac38 100644 --- 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 @@ -20,14 +20,14 @@ */ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * @author Apache Software Foundation */ 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 index a9434edf49..d01c4ac33d 100644 --- 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 @@ -25,7 +25,6 @@ import org.apache.qpid.client.AMQSession; import javax.jms.Destination; import javax.jms.JMSException; - import java.util.Enumeration; import java.util.UUID; 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 index 179ebd66d1..a0c3914127 100644 --- 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 @@ -21,22 +21,8 @@ package org.apache.qpid.client.message; -import java.lang.ref.SoftReference; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.HashSet; -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; @@ -54,8 +40,22 @@ import org.apache.qpid.transport.MessageDeliveryPriority; import org.apache.qpid.transport.MessageProperties; import org.apache.qpid.transport.ReplyTo; import org.apache.qpid.transport.TransportException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import javax.jms.DeliveryMode; +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.MessageFormatException; +import javax.jms.MessageNotWriteableException; +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; /** * This extends AbstractAMQMessageDelegate which contains common code between @@ -65,7 +65,22 @@ import org.slf4j.LoggerFactory; public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate { private static final Logger _logger = LoggerFactory.getLogger(AMQMessageDelegate_0_10.class); - private static final Map<ReplyTo, SoftReference<Destination>> _destinationCache = Collections.synchronizedMap(new HashMap<ReplyTo, SoftReference<Destination>>()); + + 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"; @@ -241,12 +256,8 @@ public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate } else { - Destination dest = null; - SoftReference<Destination> ref = _destinationCache.get(replyTo); - if (ref != null) - { - dest = ref.get(); - } + Destination dest = _destinationCache.get(replyTo); + if (dest == null) { String exchange = replyTo.getExchange(); @@ -254,14 +265,13 @@ public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate if (AMQDestination.getDefaultDestSyntax() == AMQDestination.DestSyntax.BURL) { - dest = generateDestination(new AMQShortString(exchange), new AMQShortString(routingKey)); } else { dest = convertToAddressBasedDestination(exchange,routingKey,null); } - _destinationCache.put(replyTo, new SoftReference<Destination>(dest)); + _destinationCache.put(replyTo, dest); } return dest; @@ -271,6 +281,7 @@ public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate private Destination convertToAddressBasedDestination(String exchange, String routingKey, String subject) { String addr; + boolean isQueue = true; if ("".equals(exchange)) // type Queue { subject = (subject == null) ? "" : "/" + subject; @@ -279,11 +290,24 @@ public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate else { addr = exchange + "/" + routingKey; + isQueue = false; } try { - return AMQDestination.createDestination("ADDR:" + addr); + AMQDestination dest = (AMQDestination)AMQDestination.createDestination("ADDR:" + addr); + 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) { @@ -341,13 +365,11 @@ public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate jmse.setLinkedException(e); throw jmse; } - } - + final ReplyTo replyTo = new ReplyTo(amqd.getExchangeName().toString(), amqd.getRoutingKey().toString()); - _destinationCache.put(replyTo, new SoftReference<Destination>(destination)); + _destinationCache.put(replyTo, destination); _messageProps.setReplyTo(replyTo); - } public Destination getJMSDestination() throws JMSException @@ -560,6 +582,10 @@ public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate { return ((Short)o).shortValue(); } + else if(o instanceof String) + { + return Short.valueOf((String) o); + } else { try @@ -587,6 +613,10 @@ public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate { return ((Integer)o).intValue(); } + else if(o instanceof String) + { + return Integer.valueOf((String) o); + } else { try @@ -613,6 +643,10 @@ public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate { return ((Long)o).longValue(); } + else if(o instanceof String) + { + return Long.valueOf((String) o); + } else { try @@ -933,7 +967,7 @@ public class AMQMessageDelegate_0_10 extends AbstractAMQMessageDelegate // 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"); +// 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" 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 index ab7061c382..fe9f9f4d00 100644 --- 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 @@ -21,27 +21,47 @@ package org.apache.qpid.client.message; +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.client.JMSAMQException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.BasicContentHeaderProperties; +import org.apache.qpid.framing.ContentHeaderProperties; +import org.apache.qpid.url.AMQBindingURL; +import org.apache.qpid.url.BindingURL; + +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.MessageNotWriteableException; import java.net.URISyntaxException; import java.util.Collections; import java.util.Enumeration; +import java.util.LinkedHashMap; import java.util.Map; import java.util.UUID; -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.MessageNotWriteableException; - -import org.apache.qpid.client.*; -import org.apache.qpid.collections.ReferenceMap; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.framing.ContentHeaderProperties; -import org.apache.qpid.url.AMQBindingURL; -import org.apache.qpid.url.BindingURL; public class AMQMessageDelegate_0_8 extends AbstractAMQMessageDelegate { - private static final Map _destinationCache = Collections.synchronizedMap(new ReferenceMap()); + 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"; @@ -229,7 +249,7 @@ public class AMQMessageDelegate_0_8 extends AbstractAMQMessageDelegate } else { - Destination dest = (Destination) _destinationCache.get(replyToEncoding); + Destination dest = _destinationCache.get(replyToEncoding); if (dest == null) { try @@ -266,7 +286,7 @@ public class AMQMessageDelegate_0_8 extends AbstractAMQMessageDelegate final AMQDestination amqd = (AMQDestination) destination; final AMQShortString encodedDestination = amqd.getEncodedName(); - _destinationCache.put(encodedDestination, destination); + _destinationCache.put(encodedDestination.asString(), destination); getContentHeaderProperties().setReplyTo(encodedDestination); } 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 index be71c8c657..11d99f5446 100644 --- 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 @@ -21,18 +21,17 @@ package org.apache.qpid.client.message; */ -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.nio.ByteBuffer; - -import javax.jms.JMSException; -import javax.jms.MessageFormatException; - 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"; @@ -68,7 +67,7 @@ public class AMQPEncodedMapMessage extends JMSMapMessage || (value instanceof Double) || (value instanceof String) || (value instanceof byte[]) || (value instanceof List) || (value instanceof Map) || (value instanceof UUID) || (value == null)) { - _map.put(propName, value); + getMap().put(propName, value); } else { @@ -82,7 +81,7 @@ public class AMQPEncodedMapMessage extends JMSMapMessage public ByteBuffer getData() { BBEncoder encoder = new BBEncoder(1024); - encoder.writeMap(_map); + encoder.writeMap(getMap()); return encoder.segment(); } @@ -94,22 +93,18 @@ public class AMQPEncodedMapMessage extends JMSMapMessage data.rewind(); BBDecoder decoder = new BBDecoder(); decoder.init(data); - _map = decoder.readMap(); + setMap(decoder.readMap()); } else { - _map.clear(); + getMap().clear(); } } // for testing public Map<String,Object> getMap() { - return _map; - } - - void setMap(Map<String,Object> map) - { - _map = map; + 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 index 2c38f153cb..f997862bb0 100644 --- 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 @@ -21,12 +21,11 @@ package org.apache.qpid.client.message; */ -import javax.jms.JMSException; +import org.apache.qpid.AMQException; +import javax.jms.JMSException; import java.nio.ByteBuffer; -import org.apache.qpid.AMQException; - public class AMQPEncodedMapMessageFactory extends AbstractJMSMessageFactory { 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 index 1b6c0c751d..1395f39b99 100644 --- 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 @@ -20,12 +20,6 @@ */ package org.apache.qpid.client.message; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.jms.JMSException; -import javax.jms.Session; - import org.apache.qpid.client.AMQAnyDestination; import org.apache.qpid.client.AMQDestination; import org.apache.qpid.client.AMQQueue; @@ -34,6 +28,11 @@ import org.apache.qpid.client.AMQTopic; import org.apache.qpid.exchange.ExchangeDefaults; import org.apache.qpid.framing.AMQShortString; +import javax.jms.JMSException; +import javax.jms.Session; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + /** * This abstract class provides exchange lookup functionality that is shared * between all MessageDelegates. Update facilities are provided so that the 0-10 @@ -122,18 +121,18 @@ public abstract class AbstractAMQMessageDelegate implements AMQMessageDelegate exchangeInfo = new ExchangeInfo(exchange.asString(),"",AMQDestination.UNKNOWN_TYPE); } - if ("topic".equals(exchangeInfo.exchangeType)) + if ("topic".equals(exchangeInfo.getExchangeType())) { dest = new AMQTopic(exchange, routingKey, null); } - else if ("direct".equals(exchangeInfo.exchangeType)) + else if ("direct".equals(exchangeInfo.getExchangeType())) { dest = new AMQQueue(exchange, routingKey, routingKey); } else { dest = new AMQAnyDestination(exchange, - new AMQShortString(exchangeInfo.exchangeType), + new AMQShortString(exchangeInfo.getExchangeType()), routingKey, false, false, @@ -224,9 +223,9 @@ public abstract class AbstractAMQMessageDelegate implements AMQMessageDelegate class ExchangeInfo { - String exchangeName; - String exchangeType; - int destType = AMQDestination.QUEUE_TYPE; + private String exchangeName; + private String exchangeType; + private int destType = AMQDestination.QUEUE_TYPE; public ExchangeInfo(String exchangeName, String exchangeType, int 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 index ddeb62fbf6..9c7bd0bdcf 100644 --- 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 @@ -21,26 +21,20 @@ package org.apache.qpid.client.message; -import java.io.ByteArrayOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.ByteBuffer; +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 org.apache.qpid.AMQException; -import org.apache.qpid.transport.util.Functions; +import java.nio.ByteBuffer; /** * @author Apache Software Foundation */ public abstract class AbstractBytesTypedMessage extends AbstractJMSMessage { - protected boolean _readableMessage = false; + private boolean _readableMessage = false; AbstractBytesTypedMessage(AMQMessageDelegateFactory delegateFactory, boolean fromReceivedMessage) { @@ -81,6 +75,11 @@ public abstract class AbstractBytesTypedMessage extends AbstractJMSMessage _readableMessage = false; } + protected void setReadable(boolean readable) + { + _readableMessage = readable; + } + public String toBodyString() throws JMSException { 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 index f713554bfb..d1e43447cc 100644 --- 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 @@ -20,16 +20,15 @@ */ package org.apache.qpid.client.message; -import java.nio.ByteBuffer; -import java.util.Enumeration; -import java.util.UUID; +import org.apache.qpid.AMQException; +import org.apache.qpid.client.AMQSession; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.MessageNotWriteableException; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.AMQSession; +import java.nio.ByteBuffer; +import java.util.Enumeration; +import java.util.UUID; public abstract class AbstractJMSMessage implements org.apache.qpid.jms.Message { @@ -37,7 +36,7 @@ public abstract class AbstractJMSMessage implements org.apache.qpid.jms.Message /** If the acknowledge mode is CLIENT_ACKNOWLEDGE the session is required */ - protected AMQMessageDelegate _delegate; + private AMQMessageDelegate _delegate; private boolean _redelivered; private boolean _receivedFromServer; 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 index 16b71db77e..608567674a 100644 --- 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 @@ -20,27 +20,25 @@ */ package org.apache.qpid.client.message; +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.ContentBody; import org.apache.qpid.framing.ContentHeaderBody; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.transport.MessageProperties; import org.apache.qpid.transport.DeliveryProperties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.apache.qpid.transport.MessageProperties; import javax.jms.JMSException; - +import java.nio.ByteBuffer; import java.util.Iterator; import java.util.List; -import java.nio.ByteBuffer; - public abstract class AbstractJMSMessageFactory implements MessageFactory { private static final Logger _logger = LoggerFactory.getLogger(AbstractJMSMessageFactory.class); @@ -59,25 +57,25 @@ public abstract class AbstractJMSMessageFactory implements MessageFactory { if (debug) { - _logger.debug("Non-fragmented message body (bodySize=" + contentHeader.bodySize + ")"); + _logger.debug("Non-fragmented message body (bodySize=" + contentHeader.getBodySize() + ")"); } - data = ByteBuffer.wrap(((ContentBody) bodies.get(0))._payload); + data = ByteBuffer.wrap(((ContentBody) bodies.get(0)).getPayload()); } else if (bodies != null) { if (debug) { _logger.debug("Fragmented message body (" + bodies - .size() + " frames, bodySize=" + contentHeader.bodySize + ")"); + .size() + " frames, bodySize=" + contentHeader.getBodySize() + ")"); } - data = ByteBuffer.allocate((int) contentHeader.bodySize); // XXX: Is cast a problem? + 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._payload); + final ByteBuffer payload = ByteBuffer.wrap(cb.getPayload()); if(payload.isDirect() || payload.isReadOnly()) { data.put(payload); 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 index 49ae8c14b2..31a0440b04 100644 --- 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 @@ -20,35 +20,39 @@ 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; +import java.util.HashMap; +import java.util.Map; + public class 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; - } + 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>(); - for (AMQShortString key: ft.keySet() ) - { - map.put(key.asString(), ft.getObject(key)); - } + public static Map<String,Object> convertToMap(FieldTable ft) + { + Map<String,Object> map = new HashMap<String,Object>(); + for (AMQShortString key: ft.keySet() ) + { + map.put(key.asString(), ft.getObject(key)); + } - return map; - } + 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 index e252bdb719..b0320d0f4e 100644 --- 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 @@ -20,21 +20,13 @@ */ package org.apache.qpid.client.message; -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; +import org.apache.qpid.AMQException; 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.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; +import java.nio.ByteBuffer; public class JMSBytesMessage extends AbstractBytesTypedMessage implements BytesMessage { @@ -60,7 +52,7 @@ public class JMSBytesMessage extends AbstractBytesTypedMessage implements BytesM public void reset() { - _readableMessage = true; + setReadable(true); if(_typedBytesContentReader != null) { 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 index 89561b88eb..c8c01f16ee 100644 --- 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 @@ -20,12 +20,9 @@ */ package org.apache.qpid.client.message; -import javax.jms.JMSException; - import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; +import javax.jms.JMSException; import java.nio.ByteBuffer; public class JMSBytesMessageFactory extends AbstractJMSMessageFactory 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 index 52c0eb263b..122a5c4ef2 100644 --- 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 @@ -20,18 +20,17 @@ */ package org.apache.qpid.client.message; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.Enumeration; +import org.apache.qpid.AMQPInvalidClassException; +import org.apache.qpid.framing.AMQShortString; +import org.apache.qpid.framing.FieldTable; import javax.jms.JMSException; import javax.jms.MessageFormatException; - +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; import java.nio.ByteBuffer; -import org.apache.qpid.AMQPInvalidClassException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; +import java.util.Enumeration; public final class JMSHeaderAdapter @@ -60,7 +59,7 @@ public final class JMSHeaderAdapter { Object str = getHeaders().getObject(string); - if (str == null || !(str instanceof String)) + if (!(str instanceof String)) { throw new MessageFormatException("getBoolean can't use " + string + " item."); } @@ -89,7 +88,7 @@ public final class JMSHeaderAdapter { Object str = getHeaders().getObject(string); - if (str == null || !(str instanceof String)) + if (!(str instanceof String)) { throw new MessageFormatException("getBoolean can't use " + string + " item."); } @@ -160,7 +159,7 @@ public final class JMSHeaderAdapter { Object str = getHeaders().getObject(string); - if (str == null || !(str instanceof String)) + if (!(str instanceof String)) { throw new MessageFormatException("getByte can't use " + string + " item."); } @@ -228,7 +227,7 @@ public final class JMSHeaderAdapter { Object str = getHeaders().getObject(string); - if (str == null || !(str instanceof String)) + if (!(str instanceof String)) { throw new MessageFormatException("getFloat can't use " + string + " item."); } @@ -285,7 +284,7 @@ public final class JMSHeaderAdapter s = String.valueOf(o); } } - }//else return s // null; + } } return s; @@ -527,7 +526,7 @@ public final class JMSHeaderAdapter // 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"); +// 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" 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 index fad24a968e..e18ed80f6d 100644 --- 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 @@ -20,17 +20,14 @@ */ package org.apache.qpid.client.message; -import org.apache.qpid.AMQException; - - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.apache.qpid.AMQException; + import javax.jms.JMSException; import javax.jms.MessageFormatException; - import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; @@ -42,7 +39,7 @@ public class JMSMapMessage extends AbstractJMSMessage implements javax.jms.MapMe public static final String MIME_TYPE = "jms/map-message"; - protected Map<String, Object> _map = new HashMap<String, Object>(); + private Map<String, Object> _map = new HashMap<String, Object>(); public JMSMapMessage(AMQMessageDelegateFactory delegateFactory) throws JMSException { @@ -486,4 +483,13 @@ public class JMSMapMessage extends AbstractJMSMessage implements javax.jms.MapMe 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 index 89408a5c3c..72bc8d59ea 100644 --- 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 @@ -20,10 +20,10 @@ */ package org.apache.qpid.client.message; -import javax.jms.JMSException; +import org.apache.qpid.AMQException; +import javax.jms.JMSException; import java.nio.ByteBuffer; -import org.apache.qpid.AMQException; public class JMSMapMessageFactory extends AbstractJMSMessageFactory { 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 index 7f733b9644..509fc9f7f1 100644 --- 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 @@ -20,16 +20,18 @@ */ package org.apache.qpid.client.message; -import java.io.*; -import java.nio.ByteBuffer; +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 org.apache.qpid.AMQException; -import org.apache.qpid.client.util.ClassLoadingAwareObjectInputStream; -import org.apache.qpid.util.ByteBufferInputStream; +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 { 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 index 4660c91c1f..a1727811ae 100644 --- 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 @@ -20,10 +20,10 @@ */ package org.apache.qpid.client.message; -import javax.jms.JMSException; +import org.apache.qpid.AMQException; +import javax.jms.JMSException; import java.nio.ByteBuffer; -import org.apache.qpid.AMQException; public class JMSObjectMessageFactory extends AbstractJMSMessageFactory { 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 index 5c93f6b6f0..b958d89515 100644 --- 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 @@ -20,15 +20,12 @@ */ package org.apache.qpid.client.message; +import org.apache.qpid.AMQException; + import javax.jms.JMSException; import javax.jms.StreamMessage; - import java.nio.ByteBuffer; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; - /** * @author Apache Software Foundation */ @@ -57,7 +54,7 @@ public class JMSStreamMessage extends AbstractBytesTypedMessage implements Strea public void reset() { - _readableMessage = true; + setReadable(true); if(_typedBytesContentReader != null) { 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 index 359f5157f3..56fa8e5e38 100644 --- 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 @@ -20,12 +20,11 @@ */ package org.apache.qpid.client.message; -import javax.jms.JMSException; +import org.apache.qpid.AMQException; +import javax.jms.JMSException; import java.nio.ByteBuffer; -import org.apache.qpid.AMQException; - public class JMSStreamMessageFactory extends AbstractJMSMessageFactory { protected AbstractJMSMessage createMessage(AMQMessageDelegate delegate, ByteBuffer data) throws AMQException 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 index acf3a0ca14..097a3bb5c0 100644 --- 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 @@ -20,8 +20,11 @@ */ package org.apache.qpid.client.message; -import java.io.DataInputStream; -import java.io.UnsupportedEncodingException; +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; @@ -29,16 +32,6 @@ import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; -import javax.jms.JMSException; -import javax.jms.MessageFormatException; - -import org.apache.qpid.AMQException; -import org.apache.qpid.client.CustomJMSXProperty; -import org.apache.qpid.framing.AMQFrameDecodingException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; -import org.apache.qpid.util.Strings; - public class JMSTextMessage extends AbstractJMSMessage implements javax.jms.TextMessage { private static final String MIME_TYPE = "text/plain"; 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 index d1af32c10a..0b28e6ca85 100644 --- 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 @@ -20,12 +20,10 @@ */ package org.apache.qpid.client.message; -import javax.jms.JMSException; +import org.apache.qpid.AMQException; +import javax.jms.JMSException; import java.nio.ByteBuffer; -import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.BasicContentHeaderProperties; public class JMSTextMessageFactory extends AbstractJMSMessageFactory { 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 index e606ef11c9..5abd02f150 100644 --- 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 @@ -22,10 +22,17 @@ package org.apache.qpid.client.message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.apache.qpid.client.AMQSession; -import javax.jms.*; +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 @@ -34,7 +41,7 @@ public class MessageConverter /** * Log4J logger */ - protected final Logger _logger = LoggerFactory.getLogger(getClass()); + private final Logger _logger = LoggerFactory.getLogger(getClass()); /** * AbstractJMSMessage which will hold the converted message 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 index 93c2872b2e..70c6aa4c75 100644 --- 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 @@ -20,10 +20,6 @@ */ 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; @@ -33,6 +29,9 @@ import org.apache.qpid.framing.ContentHeaderBody; import org.apache.qpid.transport.DeliveryProperties; import org.apache.qpid.transport.MessageProperties; +import javax.jms.JMSException; +import java.util.List; + public interface MessageFactory { 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 index 15ad3ed89f..fa39b4c93c 100644 --- 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 @@ -20,12 +20,8 @@ */ package org.apache.qpid.client.message; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.nio.ByteBuffer; - -import javax.jms.JMSException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.apache.qpid.AMQException; import org.apache.qpid.client.AMQQueue; @@ -34,19 +30,21 @@ 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.Struct; +import org.apache.qpid.transport.DeliveryProperties; import org.apache.qpid.transport.MessageProperties; import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.DeliveryProperties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import javax.jms.JMSException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class MessageFactoryRegistry { /** * This class logger */ - protected final Logger _logger = LoggerFactory.getLogger(getClass()); + private final Logger _logger = LoggerFactory.getLogger(getClass()); private final Map<String, MessageFactory> _mimeStringToFactoryMap = new HashMap<String, MessageFactory>(); private final Map<AMQShortString, MessageFactory> _mimeShortStringToFactoryMap = 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 index b30afafa35..663dfd39b1 100644 --- 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 @@ -25,6 +25,9 @@ package org.apache.qpid.client.message; */ public class QpidMessageProperties { + private QpidMessageProperties() + { + } public static final String QPID_SUBJECT = "qpid.subject"; diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/message/TypedBytesContentReader.java b/qpid/java/client/src/main/java/org/apache/qpid/client/message/TypedBytesContentReader.java index 1ae25eb1ed..b00ac7e34b 100644 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/message/TypedBytesContentReader.java +++ b/qpid/java/client/src/main/java/org/apache/qpid/client/message/TypedBytesContentReader.java @@ -455,7 +455,7 @@ class TypedBytesContentReader implements TypedBytesCodes ByteBuffer dup = _data.duplicate(); int pos = _data.position(); byte b; - while((b = _data.get()) != 0); + while((b = _data.get()) != 0) {}; dup.limit(_data.position()-1); return _charsetDecoder.decode(dup).toString(); 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 index e2cb36a030..bb0e3b447f 100644 --- 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 @@ -21,7 +21,6 @@ package org.apache.qpid.client.message; import org.apache.qpid.client.AMQSession; -import org.apache.qpid.client.BasicMessageConsumer; /** 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 index ce87a112c9..5ed98dc8ea 100644 --- 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 @@ -20,15 +20,15 @@ */ package org.apache.qpid.client.message; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - 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. @@ -44,7 +44,7 @@ public class UnprocessedMessage_0_8 extends UnprocessedMessage private AMQShortString _exchange; private AMQShortString _routingKey; private final long _deliveryId; - protected boolean _redelivered; + private boolean _redelivered; private BasicDeliverBody _deliverBody; private ContentHeaderBody _contentHeader; @@ -87,13 +87,13 @@ public class UnprocessedMessage_0_8 extends UnprocessedMessage public void receiveBody(ContentBody body) { - if (body._payload != null) + if (body.getPayload() != null) { - final long payloadSize = body._payload.length; + final long payloadSize = body.getPayload().length; if (_bodies == null) { - if (payloadSize == getContentHeader().bodySize) + if (payloadSize == getContentHeader().getBodySize()) { _bodies = Collections.singletonList(body); } @@ -124,7 +124,7 @@ public class UnprocessedMessage_0_8 extends UnprocessedMessage public boolean isAllBodyDataReceived() { - return _bytesReceived == getContentHeader().bodySize; + return _bytesReceived == getContentHeader().getBodySize(); } public BasicDeliverBody getDeliverBody() 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 index 368ec60525..318fe32d36 100644 --- 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 @@ -20,22 +20,21 @@ */ 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.Node.ExchangeNode; import org.apache.qpid.client.messaging.address.Node.QueueNode; -import org.apache.qpid.client.messaging.address.Node.UnknownNodeType; import org.apache.qpid.configuration.Accessor; import org.apache.qpid.configuration.Accessor.MapAccessor; import org.apache.qpid.messaging.Address; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; + /** * Utility class for extracting information from the address class */ 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 index c73d800b14..41f6725c8f 100644 --- 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 @@ -29,16 +29,16 @@ public class Link public enum Reliability { UNRELIABLE, AT_MOST_ONCE, AT_LEAST_ONCE, EXACTLY_ONCE } - protected String name; - protected String _filter; - protected FilterType _filterType = FilterType.SUBJECT; - protected boolean _isNoLocal; - protected boolean _isDurable; - protected int _consumerCapacity = 0; - protected int _producerCapacity = 0; - protected Node node; - protected Subscription subscription; - protected Reliability reliability = Reliability.AT_LEAST_ONCE; + private String name; + private String _filter; + private FilterType _filterType = FilterType.SUBJECT; + private boolean _isNoLocal; + private boolean _isDurable; + private int _consumerCapacity = 0; + private int _producerCapacity = 0; + private Node node; + private Subscription subscription; + private Reliability reliability = Reliability.AT_LEAST_ONCE; public Reliability getReliability() { 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 index c98b194334..0da0327885 100644 --- 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 @@ -21,25 +21,28 @@ package org.apache.qpid.client.messaging.address; +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.client.AMQDestination.Binding; + import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; -import javax.naming.OperationNotSupportedException; - -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.client.AMQDestination.Binding; - public abstract class Node { - protected int _nodeType = AMQDestination.UNKNOWN_TYPE; - protected boolean _isDurable; - protected boolean _isAutoDelete; - protected String _alternateExchange; - protected List<Binding> _bindings = new ArrayList<Binding>(); - protected Map<String,Object> _declareArgs = Collections.emptyMap(); - + private int _nodeType = AMQDestination.UNKNOWN_TYPE; + private boolean _isDurable; + private boolean _isAutoDelete; + private String _alternateExchange; + private List<Binding> _bindings = new ArrayList<Binding>(); + private Map<String,Object> _declareArgs = Collections.emptyMap(); + + protected Node(int nodeType) + { + _nodeType = nodeType; + } + public int getType() { return _nodeType; @@ -101,12 +104,12 @@ public abstract class Node public static class QueueNode extends Node { - protected boolean _isExclusive; - protected QpidQueueOptions _queueOptions = new QpidQueueOptions(); + private boolean _isExclusive; + private QpidQueueOptions _queueOptions = new QpidQueueOptions(); public QueueNode() { - _nodeType = AMQDestination.QUEUE_TYPE; + super(AMQDestination.QUEUE_TYPE); } public boolean isExclusive() @@ -122,12 +125,12 @@ public abstract class Node public static class ExchangeNode extends Node { - protected QpidExchangeOptions _exchangeOptions = new QpidExchangeOptions(); - protected String _exchangeType; + private QpidExchangeOptions _exchangeOptions = new QpidExchangeOptions(); + private String _exchangeType; public ExchangeNode() { - _nodeType = AMQDestination.TOPIC_TYPE; + super(AMQDestination.TOPIC_TYPE); } public String getExchangeType() @@ -144,5 +147,9 @@ public abstract class Node public static class UnknownNodeType extends Node { + public UnknownNodeType() + { + super(AMQDestination.UNKNOWN_TYPE); + } } } 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 index 8911d4ee3e..d380402da7 100644 --- 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 @@ -20,18 +20,9 @@ */ package org.apache.qpid.client.protocol; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.net.SocketAddress; -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; +import org.apache.qpid.util.BytesDataOutput; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.apache.qpid.AMQConnectionClosedException; import org.apache.qpid.AMQDisconnectedException; @@ -66,8 +57,16 @@ import org.apache.qpid.protocol.ProtocolEngine; import org.apache.qpid.thread.Threading; import org.apache.qpid.transport.Sender; import org.apache.qpid.transport.network.NetworkConnection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import java.io.IOException; +import java.net.SocketAddress; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArraySet; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; /** * AMQProtocolHandler is the client side protocol handler for AMQP, it handles all protocol events received from the @@ -300,7 +299,6 @@ public class AMQProtocolHandler implements ProtocolEngine { if (_failoverState == FailoverState.NOT_STARTED) { - // if (!(cause instanceof AMQUndeliveredException) && (!(cause instanceof AMQAuthenticationException))) if ((cause instanceof AMQConnectionClosedException) || cause instanceof IOException) { _logger.info("Exception caught therefore going to attempt failover: " + cause, cause); @@ -314,7 +312,7 @@ public class AMQProtocolHandler implements ProtocolEngine } // FIXME Need to correctly handle other exceptions. Things like ... - // if (cause instanceof AMQChannelClosedException) + // 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 @@ -865,160 +863,6 @@ public class AMQProtocolHandler implements ProtocolEngine return _suggestedProtocolVersion; } - private static class BytesDataOutput implements DataOutput - { - int _pos = 0; - byte[] _buf; - - public BytesDataOutput(byte[] buf) - { - _buf = buf; - } - - public void setBuffer(byte[] buf) - { - _buf = buf; - _pos = 0; - } - - public void reset() - { - _pos = 0; - } - - public int length() - { - return _pos; - } - - public void write(int b) - { - _buf[_pos++] = (byte) b; - } - - public void write(byte[] b) - { - System.arraycopy(b, 0, _buf, _pos, b.length); - _pos+=b.length; - } - - - public void write(byte[] b, int off, int len) - { - System.arraycopy(b, off, _buf, _pos, len); - _pos+=len; - - } - - public void writeBoolean(boolean v) - { - _buf[_pos++] = v ? (byte) 1 : (byte) 0; - } - - public void writeByte(int v) - { - _buf[_pos++] = (byte) v; - } - - public void writeShort(int v) - { - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte) v; - } - - public void writeChar(int v) - { - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte) v; - } - - public void writeInt(int v) - { - _buf[_pos++] = (byte) (v >>> 24); - _buf[_pos++] = (byte) (v >>> 16); - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte) v; - } - - public void writeLong(long v) - { - _buf[_pos++] = (byte) (v >>> 56); - _buf[_pos++] = (byte) (v >>> 48); - _buf[_pos++] = (byte) (v >>> 40); - _buf[_pos++] = (byte) (v >>> 32); - _buf[_pos++] = (byte) (v >>> 24); - _buf[_pos++] = (byte) (v >>> 16); - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte)v; - } - - public void writeFloat(float v) - { - writeInt(Float.floatToIntBits(v)); - } - - public void writeDouble(double v) - { - writeLong(Double.doubleToLongBits(v)); - } - - public void writeBytes(String s) - { - int len = s.length(); - for (int i = 0 ; i < len ; i++) - { - _buf[_pos++] = ((byte)s.charAt(i)); - } - } - - public void writeChars(String s) - { - int len = s.length(); - for (int i = 0 ; i < len ; i++) - { - int v = s.charAt(i); - _buf[_pos++] = (byte) (v >>> 8); - _buf[_pos++] = (byte) v; - } - } - - public void writeUTF(String s) - { - int strlen = s.length(); - - int pos = _pos; - _pos+=2; - - - for (int i = 0; i < strlen; i++) - { - int c = s.charAt(i); - if ((c >= 0x0001) && (c <= 0x007F)) - { - c = s.charAt(i); - _buf[_pos++] = (byte) c; - - } - else if (c > 0x07FF) - { - _buf[_pos++] = (byte) (0xE0 | ((c >> 12) & 0x0F)); - _buf[_pos++] = (byte) (0x80 | ((c >> 6) & 0x3F)); - _buf[_pos++] = (byte) (0x80 | (c & 0x3F)); - } - else - { - _buf[_pos++] = (byte) (0xC0 | ((c >> 6) & 0x1F)); - _buf[_pos++] = (byte) (0x80 | (c & 0x3F)); - } - } - - int len = _pos - (pos + 2); - - _buf[pos++] = (byte) (len >>> 8); - _buf[pos] = (byte) len; - } - - } } 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 index b7253e6e9c..af57fd98fc 100644 --- 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 @@ -20,11 +20,8 @@ */ 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; @@ -48,8 +45,11 @@ import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.protocol.AMQVersionAwareProtocolSession; import org.apache.qpid.transport.Sender; import org.apache.qpid.transport.TransportException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import javax.jms.JMSException; +import javax.security.sasl.SaslClient; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; /** * Wrapper for protocol session that provides type-safe access to session attributes. <p/> The underlying protocol @@ -73,16 +73,11 @@ public class AMQProtocolSession implements AMQVersionAwareProtocolSession protected static final String SASL_CLIENT = "SASLClient"; - /** - * The handler from which this session was created and which is used to handle protocol events. We send failover - * events to the handler. - */ - protected final AMQProtocolHandler _protocolHandler; + private final AMQProtocolHandler _protocolHandler; - /** Maps from the channel id to the AMQSession that it represents. */ - protected ConcurrentMap<Integer, AMQSession> _channelId2SessionMap = new ConcurrentHashMap<Integer, AMQSession>(); + private ConcurrentMap<Integer, AMQSession> _channelId2SessionMap = new ConcurrentHashMap<Integer, AMQSession>(); - protected ConcurrentMap _closingChannels = new ConcurrentHashMap(); + private ConcurrentMap _closingChannels = new ConcurrentHashMap(); /** * Maps from a channel id to an unprocessed message. This is used to tie together the JmsDeliverBody (which arrives @@ -91,20 +86,17 @@ public class AMQProtocolSession implements AMQVersionAwareProtocolSession private final ConcurrentMap<Integer, UnprocessedMessage> _channelId2UnprocessedMsgMap = new ConcurrentHashMap<Integer, UnprocessedMessage>(); private final UnprocessedMessage[] _channelId2UnprocessedMsgArray = new UnprocessedMessage[16]; - /** Counter to ensure unique queue names */ - protected int _queueId = 1; - protected final Object _queueIdLock = new Object(); + private int _queueId = 1; + private final Object _queueIdLock = new Object(); private ProtocolVersion _protocolVersion; -// private VersionSpecificRegistry _registry = -// MainRegistry.getVersionSpecificRegistry(ProtocolVersion.getLatestSupportedVersion()); private MethodRegistry _methodRegistry = MethodRegistry.getMethodRegistry(ProtocolVersion.getLatestSupportedVersion()); private MethodDispatcher _methodDispatcher; - protected final AMQConnection _connection; + private final AMQConnection _connection; private ConnectionTuneParameters _connectionTuneParameters; @@ -116,7 +108,10 @@ public class AMQProtocolSession implements AMQVersionAwareProtocolSession { _protocolHandler = protocolHandler; _protocolVersion = connection.getProtocolVersion(); - _logger.info("Using ProtocolVersion for Session:" + _protocolVersion); + if (_logger.isDebugEnabled()) + { + _logger.debug("Using ProtocolVersion for Session:" + _protocolVersion); + } _methodDispatcher = ClientMethodDispatcherImpl.newMethodDispatcher(ProtocolVersion.getLatestSupportedVersion(), this); _connection = connection; @@ -223,7 +218,7 @@ public class AMQProtocolSession implements AMQVersionAwareProtocolSession } msg.setContentHeader(contentHeader); - if (contentHeader.bodySize == 0) + if (contentHeader.getBodySize() == 0) { deliverMessageToAMQSession(channelId, msg); } @@ -310,7 +305,10 @@ public class AMQProtocolSession implements AMQVersionAwareProtocolSession */ public void closeSession(AMQSession session) { - _logger.debug("closeSession called on protocol session for session " + session.getChannelId()); + if (_logger.isDebugEnabled()) + { + _logger.debug("closeSession called on protocol session for session " + session.getChannelId()); + } final int channelId = session.getChannelId(); if (channelId <= 0) { @@ -401,7 +399,10 @@ public class AMQProtocolSession implements AMQVersionAwareProtocolSession public void setProtocolVersion(final ProtocolVersion pv) { - _logger.info("Setting ProtocolVersion to :" + pv); + if (_logger.isDebugEnabled()) + { + _logger.debug("Setting ProtocolVersion to :" + pv); + } _protocolVersion = pv; _methodRegistry = MethodRegistry.getMethodRegistry(pv); _methodDispatcher = ClientMethodDispatcherImpl.newMethodDispatcher(pv, this); @@ -470,4 +471,55 @@ public class AMQProtocolSession implements AMQVersionAwareProtocolSession { 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; + } } 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 index 2bc609ebf2..b865c51cb7 100644 --- 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 @@ -20,12 +20,7 @@ */ package org.apache.qpid.client.protocol; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.ReentrantLock; - import org.apache.qpid.AMQException; -import org.apache.qpid.AMQTimeoutException; import org.apache.qpid.client.failover.FailoverException; import org.apache.qpid.client.util.BlockingWaiter; import org.apache.qpid.framing.AMQMethodBody; @@ -68,7 +63,7 @@ public abstract class BlockingMethodFrameListener extends BlockingWaiter<AMQMeth { /** Holds the channel id for the channel upon which this listener is waiting for a response. */ - protected int _channelId; + private int _channelId; /** * Creates a new method listener, that filters incoming method to just those that match the specified channel id. diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java b/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java index d44faeab04..d387a8ba93 100644 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java +++ b/qpid/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java @@ -24,6 +24,10 @@ class HeartbeatDiagnostics { private static final Diagnostics _impl = init(); + private HeartbeatDiagnostics() + { + } + private static Diagnostics init() { return Boolean.getBoolean("amqj.heartbeat.diagnostics") ? new On() : new Off(); 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 index 67dd1a58b6..068e105731 100644 --- 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 @@ -20,10 +20,10 @@ */ package org.apache.qpid.client.security; -import javax.security.auth.callback.CallbackHandler; - 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 index 14bae68561..6b2448e385 100644 --- 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 @@ -20,6 +20,11 @@ */ package org.apache.qpid.client.security; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.qpid.util.FileUtils; + import java.io.IOException; import java.io.InputStream; import java.util.Collection; @@ -33,10 +38,6 @@ import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; -import org.apache.qpid.util.FileUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** * 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 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 index 2b4261b4b7..9198903408 100644 --- 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 @@ -20,13 +20,12 @@ */ package org.apache.qpid.client.security; -import org.apache.qpid.util.FileUtils; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import javax.security.sasl.SaslClientFactory; +import org.apache.qpid.util.FileUtils; +import javax.security.sasl.SaslClientFactory; import java.io.IOException; import java.io.InputStream; import java.security.Security; @@ -63,6 +62,10 @@ public class DynamicSaslRegistrar /** 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 void registerSaslProviders() { @@ -122,47 +125,6 @@ public class DynamicSaslRegistrar } /** - * Either attempts to open the specified filename as an input stream, or uses the default SASL configuration - * resource. - * - * @param filename The name of the file to get the SASL properties from, null to use the default. - * - * @return An input stream to read the dynamic SASL configuration from, or null if one could not be opened. - */ - /*private static InputStream openPropertiesInputStream(String filename) - { - InputStream is = null; - - // Flag to indicate whether the default resource should be used. By default this is true, so that the default - // is used when opening the file fails. - boolean useDefault = true; - - // Try to open the file if one was specified. - if (filename != null) - { - try - { - is = new BufferedInputStream(new FileInputStream(new File(filename))); - - // Clear the default flag because the file was succesfully opened. - useDefault = false; - } - catch (FileNotFoundException e) - { - _logger.error("Unable to read from file " + filename + ": " + e, e); - } - } - - // Load the default resource if a file was not specified, or if opening the file failed. - if (useDefault) - { - is = CallbackHandlerRegistry.class.getResourceAsStream(DEFAULT_RESOURCE_NAME); - } - - return is; - }*/ - - /** * 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. 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 index 828d26ed0d..4a91f805f6 100644 --- 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 @@ -24,9 +24,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.security.sasl.SaslClientFactory; - import java.security.Provider; -import java.security.Security; import java.util.Map; /** @@ -53,7 +51,6 @@ public class JCAProvider extends Provider super("AMQSASLProvider-Client", 1.0, "A JCA provider that registers all " + "AMQ SASL providers that want to be registered"); register(providerMap); -// Security.addProvider(this); } /** 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 index 6ec83f0a23..fe24d48329 100644 --- 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 @@ -20,17 +20,16 @@ */ package org.apache.qpid.client.security; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; +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 org.apache.qpid.jms.ConnectionURL; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; public class UsernameHashedPasswordCallbackHandler implements AMQCallbackHandler { 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 index ad088722c8..99b5f247ef 100644 --- 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 @@ -20,14 +20,13 @@ */ package org.apache.qpid.client.security; -import java.io.IOException; +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 org.apache.qpid.jms.ConnectionURL; +import java.io.IOException; public class UsernamePasswordCallbackHandler implements AMQCallbackHandler { 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 index f8a25c630c..5f9a240e8f 100644 --- 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 @@ -20,6 +20,9 @@ */ 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; @@ -27,9 +30,6 @@ import javax.security.auth.callback.PasswordCallback; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslException; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.framing.FieldTableFactory; - /** * Implements the "AMQPlain" authentication protocol that uses FieldTables to send username and pwd. * 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 index 30cc786890..f1d7da2e94 100644 --- 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 @@ -20,13 +20,12 @@ */ package org.apache.qpid.client.security.amqplain; -import java.util.Map; - import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.Sasl; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslClientFactory; import javax.security.sasl.SaslException; +import java.util.Map; public class AmqPlainSaslClientFactory implements SaslClientFactory { 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 index de698f87c6..283ba5f632 100644 --- 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 @@ -20,14 +20,12 @@ */ package org.apache.qpid.client.security.anonymous; -import java.util.Arrays; -import java.util.Map; - -import javax.security.sasl.Sasl; +import javax.security.auth.callback.CallbackHandler; import javax.security.sasl.SaslClient; import javax.security.sasl.SaslClientFactory; import javax.security.sasl.SaslException; -import javax.security.auth.callback.CallbackHandler; +import java.util.Arrays; +import java.util.Map; public class AnonymousSaslClientFactory implements SaslClientFactory { 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 index 22bb1ac156..cb989f7919 100644 --- 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 @@ -20,15 +20,12 @@ */ package org.apache.qpid.client.security.crammd5hashed; -import org.apache.qpid.client.security.amqplain.AmqPlainSaslClient; - -import javax.security.sasl.SaslClientFactory; +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 javax.security.sasl.Sasl; -import javax.security.auth.callback.CallbackHandler; import java.util.Map; -import java.security.Security; public class CRAMMD5HashedSaslClientFactory implements SaslClientFactory { 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 index 2c99b9a97b..f7d8b2bf35 100644 --- 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 @@ -20,8 +20,8 @@ */ package org.apache.qpid.client.state; -import org.apache.qpid.framing.AMQMethodBody; import org.apache.qpid.AMQException; +import org.apache.qpid.framing.AMQMethodBody; public class AMQMethodNotImplementedException extends AMQException { 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 index 0d6fc727c1..7d028e022a 100644 --- 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 @@ -20,16 +20,17 @@ */ package org.apache.qpid.client.state; +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.*; +import org.apache.qpid.framing.AMQMethodBody; import org.apache.qpid.protocol.AMQMethodEvent; import org.apache.qpid.protocol.AMQMethodListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import java.util.Set; import java.util.List; +import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; /** @@ -62,7 +63,7 @@ public class AMQStateManager implements AMQMethodListener private static final long MAXIMUM_STATE_WAIT_TIME = Long.parseLong(System.getProperty("amqj.MaximumStateWait", "30000")); - protected final List<StateWaiter> _waiters = new CopyOnWriteArrayList<StateWaiter>(); + private final List<StateWaiter> _waiters = new CopyOnWriteArrayList<StateWaiter>(); private Exception _lastException; public AMQStateManager() @@ -110,7 +111,6 @@ public class AMQStateManager implements AMQMethodListener { B method = evt.getMethod(); - // StateAwareMethodListener handler = findStateTransitionHandler(_currentState, evt.getMethod()); method.execute(_protocolSession.getMethodDispatcher(), evt.getChannelId()); return true; } 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 index 17d04f4fa3..6b038e09c8 100644 --- 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 @@ -21,9 +21,8 @@ package org.apache.qpid.client.state; import org.apache.qpid.AMQException; -import org.apache.qpid.framing.AMQMethodBody; import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.protocol.AMQMethodEvent; +import org.apache.qpid.framing.AMQMethodBody; /** * A frame listener that is informed of the protocl state when invoked and has 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 index 732480e1c9..c8903d252f 100644 --- 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 @@ -20,11 +20,12 @@ */ package org.apache.qpid.client.state; -import org.apache.qpid.client.util.BlockingWaiter; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.AMQException; -import org.slf4j.LoggerFactory; 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; diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/transport/AMQNoTransportForProtocolException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/transport/AMQNoTransportForProtocolException.java deleted file mode 100644 index 6e47e2ce28..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/transport/AMQNoTransportForProtocolException.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.transport; - -import org.apache.qpid.jms.BrokerDetails; - -/** - * AMQNoTransportForProtocolException represents a connection failure where there is no transport medium to connect - * to the broker available. This may be the case if their is a error in the connection url, or an unsupported transport - * type is specified. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Represent absence of a transport medium. - * </table> - * - * @todo Error code never used. This is not an AMQException. - */ -public class AMQNoTransportForProtocolException extends AMQTransportConnectionException -{ - BrokerDetails _details; - - public AMQNoTransportForProtocolException(BrokerDetails details, String message, Throwable cause) - { - super(null, message, cause); - - _details = details; - } - - public String toString() - { - if (_details != null) - { - return super.toString() + _details.toString(); - } - else - { - return super.toString(); - } - } -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/transport/AMQTransportConnectionException.java b/qpid/java/client/src/main/java/org/apache/qpid/client/transport/AMQTransportConnectionException.java deleted file mode 100644 index 6bef6216bd..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/transport/AMQTransportConnectionException.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.transport; - -import org.apache.qpid.AMQException; -import org.apache.qpid.protocol.AMQConstant; - -/** - * AMQTransportConnectionException indicates a failure to establish a connection through the transporting medium, to - * an AMQP broker. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Represent failure to connect through the transport medium. - * </table> - * - * @todo Error code never used. This is not an AMQException. - */ -public class AMQTransportConnectionException extends AMQException -{ - public AMQTransportConnectionException(AMQConstant errorCode, String message, Throwable cause) - { - super(errorCode, message, cause); - } -} 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 index 1b483f6948..3c9a6e1500 100644 --- 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 @@ -20,13 +20,11 @@ */ package org.apache.qpid.client.transport; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.security.sasl.Sasl; -import javax.security.sasl.SaslClient; -import javax.security.sasl.SaslException; +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; @@ -38,11 +36,13 @@ 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 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 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; /** * @@ -85,7 +85,7 @@ public class ClientConnectionDelegate extends ClientDelegate protected SaslClient createSaslClient(List<Object> brokerMechs) throws ConnectionException, SaslException { final String brokerMechanisms = Strings.join(" ", brokerMechs); - final String restrictionList = _conSettings.getSaslMechs(); + final String restrictionList = getConnectionSettings().getSaslMechs(); final String selectedMech = CallbackHandlerRegistry.getInstance().selectMechanism(brokerMechanisms, restrictionList); if (selectedMech == null) { @@ -96,14 +96,14 @@ public class ClientConnectionDelegate extends ClientDelegate } Map<String,Object> saslProps = new HashMap<String,Object>(); - if (_conSettings.isUseSASLEncryption()) + 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, _conSettings.getSaslProtocol(), _conSettings.getSaslServerName(), saslProps, handler); + final SaslClient sc = Sasl.createSaslClient(new String[] {selectedMech}, null, getConnectionSettings().getSaslProtocol(), getConnectionSettings().getSaslServerName(), saslProps, handler); return sc; } @@ -137,7 +137,7 @@ public class ClientConnectionDelegate extends ClientDelegate private String getKerberosUser() { LOGGER.debug("Obtaining userID from kerberos"); - String service = _conSettings.getSaslProtocol() + "@" + _conSettings.getSaslServerName(); + String service = getConnectionSettings().getSaslProtocol() + "@" + getConnectionSettings().getSaslServerName(); GSSManager manager = GSSManager.getInstance(); try diff --git a/qpid/java/client/src/main/java/org/apache/qpid/client/transport/ITransportConnection.java b/qpid/java/client/src/main/java/org/apache/qpid/client/transport/ITransportConnection.java deleted file mode 100644 index 7a24d6e15a..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/client/transport/ITransportConnection.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.transport; - -import java.io.IOException; - -import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.jms.BrokerDetails; - -public interface ITransportConnection -{ - void connect(AMQProtocolHandler protocolHandler, BrokerDetails brokerDetail) - throws IOException; -} 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 index 03167561ef..f303d155c6 100644 --- 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 @@ -21,10 +21,6 @@ package org.apache.qpid.client.url; */ -import java.net.URI; -import java.net.URISyntaxException; -import java.util.StringTokenizer; - import org.apache.qpid.client.AMQBrokerDetails; import org.apache.qpid.client.AMQConnectionFactory; import org.apache.qpid.client.AMQConnectionURL; @@ -32,6 +28,10 @@ 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; 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 index 605e9ee154..d81868f924 100644 --- 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 @@ -17,13 +17,13 @@ */ 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; -import org.apache.qpid.client.AMQBrokerDetails; -import org.apache.qpid.jms.BrokerDetails; - /** * The format Qpid URL is based on the AMQP one. * The grammar is as follows: @@ -57,7 +57,6 @@ public class URLParser_0_10 private static final char PROPERTY_SEPARATOR_CHAR = ';'; private static final char ADDRESS_SEPERATOR_CHAR = ','; - //private static final char CLIENT_ID_TRANSPORT_SEPARATOR_CHAR = ':'; private static final char TRANSPORT_HOST_SEPARATOR_CHAR = ':'; private static final char HOST_PORT_SEPARATOR_CHAR = ':'; private static final char AT_CHAR = '@'; 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 index bec41644fc..80d171592f 100644 --- 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 @@ -20,16 +20,17 @@ */ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; /** * BlockingWaiter is a 'rendezvous' which delegates handling of @@ -84,7 +85,7 @@ public abstract class BlockingWaiter<T> private volatile Exception _error; /** Holds the incomming Object. */ - protected Object _doneObject = null; + private Object _doneObject = null; private AtomicBoolean _waiting = new AtomicBoolean(false); private boolean _closed = false; @@ -183,11 +184,7 @@ public abstract class BlockingWaiter<T> { _logger.error(e.getMessage(), e); // IGNORE -- //fixme this isn't ideal as being interrupted isn't equivellant to sucess - // if (!_ready && timeout != -1) - // { - // _error = new AMQException("Server did not respond timely"); - // _ready = true; - // } + } } } 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 index ee7fc533a3..c8d12142e6 100644 --- 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 @@ -20,13 +20,13 @@ */ package org.apache.qpid.client.util; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + 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 diff --git a/qpid/java/client/src/main/java/org/apache/qpid/collections/KeyValue.java b/qpid/java/client/src/main/java/org/apache/qpid/collections/KeyValue.java deleted file mode 100644 index e890aba968..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/collections/KeyValue.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2003-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.collections; - -/** - * Defines a simple key value pair. - * <p> - * A Map Entry has considerable additional semantics over and above a simple - * key-value pair. This interface defines the minimum key value, with just the - * two get methods. - * - * @since Commons Collections 3.0 - * @version $Revision$ $Date$ - * - * @author Stephen Colebourne - */ -public interface KeyValue { - - /** - * Gets the key from the pair. - * - * @return the key - */ - Object getKey(); - - /** - * Gets the value from the pair. - * - * @return the value - */ - Object getValue(); - -}
\ No newline at end of file diff --git a/qpid/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java b/qpid/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java deleted file mode 100644 index 1516c56e42..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java +++ /dev/null @@ -1,957 +0,0 @@ -/* - * Copyright 2001-2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.collections; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.ObjectOutputStream; -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.SoftReference; -import java.lang.ref.WeakReference; -import java.util.AbstractCollection; -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.ConcurrentModificationException; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -import org.apache.qpid.collections.keyvalue.DefaultMapEntry; - -/** - * Hash-based {@link Map} implementation that allows - * mappings to be removed by the garbage collector.<p> - * - * When you construct a <code>ReferenceMap</code>, you can - * specify what kind of references are used to store the - * map's keys and values. If non-hard references are - * used, then the garbage collector can remove mappings - * if a key or value becomes unreachable, or if the - * JVM's memory is running low. For information on how - * the different reference types behave, see - * {@link Reference}.<p> - * - * Different types of references can be specified for keys - * and values. The keys can be configured to be weak but - * the values hard, in which case this class will behave - * like a <a href="http://java.sun.com/j2se/1.4/docs/api/java/util/WeakHashMap.html"> - * <code>WeakHashMap</code></a>. However, you - * can also specify hard keys and weak values, or any other - * combination. The default constructor uses hard keys - * and soft values, providing a memory-sensitive cache.<p> - * - * The algorithms used are basically the same as those - * in {@link java.util.HashMap}. In particular, you - * can specify a load factor and capacity to suit your - * needs. All optional {@link Map} operations are - * supported.<p> - * - * However, this {@link Map} implementation does <I>not</I> - * allow null elements. Attempting to add a null key or - * or a null value to the map will raise a - * <code>NullPointerException</code>.<p> - * - * As usual, this implementation is not synchronized. You - * can use {@link java.util.Collections#synchronizedMap} to - * provide synchronized access to a <code>ReferenceMap</code>. - * - * @see java.lang.ref.Reference - * - * @deprecated Moved to map subpackage. Due to be removed in v4.0. - * @since Commons Collections 2.1 - * @version $Revision$ $Date$ - * - * @author Paul Jack - */ -public class ReferenceMap extends AbstractMap { - - /** - * For serialization. - */ - private static final long serialVersionUID = -3370601314380922368L; - - - /** - * Constant indicating that hard references should be used. - */ - final public static int HARD = 0; - - - /** - * Constant indicating that soft references should be used. - */ - final public static int SOFT = 1; - - - /** - * Constant indicating that weak references should be used. - */ - final public static int WEAK = 2; - - - // --- serialized instance variables: - - - /** - * The reference type for keys. Must be HARD, SOFT, WEAK. - * Note: I originally marked this field as final, but then this class - * didn't compile under JDK1.2.2. - * @serial - */ - private int keyType; - - - /** - * The reference type for values. Must be HARD, SOFT, WEAK. - * Note: I originally marked this field as final, but then this class - * didn't compile under JDK1.2.2. - * @serial - */ - private int valueType; - - - /** - * The threshold variable is calculated by multiplying - * table.length and loadFactor. - * Note: I originally marked this field as final, but then this class - * didn't compile under JDK1.2.2. - * @serial - */ - private float loadFactor; - - /** - * Should the value be automatically purged when the associated key has been collected? - */ - private boolean purgeValues = false; - - - // -- Non-serialized instance variables - - /** - * ReferenceQueue used to eliminate stale mappings. - * See purge. - */ - private transient ReferenceQueue queue = new ReferenceQueue(); - - - /** - * The hash table. Its length is always a power of two. - */ - private transient Entry[] table; - - - /** - * Number of mappings in this map. - */ - private transient int size; - - - /** - * When size reaches threshold, the map is resized. - * See resize(). - */ - private transient int threshold; - - - /** - * Number of times this map has been modified. - */ - private transient volatile int modCount; - - - /** - * Cached key set. May be null if key set is never accessed. - */ - private transient Set keySet; - - - /** - * Cached entry set. May be null if entry set is never accessed. - */ - private transient Set entrySet; - - - /** - * Cached values. May be null if values() is never accessed. - */ - private transient Collection values; - - - /** - * Constructs a new <code>ReferenceMap</code> that will - * use hard references to keys and soft references to values. - */ - public ReferenceMap() { - this(HARD, SOFT); - } - - /** - * Constructs a new <code>ReferenceMap</code> that will - * use the specified types of references. - * - * @param keyType the type of reference to use for keys; - * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} - * @param valueType the type of reference to use for values; - * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} - * @param purgeValues should the value be automatically purged when the - * key is garbage collected - */ - public ReferenceMap(int keyType, int valueType, boolean purgeValues) { - this(keyType, valueType); - this.purgeValues = purgeValues; - } - - /** - * Constructs a new <code>ReferenceMap</code> that will - * use the specified types of references. - * - * @param keyType the type of reference to use for keys; - * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} - * @param valueType the type of reference to use for values; - * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} - */ - public ReferenceMap(int keyType, int valueType) { - this(keyType, valueType, 16, 0.75f); - } - - /** - * Constructs a new <code>ReferenceMap</code> with the - * specified reference types, load factor and initial - * capacity. - * - * @param keyType the type of reference to use for keys; - * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} - * @param valueType the type of reference to use for values; - * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} - * @param capacity the initial capacity for the map - * @param loadFactor the load factor for the map - * @param purgeValues should the value be automatically purged when the - * key is garbage collected - */ - public ReferenceMap( - int keyType, - int valueType, - int capacity, - float loadFactor, - boolean purgeValues) { - this(keyType, valueType, capacity, loadFactor); - this.purgeValues = purgeValues; - } - - /** - * Constructs a new <code>ReferenceMap</code> with the - * specified reference types, load factor and initial - * capacity. - * - * @param keyType the type of reference to use for keys; - * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} - * @param valueType the type of reference to use for values; - * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} - * @param capacity the initial capacity for the map - * @param loadFactor the load factor for the map - */ - public ReferenceMap(int keyType, int valueType, int capacity, float loadFactor) { - super(); - - verify("keyType", keyType); - verify("valueType", valueType); - - if (capacity <= 0) { - throw new IllegalArgumentException("capacity must be positive"); - } - if ((loadFactor <= 0.0f) || (loadFactor >= 1.0f)) { - throw new IllegalArgumentException("Load factor must be greater than 0 and less than 1."); - } - - this.keyType = keyType; - this.valueType = valueType; - - int v = 1; - while (v < capacity) v *= 2; - - this.table = new Entry[v]; - this.loadFactor = loadFactor; - this.threshold = (int)(v * loadFactor); - } - - - // used by constructor - private static void verify(String name, int type) { - if ((type < HARD) || (type > WEAK)) { - throw new IllegalArgumentException(name + - " must be HARD, SOFT, WEAK."); - } - } - - - /** - * Writes this object to the given output stream. - * - * @param out the output stream to write to - * @throws IOException if the stream raises it - */ - private void writeObject(ObjectOutputStream out) throws IOException { - out.defaultWriteObject(); - out.writeInt(table.length); - - // Have to use null-terminated list because size might shrink - // during iteration - - for (Iterator iter = entrySet().iterator(); iter.hasNext();) { - Map.Entry entry = (Map.Entry)iter.next(); - out.writeObject(entry.getKey()); - out.writeObject(entry.getValue()); - } - out.writeObject(null); - } - - - /** - * Reads the contents of this object from the given input stream. - * - * @param inp the input stream to read from - * @throws IOException if the stream raises it - * @throws ClassNotFoundException if the stream raises it - */ - private void readObject(ObjectInputStream inp) throws IOException, ClassNotFoundException { - inp.defaultReadObject(); - table = new Entry[inp.readInt()]; - threshold = (int)(table.length * loadFactor); - queue = new ReferenceQueue(); - Object key = inp.readObject(); - while (key != null) { - Object value = inp.readObject(); - put(key, value); - key = inp.readObject(); - } - } - - - /** - * Constructs a reference of the given type to the given - * referent. The reference is registered with the queue - * for later purging. - * - * @param type HARD, SOFT or WEAK - * @param referent the object to refer to - * @param hash the hash code of the <I>key</I> of the mapping; - * this number might be different from referent.hashCode() if - * the referent represents a value and not a key - */ - private Object toReference(int type, Object referent, int hash) { - switch (type) { - case HARD: return referent; - case SOFT: return new SoftRef(hash, referent, queue); - case WEAK: return new WeakRef(hash, referent, queue); - default: throw new Error(); - } - } - - - /** - * Returns the entry associated with the given key. - * - * @param key the key of the entry to look up - * @return the entry associated with that key, or null - * if the key is not in this map - */ - private Entry getEntry(Object key) { - if (key == null) return null; - int hash = key.hashCode(); - int index = indexFor(hash); - for (Entry entry = table[index]; entry != null; entry = entry.next) { - if ((entry.hash == hash) && key.equals(entry.getKey())) { - return entry; - } - } - return null; - } - - - /** - * Converts the given hash code into an index into the - * hash table. - */ - private int indexFor(int hash) { - // mix the bits to avoid bucket collisions... - hash += ~(hash << 15); - hash ^= (hash >>> 10); - hash += (hash << 3); - hash ^= (hash >>> 6); - hash += ~(hash << 11); - hash ^= (hash >>> 16); - return hash & (table.length - 1); - } - - - - /** - * Resizes this hash table by doubling its capacity. - * This is an expensive operation, as entries must - * be copied from the old smaller table to the new - * bigger table. - */ - private void resize() { - Entry[] old = table; - table = new Entry[old.length * 2]; - - for (int i = 0; i < old.length; i++) { - Entry next = old[i]; - while (next != null) { - Entry entry = next; - next = next.next; - int index = indexFor(entry.hash); - entry.next = table[index]; - table[index] = entry; - } - old[i] = null; - } - threshold = (int)(table.length * loadFactor); - } - - - - /** - * Purges stale mappings from this map. - * <p> - * Ordinarily, stale mappings are only removed during - * a write operation, although this method is called for both - * read and write operations to maintain a consistent state. - * <p> - * Note that this method is not synchronized! Special - * care must be taken if, for instance, you want stale - * mappings to be removed on a periodic basis by some - * background thread. - */ - private void purge() { - Reference ref = queue.poll(); - while (ref != null) { - purge(ref); - ref = queue.poll(); - } - } - - - private void purge(Reference ref) { - // The hashCode of the reference is the hashCode of the - // mapping key, even if the reference refers to the - // mapping value... - int hash = ref.hashCode(); - int index = indexFor(hash); - Entry previous = null; - Entry entry = table[index]; - while (entry != null) { - if (entry.purge(ref)) { - if (previous == null) table[index] = entry.next; - else previous.next = entry.next; - this.size--; - return; - } - previous = entry; - entry = entry.next; - } - - } - - - /** - * Returns the size of this map. - * - * @return the size of this map - */ - public int size() { - purge(); - return size; - } - - - /** - * Returns <code>true</code> if this map is empty. - * - * @return <code>true</code> if this map is empty - */ - public boolean isEmpty() { - purge(); - return size == 0; - } - - - /** - * Returns <code>true</code> if this map contains the given key. - * - * @return true if the given key is in this map - */ - public boolean containsKey(Object key) { - purge(); - Entry entry = getEntry(key); - if (entry == null) return false; - return entry.getValue() != null; - } - - - /** - * Returns the value associated with the given key, if any. - * - * @return the value associated with the given key, or <code>null</code> - * if the key maps to no value - */ - public Object get(Object key) { - purge(); - Entry entry = getEntry(key); - if (entry == null) return null; - return entry.getValue(); - } - - - /** - * Associates the given key with the given value.<p> - * Neither the key nor the value may be null. - * - * @param key the key of the mapping - * @param value the value of the mapping - * @return the last value associated with that key, or - * null if no value was associated with the key - * @throws NullPointerException if either the key or value - * is null - */ - public Object put(Object key, Object value) { - if (key == null) throw new NullPointerException("null keys not allowed"); - if (value == null) throw new NullPointerException("null values not allowed"); - - purge(); - if (size + 1 > threshold) resize(); - - int hash = key.hashCode(); - int index = indexFor(hash); - Entry entry = table[index]; - while (entry != null) { - if ((hash == entry.hash) && key.equals(entry.getKey())) { - Object result = entry.getValue(); - entry.setValue(value); - return result; - } - entry = entry.next; - } - this.size++; - modCount++; - key = toReference(keyType, key, hash); - value = toReference(valueType, value, hash); - table[index] = new Entry(key, hash, value, table[index]); - return null; - } - - - /** - * Removes the key and its associated value from this map. - * - * @param key the key to remove - * @return the value associated with that key, or null if - * the key was not in the map - */ - public Object remove(Object key) { - if (key == null) return null; - purge(); - int hash = key.hashCode(); - int index = indexFor(hash); - Entry previous = null; - Entry entry = table[index]; - while (entry != null) { - if ((hash == entry.hash) && key.equals(entry.getKey())) { - if (previous == null) table[index] = entry.next; - else previous.next = entry.next; - this.size--; - modCount++; - return entry.getValue(); - } - previous = entry; - entry = entry.next; - } - return null; - } - - - /** - * Clears this map. - */ - public void clear() { - Arrays.fill(table, null); - size = 0; - while (queue.poll() != null); // drain the queue - } - - - /** - * Returns a set view of this map's entries. - * - * @return a set view of this map's entries - */ - public Set entrySet() { - if (entrySet != null) { - return entrySet; - } - entrySet = new AbstractSet() { - public int size() { - return ReferenceMap.this.size(); - } - - public void clear() { - ReferenceMap.this.clear(); - } - - public boolean contains(Object o) { - if (o == null) return false; - if (!(o instanceof Map.Entry)) return false; - Map.Entry e = (Map.Entry)o; - Entry e2 = getEntry(e.getKey()); - return (e2 != null) && e.equals(e2); - } - - public boolean remove(Object o) { - boolean r = contains(o); - if (r) { - Map.Entry e = (Map.Entry)o; - ReferenceMap.this.remove(e.getKey()); - } - return r; - } - - public Iterator iterator() { - return new EntryIterator(); - } - - public Object[] toArray() { - return toArray(new Object[0]); - } - - public Object[] toArray(Object[] arr) { - ArrayList list = new ArrayList(); - Iterator iterator = iterator(); - while (iterator.hasNext()) { - Entry e = (Entry)iterator.next(); - list.add(new DefaultMapEntry(e.getKey(), e.getValue())); - } - return list.toArray(arr); - } - }; - return entrySet; - } - - - /** - * Returns a set view of this map's keys. - * - * @return a set view of this map's keys - */ - public Set keySet() { - if (keySet != null) return keySet; - keySet = new AbstractSet() { - public int size() { - return ReferenceMap.this.size(); - } - - public Iterator iterator() { - return new KeyIterator(); - } - - public boolean contains(Object o) { - return containsKey(o); - } - - - public boolean remove(Object o) { - Object r = ReferenceMap.this.remove(o); - return r != null; - } - - public void clear() { - ReferenceMap.this.clear(); - } - - public Object[] toArray() { - return toArray(new Object[0]); - } - - public Object[] toArray(Object[] array) { - Collection c = new ArrayList(size()); - for (Iterator it = iterator(); it.hasNext(); ) { - c.add(it.next()); - } - return c.toArray(array); - } - }; - return keySet; - } - - - /** - * Returns a collection view of this map's values. - * - * @return a collection view of this map's values. - */ - public Collection values() { - if (values != null) return values; - values = new AbstractCollection() { - public int size() { - return ReferenceMap.this.size(); - } - - public void clear() { - ReferenceMap.this.clear(); - } - - public Iterator iterator() { - return new ValueIterator(); - } - - public Object[] toArray() { - return toArray(new Object[0]); - } - - public Object[] toArray(Object[] array) { - Collection c = new ArrayList(size()); - for (Iterator it = iterator(); it.hasNext(); ) { - c.add(it.next()); - } - return c.toArray(array); - } - }; - return values; - } - - - // If getKey() or getValue() returns null, it means - // the mapping is stale and should be removed. - private class Entry implements Map.Entry, KeyValue { - - Object key; - Object value; - int hash; - Entry next; - - - public Entry(Object key, int hash, Object value, Entry next) { - this.key = key; - this.hash = hash; - this.value = value; - this.next = next; - } - - - public Object getKey() { - return (keyType > HARD) ? ((Reference)key).get() : key; - } - - - public Object getValue() { - return (valueType > HARD) ? ((Reference)value).get() : value; - } - - - public Object setValue(Object object) { - Object old = getValue(); - if (valueType > HARD) ((Reference)value).clear(); - value = toReference(valueType, object, hash); - return old; - } - - - public boolean equals(Object o) { - if (o == null) return false; - if (o == this) return true; - if (!(o instanceof Map.Entry)) return false; - - Map.Entry entry = (Map.Entry)o; - Object key = entry.getKey(); - Object value = entry.getValue(); - if ((key == null) || (value == null)) return false; - return key.equals(getKey()) && value.equals(getValue()); - } - - - public int hashCode() { - Object v = getValue(); - return hash ^ ((v == null) ? 0 : v.hashCode()); - } - - - public String toString() { - return getKey() + "=" + getValue(); - } - - - boolean purge(Reference ref) { - boolean r = (keyType > HARD) && (key == ref); - r = r || ((valueType > HARD) && (value == ref)); - if (r) { - if (keyType > HARD) ((Reference)key).clear(); - if (valueType > HARD) { - ((Reference)value).clear(); - } else if (purgeValues) { - value = null; - } - } - return r; - } - } - - - private class EntryIterator implements Iterator { - // These fields keep track of where we are in the table. - int index; - Entry entry; - Entry previous; - - // These Object fields provide hard references to the - // current and next entry; this assures that if hasNext() - // returns true, next() will actually return a valid element. - Object nextKey, nextValue; - Object currentKey, currentValue; - - int expectedModCount; - - - public EntryIterator() { - index = (size() != 0 ? table.length : 0); - // have to do this here! size() invocation above - // may have altered the modCount. - expectedModCount = modCount; - } - - - public boolean hasNext() { - checkMod(); - while (nextNull()) { - Entry e = entry; - int i = index; - while ((e == null) && (i > 0)) { - i--; - e = table[i]; - } - entry = e; - index = i; - if (e == null) { - currentKey = null; - currentValue = null; - return false; - } - nextKey = e.getKey(); - nextValue = e.getValue(); - if (nextNull()) entry = entry.next; - } - return true; - } - - - private void checkMod() { - if (modCount != expectedModCount) { - throw new ConcurrentModificationException(); - } - } - - - private boolean nextNull() { - return (nextKey == null) || (nextValue == null); - } - - protected Entry nextEntry() { - checkMod(); - if (nextNull() && !hasNext()) throw new NoSuchElementException(); - previous = entry; - entry = entry.next; - currentKey = nextKey; - currentValue = nextValue; - nextKey = null; - nextValue = null; - return previous; - } - - - public Object next() { - return nextEntry(); - } - - - public void remove() { - checkMod(); - if (previous == null) throw new IllegalStateException(); - ReferenceMap.this.remove(currentKey); - previous = null; - currentKey = null; - currentValue = null; - expectedModCount = modCount; - } - - } - - - private class ValueIterator extends EntryIterator { - public Object next() { - return nextEntry().getValue(); - } - } - - - private class KeyIterator extends EntryIterator { - public Object next() { - return nextEntry().getKey(); - } - } - - - - // These two classes store the hashCode of the key of - // of the mapping, so that after they're dequeued a quick - // lookup of the bucket in the table can occur. - - - private static class SoftRef extends SoftReference { - private int hash; - - - public SoftRef(int hash, Object r, ReferenceQueue q) { - super(r, q); - this.hash = hash; - } - - - public int hashCode() { - return hash; - } - } - - - private static class WeakRef extends WeakReference { - private int hash; - - - public WeakRef(int hash, Object r, ReferenceQueue q) { - super(r, q); - this.hash = hash; - } - - - public int hashCode() { - return hash; - } - } - - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java b/qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java deleted file mode 100644 index a7ca67ad15..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2003-2006 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.collections.keyvalue; - -import org.apache.qpid.collections.KeyValue; - - -/** - * Abstract pair class to assist with creating <code>KeyValue</code> - * and {@link java.util.Map.Entry Map.Entry} implementations. - * - * @since Commons Collections 3.0 - * @version $Revision$ $Date$ - * - * @author James Strachan - * @author Michael A. Smith - * @author Neil O'Toole - * @author Stephen Colebourne - */ -public abstract class AbstractKeyValue implements KeyValue { - - /** The key */ - protected Object key; - /** The value */ - protected Object value; - - /** - * Constructs a new pair with the specified key and given value. - * - * @param key the key for the entry, may be null - * @param value the value for the entry, may be null - */ - protected AbstractKeyValue(Object key, Object value) { - super(); - this.key = key; - this.value = value; - } - - /** - * Gets the key from the pair. - * - * @return the key - */ - public Object getKey() { - return key; - } - - /** - * Gets the value from the pair. - * - * @return the value - */ - public Object getValue() { - return value; - } - - /** - * Gets a debugging String view of the pair. - * - * @return a String view of the entry - */ - public String toString() { - return new StringBuffer() - .append(getKey()) - .append('=') - .append(getValue()) - .toString(); - } - -} diff --git a/qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java b/qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java deleted file mode 100644 index f4717a1c20..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2003-2006 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.collections.keyvalue; - -import java.util.Map; - -import org.apache.qpid.collections.keyvalue.AbstractKeyValue; - -/** - * Abstract Pair class to assist with creating correct - * {@link java.util.Map.Entry Map.Entry} implementations. - * - * @since Commons Collections 3.0 - * @version $Revision$ $Date$ - * - * @author James Strachan - * @author Michael A. Smith - * @author Neil O'Toole - * @author Stephen Colebourne - */ -public abstract class AbstractMapEntry extends AbstractKeyValue implements Map.Entry { - - /** - * Constructs a new entry with the given key and given value. - * - * @param key the key for the entry, may be null - * @param value the value for the entry, may be null - */ - protected AbstractMapEntry(Object key, Object value) { - super(key, value); - } - - // Map.Entry interface - //------------------------------------------------------------------------- - /** - * Sets the value stored in this <code>Map.Entry</code>. - * <p> - * This <code>Map.Entry</code> is not connected to a Map, so only the - * local data is changed. - * - * @param value the new value - * @return the previous value - */ - public Object setValue(Object value) { - Object answer = this.value; - this.value = value; - return answer; - } - - /** - * Compares this <code>Map.Entry</code> with another <code>Map.Entry</code>. - * <p> - * Implemented per API documentation of {@link java.util.Map.Entry#equals(Object)} - * - * @param obj the object to compare to - * @return true if equal key and value - */ - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj instanceof Map.Entry == false) { - return false; - } - Map.Entry other = (Map.Entry) obj; - return - (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && - (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue())); - } - - /** - * Gets a hashCode compatible with the equals method. - * <p> - * Implemented per API documentation of {@link java.util.Map.Entry#hashCode()} - * - * @return a suitable hash code - */ - public int hashCode() { - return (getKey() == null ? 0 : getKey().hashCode()) ^ - (getValue() == null ? 0 : getValue().hashCode()); - } - -}
\ No newline at end of file diff --git a/qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java b/qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java deleted file mode 100644 index f0f04a366a..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2001-2006 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.qpid.collections.keyvalue; - -import java.util.Map; - -import org.apache.qpid.collections.KeyValue; -import org.apache.qpid.collections.keyvalue.AbstractMapEntry; - -/** - * A restricted implementation of {@link java.util.Map.Entry} that prevents - * the <code>Map.Entry</code> contract from being broken. - * - * @since Commons Collections 3.0 - * @version $Revision$ $Date$ - * - * @author James Strachan - * @author Michael A. Smith - * @author Neil O'Toole - * @author Stephen Colebourne - */ -public final class DefaultMapEntry extends AbstractMapEntry { - - /** - * Constructs a new entry with the specified key and given value. - * - * @param key the key for the entry, may be null - * @param value the value for the entry, may be null - */ - public DefaultMapEntry(final Object key, final Object value) { - super(key, value); - } - - /** - * Constructs a new entry from the specified <code>KeyValue</code>. - * - * @param pair the pair to copy, must not be null - * @throws NullPointerException if the entry is null - */ - public DefaultMapEntry(final KeyValue pair) { - super(pair.getKey(), pair.getValue()); - } - - /** - * Constructs a new entry from the specified <code>Map.Entry</code>. - * - * @param entry the entry to copy, must not be null - * @throws NullPointerException if the entry is null - */ - public DefaultMapEntry(final Map.Entry entry) { - super(entry.getKey(), entry.getValue()); - } - -}
\ No newline at end of file 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 index 0c2f4ce57d..71d7ffd2a3 100644 --- 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 @@ -20,10 +20,10 @@ */ package org.apache.qpid.jms; -import java.util.Map; - import org.apache.qpid.transport.ConnectionSettings; +import java.util.Map; + public interface BrokerDetails { 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 index 24d9360cfa..8fd6ff6d33 100644 --- 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 @@ -21,7 +21,6 @@ package org.apache.qpid.jms; import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.ProtocolVersion; import java.util.List; 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 index 56abf03c81..f4d2ecc36d 100644 --- 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 @@ -20,15 +20,15 @@ */ 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; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class FailoverPolicy { private static final Logger _logger = LoggerFactory.getLogger(FailoverPolicy.class); @@ -74,12 +74,6 @@ public class FailoverPolicy { String failoverMethod = connectionDetails.getFailoverMethod(); - /* - if (failoverMethod.equals(FailoverMethod.RANDOM)) - { - //todo write a random connection Failover - } - */ if (failoverMethod.equals(FailoverMethod.SINGLE_BROKER)) { method = new FailoverSingleServer(connectionDetails); 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 index 4ad917fa83..bec8b0917d 100644 --- 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 @@ -20,11 +20,10 @@ */ package org.apache.qpid.jms; -import java.io.UnsupportedEncodingException; - import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; +import java.io.UnsupportedEncodingException; /** */ 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 index 5287381fae..b4bf2d1d85 100644 --- 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 @@ -26,9 +26,11 @@ 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 javax.jms.Session +public interface Session extends TopicSession, QueueSession { /** * Indicates that no client acknowledgements are required. Broker assumes that once it has delivered 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 index cb3ab718e9..a5eda29274 100644 --- 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 @@ -20,15 +20,8 @@ */ package org.apache.qpid.jms.failover; -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; - -import javax.jms.JMSException; -import javax.jms.Message; -import javax.jms.MessageConsumer; -import javax.jms.MessageListener; -import javax.jms.Session; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.apache.qpid.client.AMQAnyDestination; import org.apache.qpid.client.AMQBrokerDetails; @@ -36,8 +29,15 @@ 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 org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +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. @@ -127,9 +127,7 @@ public class FailoverExchangeMethod implements FailoverMethod, MessageListener for (String brokerEntry:list) { String[] urls = brokerEntry.substring(5) .split(","); - // Iterate until you find the correct transport - // Need to reconsider the logic when the C++ broker supports - // SSL URLs. + for (String url:urls) { String[] tokens = url.split(":"); 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 index 41ba4974ec..84c1794723 100644 --- 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 @@ -20,11 +20,12 @@ */ package org.apache.qpid.jms.failover; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ConnectionURL; 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); @@ -49,8 +50,7 @@ public class FailoverRoundRobinServers implements FailoverMethod /** The current number of cycles performed. */ private int _currentCycleRetries = 0; - /** Array of BrokerDetail used to make connections. */ - protected ConnectionURL _connectionDetails; + private ConnectionURL _connectionDetails; public FailoverRoundRobinServers(ConnectionURL connectionDetails) { 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 index d033a49f5c..1ef71eccba 100644 --- 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 @@ -20,11 +20,12 @@ */ package org.apache.qpid.jms.failover; -import org.apache.qpid.jms.BrokerDetails; -import org.apache.qpid.jms.ConnectionURL; 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); @@ -36,10 +37,10 @@ public class FailoverSingleServer implements FailoverMethod private BrokerDetails _brokerDetail; /** The number of times to retry connecting to the sever */ - protected int _retries; + private int _retries; /** The current number of attempts made to the server */ - protected int _currentRetries = 0; + private int _currentRetries = 0; public FailoverSingleServer(ConnectionURL connectionDetails) @@ -64,6 +65,11 @@ public class FailoverSingleServer implements FailoverMethod _currentRetries = 0; } + protected void setCurrentRetries(int currentRetries) + { + _currentRetries = currentRetries; + } + public boolean failoverAllowed() { return _currentRetries < _retries; @@ -150,6 +156,11 @@ public class FailoverSingleServer implements FailoverMethod _retries = retries; } + public int getRetries() + { + return _retries; + } + public String methodName() { return "Single Server"; 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 index 1231324397..82cb0f9153 100644 --- 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 @@ -44,7 +44,7 @@ public class NoFailover extends FailoverSingleServer public void attainedConnection() { _connected=true; - _currentRetries = _retries; + setCurrentRetries(getRetries()); } @Override 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 index b480f56c07..bc3f89849e 100644 --- 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 @@ -20,24 +20,8 @@ */ package org.apache.qpid.jndi; -import java.io.BufferedInputStream; -import java.io.FileInputStream; -import java.io.IOException; -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.Context; -import javax.naming.NamingException; -import javax.naming.ConfigurationException; -import javax.naming.spi.InitialContextFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.apache.qpid.client.AMQConnectionFactory; import org.apache.qpid.client.AMQDestination; @@ -46,16 +30,30 @@ 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.AMQBindingURL; 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; + +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 java.io.BufferedInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Hashtable; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; public class PropertiesFileInitialContextFactory implements InitialContextFactory { - protected final Logger _logger = LoggerFactory.getLogger(PropertiesFileInitialContextFactory.class); + private final Logger _logger = LoggerFactory.getLogger(PropertiesFileInitialContextFactory.class); private String CONNECTION_FACTORY_PREFIX = "connectionfactory."; private String DESTINATION_PREFIX = "destination."; 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 index 1719ea1219..76ec5f9498 100644 --- 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 @@ -20,13 +20,6 @@ */ package org.apache.qpid.jndi; -import java.io.Serializable; -import java.util.Collections; -import java.util.HashMap; -import java.util.Hashtable; -import java.util.Iterator; -import java.util.Map; - import javax.naming.Binding; import javax.naming.CompositeName; import javax.naming.Context; @@ -41,6 +34,12 @@ 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. @@ -66,9 +65,9 @@ public class ReadOnlyContext implements Context, Serializable private static final long serialVersionUID = -5754338187296859149L; protected static final NameParser nameParser = new NameParserImpl(); - protected final Hashtable environment; // environment for this context - protected final Map bindings; // bindings at my level - protected final Map treeBindings; // all bindings under me + 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 = ""; diff --git a/qpid/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java b/qpid/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java deleted file mode 100644 index 59ec4cfba7..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java +++ /dev/null @@ -1,509 +0,0 @@ -/* Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.qpid.naming; - -import org.apache.qpid.jndi.NameParserImpl; - -import javax.naming.*; -import javax.naming.spi.NamingManager; -import java.io.Serializable; -import java.util.*; - -/** - * 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> - * <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(); - - protected final Hashtable environment; // environment for this context - protected final Map bindings; // bindings at my level - protected 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). - * - * @param name - * @param value - * @return - * @throws javax.naming.NamingException - */ - 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 ReadOnlyContext.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 ReadOnlyContext.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 ReadOnlyContext.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 ReadOnlyContext.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/naming/jndi.properties b/qpid/java/client/src/main/java/org/apache/qpid/naming/jndi.properties deleted file mode 100644 index 830de5f619..0000000000 --- a/qpid/java/client/src/main/java/org/apache/qpid/naming/jndi.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.naming.PropertiesFileInitialConextFactory - -# use the following property to configure the default connector -#java.naming.provider.url - ignored. - -# register some connection factories -# connectionfactory.[jndiname] = [ConnectionURL] -# qpid:username=foo;password=password;client_id=id;virtualhost=path@tpc:localhost:1556 -connectionfactory.local = qpid:tcp:localhost' - -# 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 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 index 6f07dcb469..b90f4308cd 100644 --- 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 @@ -17,9 +17,6 @@ */ package org.apache.qpid.nclient; -import java.nio.ByteBuffer; - -import org.apache.qpid.transport.Header; import org.apache.qpid.transport.MessageTransfer; /** 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 index 14bfb4f95e..7134f0a960 100644 --- 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 @@ -21,14 +21,17 @@ package org.apache.qpid.nclient.util; */ -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.*; - +import org.apache.qpid.api.Message; import org.apache.qpid.transport.DeliveryProperties; -import org.apache.qpid.transport.MessageProperties; import org.apache.qpid.transport.Header; -import org.apache.qpid.api.Message; +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 @@ -42,7 +45,7 @@ import org.apache.qpid.api.Message; */ public class ByteBufferMessage implements Message { - private List<ByteBuffer> _data;// = new ArrayList<ByteBuffer>(); + private List<ByteBuffer> _data; private ByteBuffer _readBuffer; private int _dataSize; private DeliveryProperties _currentDeliveryProps; 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 index 2f1eda6ef2..9a2e9de3d9 100644 --- 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 @@ -21,12 +21,13 @@ 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; -import org.apache.qpid.transport.*; -import org.apache.qpid.nclient.MessagePartListener; - /** * This is a simple message assembler. * Will call onMessage method of the adaptee @@ -37,8 +38,8 @@ import org.apache.qpid.nclient.MessagePartListener; */ public class MessagePartListenerAdapter implements MessagePartListener { - MessageListener _adaptee; - ByteBufferMessage _currentMsg; + private MessageListener _adaptee; + private ByteBufferMessage _currentMsg; public MessagePartListenerAdapter(MessageListener listener) { 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 index 3a565f0f0d..d186a440da 100644 --- 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 @@ -20,15 +20,14 @@ */ package org.apache.qpid.client; -import java.util.concurrent.atomic.AtomicReference; - -import javax.jms.ExceptionListener; -import javax.jms.JMSException; - import junit.framework.TestCase; import org.apache.qpid.AMQInvalidArgumentException; +import javax.jms.ExceptionListener; +import javax.jms.JMSException; +import java.util.concurrent.atomic.AtomicReference; + public class AMQConnectionUnitTest extends TestCase { 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 index 7789f87ace..bc48ee8895 100644 --- 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 @@ -20,17 +20,17 @@ */ package org.apache.qpid.client; -import org.apache.qpid.framing.AMQShortString; - import junit.framework.TestCase; +import org.apache.qpid.framing.AMQShortString; + public class AMQQueueTest extends TestCase { - AMQShortString exchange = new AMQShortString("test.exchange"); - AMQShortString routingkey = new AMQShortString("test-route"); - AMQShortString qname = new AMQShortString("test-queue"); - AMQShortString[] oneBinding = new AMQShortString[]{new AMQShortString("bindingA")}; - AMQShortString[] bindings = new AMQShortString[]{new AMQShortString("bindingB"), + 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() 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 index 1889577773..028e2d5cc3 100644 --- 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 @@ -18,53 +18,18 @@ */ package org.apache.qpid.client; -import java.util.ArrayList; -import java.util.List; +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; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageListener; import javax.jms.MessageProducer; - -import junit.framework.TestCase; - -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.transport.Binary; -import org.apache.qpid.transport.Connection; -import org.apache.qpid.transport.Connection.SessionFactory; -import org.apache.qpid.transport.Connection.State; -import org.apache.qpid.transport.ExchangeBound; -import org.apache.qpid.transport.ExchangeBoundResult; -import org.apache.qpid.transport.ExchangeDeclare; -import org.apache.qpid.transport.ExchangeDelete; -import org.apache.qpid.transport.ExchangeQuery; -import org.apache.qpid.transport.ExchangeQueryResult; -import org.apache.qpid.transport.ExecutionErrorCode; -import org.apache.qpid.transport.ExecutionException; -import org.apache.qpid.transport.ExecutionResult; -import org.apache.qpid.transport.ExecutionSync; -import org.apache.qpid.transport.Future; -import org.apache.qpid.transport.MessageCancel; -import org.apache.qpid.transport.MessageFlow; -import org.apache.qpid.transport.MessageRelease; -import org.apache.qpid.transport.MessageSubscribe; -import org.apache.qpid.transport.MessageTransfer; -import org.apache.qpid.transport.Method; -import org.apache.qpid.transport.Option; -import org.apache.qpid.transport.ProtocolEvent; -import org.apache.qpid.transport.QueueDelete; -import org.apache.qpid.transport.QueueQuery; -import org.apache.qpid.transport.QueueQueryResult; -import org.apache.qpid.transport.Sender; -import org.apache.qpid.transport.Session; -import org.apache.qpid.transport.SessionAttach; -import org.apache.qpid.transport.SessionDelegate; -import org.apache.qpid.transport.SessionDetach; -import org.apache.qpid.transport.SessionException; -import org.apache.qpid.transport.SessionRequestTimeout; -import org.apache.qpid.transport.TxCommit; -import org.apache.qpid.transport.TxRollback; -import org.apache.qpid.transport.TxSelect; +import java.util.ArrayList; +import java.util.List; /** * Tests AMQSession_0_10 methods. @@ -73,7 +38,7 @@ import org.apache.qpid.transport.TxSelect; * {@link SessionException} is not thrown from methods of * {@link AMQSession_0_10}. */ -public class AMQSession_0_10Test extends TestCase +public class AMQSession_0_10Test extends QpidTestCase { public void testExceptionOnCommit() @@ -311,7 +276,7 @@ public class AMQSession_0_10Test extends TestCase { BasicMessageConsumer_0_10 consumer = session.createMessageConsumer(createDestination(), 1, 1, true, false, null, null, false, true); - session.sendConsume(consumer, new AMQShortString("test"), null, true, null, 1); + session.sendConsume(consumer, new AMQShortString("test"), null, true, 1); } catch (Exception e) { @@ -494,6 +459,28 @@ public class AMQSession_0_10Test extends TestCase assertNotNull("ExchangeDeclare event was not sent", event); } + 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 cought:" + 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; 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 index 02089cc382..722cbd0752 100644 --- 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 @@ -20,12 +20,12 @@ */ package org.apache.qpid.client; -import javax.jms.Session; +import junit.framework.TestCase; import org.apache.qpid.test.unit.message.TestAMQSession; import org.apache.qpid.url.AMQBindingURL; -import junit.framework.TestCase; +import javax.jms.Session; public class BasicMessageConsumer_0_8_Test extends TestCase { 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 new file mode 100644 index 0000000000..b9c4bfc676 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/DispatcherDaemonTest.java @@ -0,0 +1,67 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF 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 index 919809edc3..009598d8a4 100644 --- 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 @@ -51,13 +51,13 @@ public class MockAMQConnection extends AMQConnection @Override public ProtocolVersion makeBrokerConnection(BrokerDetails brokerDetail) throws IOException { - _connected = true; - _protocolHandler.getStateManager().changeState(AMQState.CONNECTION_OPEN); + setConnected(true); + getProtocolHandler().getStateManager().changeState(AMQState.CONNECTION_OPEN); return null; } public AMQConnectionDelegate getDelegate() { - return _delegate; + return super.getDelegate(); } } 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 new file mode 100644 index 0000000000..8c66a75764 --- /dev/null +++ b/qpid/java/client/src/test/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10Test.java @@ -0,0 +1,108 @@ +/* + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.client.message; + +import javax.jms.Destination; + +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; + +import java.util.HashMap; +import java.util.Map; + +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)); + } + +} 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 index f81f482c6a..1fbd7cf212 100644 --- 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 @@ -21,10 +21,10 @@ package org.apache.qpid.client.message; */ -import javax.jms.JMSException; - import junit.framework.TestCase; +import javax.jms.JMSException; + public class AbstractJMSMessageTest extends TestCase { 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 index e159ceb148..9a5ca33174 100644 --- 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 @@ -20,10 +20,9 @@ */ 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; @@ -35,8 +34,9 @@ import org.apache.qpid.framing.AMQMethodBody; import org.apache.qpid.framing.amqp_8_0.BasicRecoverOkBodyImpl; import org.apache.qpid.protocol.AMQConstant; import org.apache.qpid.transport.TestNetworkConnection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; /** * This is a test address QPID-1431 where frame listeners would fail to be notified of an incomming exception. @@ -59,15 +59,15 @@ public class AMQProtocolHandlerTest extends TestCase private static final Logger _logger = LoggerFactory.getLogger(AMQProtocolHandlerTest.class); // The handler to test - AMQProtocolHandler _handler; + private AMQProtocolHandler _handler; // A frame to block upon whilst waiting the exception - AMQFrame _blockFrame; + private AMQFrame _blockFrame; // Latch to know when the listener receives an exception private CountDownLatch _handleCountDown; // The listener that will receive an exception - BlockToAccessFrameListener _listener; + private BlockToAccessFrameListener _listener; @Override public void setUp() throws Exception 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 index cc5d48fbef..b451ad630f 100644 --- 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 @@ -20,15 +20,14 @@ */ package org.apache.qpid.client.security; -import java.io.IOException; -import java.util.Properties; +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 org.apache.qpid.jms.ConnectionURL; -import org.apache.qpid.test.utils.QpidTestCase; +import java.io.IOException; +import java.util.Properties; /** 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 index 9e23f722eb..290ef7420a 100644 --- 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 @@ -20,20 +20,15 @@ */ package org.apache.qpid.client.security; -import java.security.MessageDigest; -import java.util.Arrays; +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 junit.framework.TestCase; - -import org.apache.qpid.client.AMQConnection; -import org.apache.qpid.client.AMQConnectionURL; -import org.apache.qpid.client.MockAMQConnection; -import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.client.protocol.AMQProtocolSession; +import java.security.MessageDigest; +import java.util.Arrays; /** * Unit tests for the UsernameHashPasswordCallbackHandler. This callback handler is 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 index 83ddfd72fa..70f279d53c 100644 --- 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 @@ -20,17 +20,13 @@ */ package org.apache.qpid.client.security; -import javax.security.auth.callback.Callback; -import javax.security.auth.callback.NameCallback; -import javax.security.auth.callback.PasswordCallback; - import junit.framework.TestCase; -import org.apache.qpid.client.AMQConnection; import org.apache.qpid.client.AMQConnectionURL; -import org.apache.qpid.client.MockAMQConnection; -import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.client.protocol.AMQProtocolSession; + +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; /** * Unit tests for the UsernamePasswordCallbackHandler. 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 index a12e4ce977..91460ab4e7 100644 --- 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 @@ -20,6 +20,8 @@ */ 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; @@ -27,12 +29,10 @@ import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.List; -import org.apache.qpid.test.utils.QpidTestCase; - public class ClassLoadingAwareObjectInputStreamTest extends QpidTestCase { - InputStream _in; - ClassLoadingAwareObjectInputStream _claOIS; + private InputStream _in; + private ClassLoadingAwareObjectInputStream _claOIS; protected void setUp() throws Exception { 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 index 438995aedc..cb9623237c 100644 --- 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 @@ -20,13 +20,7 @@ */ package org.apache.qpid.jms; -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; +import junit.framework.TestCase; import org.apache.qpid.client.AMQConnectionURL; import org.apache.qpid.jms.failover.FailoverExchangeMethod; @@ -35,7 +29,13 @@ import org.apache.qpid.jms.failover.FailoverRoundRobinServers; import org.apache.qpid.jms.failover.FailoverSingleServer; import org.apache.qpid.jms.failover.NoFailover; -import junit.framework.TestCase; +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. 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 index ddbc69826d..b408ad8ad1 100644 --- 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 @@ -20,12 +20,6 @@ */ package org.apache.qpid.test.unit.basic; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import javax.jms.JMSException; - import junit.framework.TestCase; import org.apache.qpid.client.message.JMSTextMessage; @@ -33,6 +27,11 @@ 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() 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 index 60ed688897..e27c684adc 100644 --- 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 @@ -20,15 +20,14 @@ */ package org.apache.qpid.test.unit.basic; -import java.util.Enumeration; - -import javax.jms.JMSException; - 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() 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 index d560c413e6..0bdd3062ea 100644 --- 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 @@ -20,6 +20,9 @@ */ 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; @@ -32,9 +35,6 @@ import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.ChannelCloseBody; import org.apache.qpid.protocol.AMQConstant; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class ChannelCloseMethodHandlerNoCloseOk implements StateAwareMethodListener<ChannelCloseBody> { private static final Logger _logger = LoggerFactory.getLogger(ChannelCloseMethodHandlerNoCloseOk.class); 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 index c7eb745566..3498045601 100644 --- 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 @@ -20,37 +20,8 @@ */ package org.apache.qpid.test.unit.client.channelclose; -import org.apache.qpid.client.state.AMQStateManager; -import org.apache.qpid.client.state.AMQState; -import org.apache.qpid.client.handler.ConnectionStartMethodHandler; -import org.apache.qpid.client.handler.ConnectionCloseMethodHandler; -import org.apache.qpid.client.handler.ConnectionTuneMethodHandler; -import org.apache.qpid.client.handler.ConnectionSecureMethodHandler; -import org.apache.qpid.client.handler.ConnectionOpenOkMethodHandler; -import org.apache.qpid.client.handler.ChannelCloseOkMethodHandler; -import org.apache.qpid.client.handler.BasicDeliverMethodHandler; -import org.apache.qpid.client.handler.BasicReturnMethodHandler; -import org.apache.qpid.client.handler.BasicCancelOkMethodHandler; -import org.apache.qpid.client.handler.ChannelFlowOkMethodHandler; -import org.apache.qpid.client.handler.QueueDeleteOkMethodHandler; -import org.apache.qpid.client.handler.ExchangeBoundOkMethodHandler; import org.apache.qpid.client.protocol.AMQProtocolSession; -import org.apache.qpid.framing.ConnectionStartBody; -import org.apache.qpid.framing.ConnectionCloseBody; -import org.apache.qpid.framing.ConnectionTuneBody; -import org.apache.qpid.framing.ConnectionSecureBody; -import org.apache.qpid.framing.ConnectionOpenOkBody; -import org.apache.qpid.framing.ChannelCloseBody; -import org.apache.qpid.framing.ChannelCloseOkBody; -import org.apache.qpid.framing.BasicDeliverBody; -import org.apache.qpid.framing.BasicReturnBody; -import org.apache.qpid.framing.BasicCancelOkBody; -import org.apache.qpid.framing.ChannelFlowOkBody; -import org.apache.qpid.framing.QueueDeleteOkBody; -import org.apache.qpid.framing.ExchangeBoundOkBody; - -import java.util.Map; -import java.util.HashMap; +import org.apache.qpid.client.state.AMQStateManager; public class NoCloseOKStateManager extends AMQStateManager { 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 index 2c32e4c559..9addb0ee71 100644 --- 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 @@ -21,14 +21,14 @@ 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.url.AMQBindingURL; import org.apache.qpid.url.BindingURL; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.net.URISyntaxException; 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 index 65013e7e6d..1ab3ad0573 100644 --- 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 @@ -20,17 +20,16 @@ */ package org.apache.qpid.test.unit.client.message; -import java.util.HashMap; +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 junit.framework.TestCase; - -import org.apache.qpid.client.message.JMSBytesMessage; -import org.apache.qpid.client.message.TestMessageHelper; +import java.util.HashMap; public class BytesMessageTest extends TestCase { 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 index 3e04c36b38..f75c660ec3 100644 --- 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 @@ -20,15 +20,15 @@ */ package org.apache.qpid.test.unit.client.message; -import javax.jms.JMSException; -import javax.jms.MessageFormatException; - import junit.framework.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 { 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 index e37970e9a2..a2c5bf624f 100644 --- 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 @@ -20,13 +20,13 @@ */ package org.apache.qpid.test.unit.client.message; -import java.util.ArrayList; -import java.util.Arrays; - 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; 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 index 085dd81079..648e4b0c83 100644 --- 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 @@ -20,7 +20,10 @@ */ package org.apache.qpid.test.unit.client.message; -import java.util.HashMap; +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; @@ -28,11 +31,7 @@ import javax.jms.MessageFormatException; import javax.jms.MessageNotReadableException; import javax.jms.MessageNotWriteableException; import javax.jms.StreamMessage; - -import junit.framework.TestCase; - -import org.apache.qpid.client.message.JMSStreamMessage; -import org.apache.qpid.client.message.TestMessageHelper; +import java.util.HashMap; /** * @author Apache Software Foundation 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 index 30f3b0b4eb..a80b3d145b 100644 --- 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 @@ -20,8 +20,6 @@ */ package org.apache.qpid.test.unit.client.message; -import javax.jms.JMSException; - import junit.framework.Assert; import junit.framework.TestCase; @@ -29,6 +27,8 @@ 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 diff --git a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java index 2052312f54..576ab4fa05 100644 --- a/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java +++ b/qpid/java/client/src/test/java/org/apache/qpid/test/unit/jndi/JNDIPropertyFileTest.java @@ -20,22 +20,21 @@ */ package org.apache.qpid.test.unit.jndi; -import java.util.Properties; +import junit.framework.TestCase; + +import org.apache.qpid.client.AMQDestination; +import org.apache.qpid.framing.AMQShortString; import javax.jms.Queue; import javax.jms.Topic; import javax.naming.ConfigurationException; import javax.naming.Context; import javax.naming.InitialContext; - -import org.apache.qpid.client.AMQDestination; -import org.apache.qpid.framing.AMQShortString; - -import junit.framework.TestCase; +import java.util.Properties; public class JNDIPropertyFileTest extends TestCase { - Context ctx; + private Context ctx; public JNDIPropertyFileTest() throws Exception { 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 index cd18b5181f..04122a6d51 100644 --- 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 @@ -20,20 +20,24 @@ */ package org.apache.qpid.test.unit.message; -import javax.jms.*; - import junit.framework.TestCase; -import org.apache.qpid.client.*; -import org.apache.qpid.client.protocol.AMQProtocolHandler; -import org.apache.qpid.client.failover.FailoverException; -import org.apache.qpid.client.message.*; +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; -import org.apache.qpid.framing.AMQShortString; -import org.apache.qpid.framing.FieldTable; -import org.apache.qpid.AMQException; -import java.util.Map; +import javax.jms.Destination; +import javax.jms.JMSException; +import javax.jms.MapMessage; +import javax.jms.Message; +import javax.jms.TextMessage; public class MessageConverterTest extends TestCase 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 index b1cf23bb9e..d93ba23a25 100644 --- 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 @@ -20,13 +20,12 @@ */ package org.apache.qpid.test.unit.message; -import java.util.Enumeration; -import java.util.Hashtable; - 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 { 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 index 4c3e9c2390..f199961b6f 100644 --- 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 @@ -20,23 +20,25 @@ */ package org.apache.qpid.test.unit.message; -import java.util.Map; - -import javax.jms.Destination; -import javax.jms.JMSException; -import javax.jms.TemporaryQueue; -import javax.jms.Topic; -import javax.jms.TopicSubscriber; - import org.apache.qpid.AMQException; -import org.apache.qpid.client.*; +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.filter.MessageFilter; 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 { @@ -122,7 +124,7 @@ public class TestAMQSession extends AMQSession_0_8 return false; } - public void sendConsume(BasicMessageConsumer_0_8 consumer, AMQShortString queueName, AMQProtocolHandler protocolHandler, boolean nowait, MessageFilter messageSelector, int tag) throws AMQException, FailoverException + public void sendConsume(BasicMessageConsumer_0_8 consumer, AMQShortString queueName, AMQProtocolHandler protocolHandler, boolean nowait, int tag) throws AMQException, FailoverException { } @@ -143,7 +145,7 @@ public class TestAMQSession extends AMQSession_0_8 } public void sendQueueDeclare(AMQDestination amqd, AMQProtocolHandler protocolHandler, - boolean nowait) throws AMQException, FailoverException + boolean nowait, boolean passive) throws AMQException, FailoverException { } |