diff options
author | Robert Godfrey <rgodfrey@apache.org> | 2012-01-29 13:05:07 +0000 |
---|---|---|
committer | Robert Godfrey <rgodfrey@apache.org> | 2012-01-29 13:05:07 +0000 |
commit | 22b64fd33e448ffc54134b28c7226342f54b4683 (patch) | |
tree | 89a27bba6ddb8674b02a810775cfb148d6de8d67 | |
parent | 9bb75aae85d397bd9dd98c8230de3e576ce97572 (diff) | |
download | qpid-python-22b64fd33e448ffc54134b28c7226342f54b4683.tar.gz |
QPID-3789 : [Java] code tidyups
git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk/qpid@1237273 13f79535-47bb-0310-9956-ffa450edef68
199 files changed, 1098 insertions, 4624 deletions
diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/AMQShortStringEncoding.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/AMQShortStringEncoding.java index 8431382d59..354dba559c 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/AMQShortStringEncoding.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/AMQShortStringEncoding.java @@ -27,6 +27,10 @@ import org.apache.qpid.framing.AMQShortString; public class AMQShortStringEncoding { + private AMQShortStringEncoding() + { + } + public static AMQShortString readShortString(TupleInput tupleInput) { int length = (int) tupleInput.readShort(); diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStore.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStore.java index 534d4b0a44..92dd592143 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStore.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStore.java @@ -151,7 +151,7 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore * messageId (long) - bodySize (integer), metaData (MessageMetaData encoded as binary) * * Message (Content): - * messageId (long), byteOffset (integer) - dataLength(integer), data(binary); + * messageId (long), byteOffset (integer) - dataLength(integer), data(binary) */ private LogSubject _logSubject; @@ -429,9 +429,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore envConfig.setTransactional(true); envConfig.setConfigParam("je.lock.nLockTables", "7"); - // Restore 500,000 default timeout. - //envConfig.setLockTimeout(15000); - // Added to help diagnosis of Deadlock issue // http://www.oracle.com/technology/products/berkeley-db/faq/je_faq.html#23 if (Boolean.getBoolean("qpid.bdb.lock.debug")) @@ -903,7 +900,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore public void removeMessage(long messageId, boolean sync) throws AMQStoreException { - // _log.debug("public void removeMessage(Long messageId = " + messageId): called"); boolean complete = false; com.sleepycat.je.Transaction tx = null; @@ -1116,9 +1112,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore */ public void bindQueue(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) throws AMQStoreException { - // _log.debug("public void bindQueue(Exchange exchange = " + exchange + ", AMQShortString routingKey = " + routingKey - // + ", AMQQueue queue = " + queue + ", FieldTable args = " + args + "): called"); - if (_state != State.RECOVERING) { BindingKey bindingRecord = new BindingKey(exchange.getNameShortString(), @@ -1408,8 +1401,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore public void enqueueMessage(final com.sleepycat.je.Transaction tx, final TransactionLogResource queue, long messageId) throws AMQStoreException { - // _log.debug("public void enqueueMessage(Transaction tx = " + tx + ", AMQShortString name = " + name + ", Long messageId): called"); - AMQShortString name = AMQShortString.valueOf(queue.getResourceName()); DatabaseEntry key = new DatabaseEntry(); @@ -1498,11 +1489,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore */ private StoreFuture commitTranImpl(final com.sleepycat.je.Transaction tx, boolean syncCommit) throws AMQStoreException { - //if (_log.isDebugEnabled()) - //{ - // _log.debug("public void commitTranImpl() called with (Transaction=" + tx + ", syncCommit= "+ syncCommit + ")"); - //} - if (tx == null) { throw new AMQStoreException("Fatal internal error: transactional is null at commitTran"); @@ -1969,8 +1955,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore private StoreFuture commit(com.sleepycat.je.Transaction tx, boolean syncCommit) throws DatabaseException { - // _log.debug("void commit(Transaction tx = " + tx + ", sync = " + syncCommit + "): called"); - tx.commitNoSync(); BDBCommitFuture commitFuture = new BDBCommitFuture(_commitThread, tx, syncCommit); @@ -1986,8 +1970,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore private static final class BDBCommitFuture implements StoreFuture { - // private static final Logger _log = Logger.getLogger(BDBCommitFuture.class); - private final CommitThread _commitThread; private final com.sleepycat.je.Transaction _tx; private DatabaseException _databaseException; @@ -1996,9 +1978,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore public BDBCommitFuture(CommitThread commitThread, com.sleepycat.je.Transaction tx, boolean syncCommit) { - // _log.debug("public Commit(CommitThread commitThread = " + commitThread + ", Transaction tx = " + tx - // + "): called"); - _commitThread = commitThread; _tx = tx; _syncCommit = syncCommit; @@ -2017,9 +1996,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore public synchronized void abort(DatabaseException databaseException) { - // _log.debug("public synchronized void abort(DatabaseException databaseException = " + databaseException - // + "): called"); - _complete = true; _databaseException = databaseException; @@ -2028,8 +2004,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore public void commit() throws DatabaseException { - //_log.debug("public void commit(): called"); - _commitThread.addJob(this, _syncCommit); if(!_syncCommit) @@ -2039,7 +2013,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore } waitForCompletion(); - // _log.debug("Commit completed, _databaseException = " + _databaseException); if (_databaseException != null) { @@ -2081,8 +2054,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore */ private class CommitThread extends Thread { - // private final Logger _log = Logger.getLogger(CommitThread.class); - private final AtomicBoolean _stopped = new AtomicBoolean(false); private final Queue<BDBCommitFuture> _jobQueue = new ConcurrentLinkedQueue<BDBCommitFuture>(); private final CheckpointConfig _config = new CheckpointConfig(); @@ -2119,7 +2090,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore } catch (InterruptedException e) { - // _log.info(getName() + " interrupted. "); } } } @@ -2129,8 +2099,6 @@ public class BDBMessageStore implements MessageStore, DurableConfigurationStore private void processJobs() { - // _log.debug("private void processJobs(): called"); - int size = _jobQueue.size(); try diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgrade.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgrade.java index 7e402e3320..f064079606 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgrade.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/BDBStoreUpgrade.java @@ -65,6 +65,7 @@ import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; +import java.util.Set; /** * This is a simple BerkeleyDB Store upgrade tool that will upgrade a V4 Store to a V5 Store. @@ -407,87 +408,39 @@ public class BDBStoreUpgrade { _logger.info("Starting store upgrade from version 4"); - //Migrate _exchangeDb; + //Migrate _exchangeDb _logger.info("Exchanges"); moveContents(_oldMessageStore.getExchangesDb(), _newMessageStore.getExchangesDb(), "Exchange"); - final List<AMQShortString> topicExchanges = new ArrayList<AMQShortString>(); - final TupleBinding exchangeTB = new ExchangeTB(); - - DatabaseVisitor exchangeListVisitor = new DatabaseVisitor() - { - public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException - { - ExchangeRecord exchangeRec = (ExchangeRecord) exchangeTB.entryToObject(value); - AMQShortString type = exchangeRec.getType(); - if (ExchangeDefaults.TOPIC_EXCHANGE_CLASS.equals(type)) - { - topicExchanges.add(exchangeRec.getNameShortString()); - } - } - }; + TopicExchangeDiscoverer exchangeListVisitor = new TopicExchangeDiscoverer(); _oldMessageStore.visitExchanges(exchangeListVisitor); - //Migrate _queueBindingsDb; + //Migrate _queueBindingsDb _logger.info("Queue Bindings"); moveContents(_oldMessageStore.getBindingsDb(), _newMessageStore.getBindingsDb(), "Queue Binding"); //Inspect the bindings to gather a list of queues which are probably durable subscriptions, i.e. those //which have a colon in their name and are bound to the Topic exchanges above - final List<AMQShortString> durableSubQueues = new ArrayList<AMQShortString>(); - final TupleBinding<BindingKey> bindingTB = _oldMessageStore.getBindingTupleBindingFactory().getInstance(); - - DatabaseVisitor durSubQueueListVisitor = new DatabaseVisitor() - { - public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException - { - BindingKey bindingRec = (BindingKey) bindingTB.entryToObject(key); - AMQShortString queueName = bindingRec.getQueueName(); - AMQShortString exchangeName = bindingRec.getExchangeName(); - - if (topicExchanges.contains(exchangeName) && queueName.asString().contains(":")) - { - durableSubQueues.add(queueName); - } - } - }; + DurableSubDiscoverer durSubQueueListVisitor = + new DurableSubDiscoverer(exchangeListVisitor.getTopicExchanges(), + _oldMessageStore.getBindingTupleBindingFactory().getInstance()); _oldMessageStore.visitBindings(durSubQueueListVisitor); + final List<AMQShortString> durableSubQueues = durSubQueueListVisitor.getDurableSubQueues(); - //Migrate _queueDb; + //Migrate _queueDb _logger.info("Queues"); // hold the list of existing queue names - final List<AMQShortString> existingQueues = new ArrayList<AMQShortString>(); final TupleBinding<QueueRecord> queueTupleBinding = _oldMessageStore.getQueueTupleBindingFactory().getInstance(); - DatabaseVisitor queueVisitor = new DatabaseVisitor() - { - public void visit(DatabaseEntry key, DatabaseEntry value) throws AMQStoreException - { - QueueRecord queueRec = (QueueRecord) queueTupleBinding.entryToObject(value); - AMQShortString queueName = queueRec.getNameShortString(); - - //if the queue name is in the gathered list then set its exclusivity true - if (durableSubQueues.contains(queueName)) - { - _logger.info("Marking as possible DurableSubscription backing queue: " + queueName); - queueRec.setExclusive(true); - } - - //The simple call to createQueue with the QueueRecord object is sufficient for a v2->v3 upgrade as - //the extra 'exclusive' property in v3 will be defaulted to false in the record creation. - _newMessageStore.createQueue(queueRec); - - _count++; - existingQueues.add(queueName); - } - }; + QueueVisitor queueVisitor = new QueueVisitor(queueTupleBinding, durableSubQueues, _newMessageStore); _oldMessageStore.visitQueues(queueVisitor); + final List<AMQShortString> existingQueues = queueVisitor.getExistingQueues(); logCount(queueVisitor.getVisitedCount(), "Queue"); @@ -495,42 +448,15 @@ public class BDBStoreUpgrade // Look for persistent messages stored for non-durable queues _logger.info("Checking for messages previously sent to non-durable queues"); - // track all message delivery to existing queues - final HashSet<Long> queueMessages = new HashSet<Long>(); - - // hold all non existing queues and their messages IDs - final HashMap<String, HashSet<Long>> phantomMessageQueues = new HashMap<String, HashSet<Long>>(); - // delivery DB visitor to check message delivery and identify non existing queues final QueueEntryTB queueEntryTB = new QueueEntryTB(); - DatabaseVisitor messageDeliveryCheckVisitor = new DatabaseVisitor() - { - public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException - { - QueueEntryKey entryKey = (QueueEntryKey) queueEntryTB.entryToObject(key); - Long messageId = entryKey.getMessageId(); - AMQShortString queueName = entryKey.getQueueName(); - if (!existingQueues.contains(queueName)) - { - String name = queueName.asString(); - HashSet<Long> messages = phantomMessageQueues.get(name); - if (messages == null) - { - messages = new HashSet<Long>(); - phantomMessageQueues.put(name, messages); - } - messages.add(messageId); - _count++; - } - else - { - queueMessages.add(messageId); - } - } - }; + MessageDeliveryCheckVisitor messageDeliveryCheckVisitor = + new MessageDeliveryCheckVisitor(queueEntryTB, queueVisitor.getExistingQueues()); _oldMessageStore.visitDelivery(messageDeliveryCheckVisitor); - if (phantomMessageQueues.isEmpty()) + final Set<Long> queueMessages = messageDeliveryCheckVisitor.getQueueMessages(); + + if (messageDeliveryCheckVisitor.getPhantomMessageQueues().isEmpty()) { _logger.info("No such messages were found"); } @@ -538,7 +464,7 @@ public class BDBStoreUpgrade { _logger.info("Found " + messageDeliveryCheckVisitor.getVisitedCount()+ " such messages in total"); - for (Entry<String, HashSet<Long>> phantomQueue : phantomMessageQueues.entrySet()) + for (Entry<String, HashSet<Long>> phantomQueue : messageDeliveryCheckVisitor.getPhantomMessageQueues().entrySet()) { String queueName = phantomQueue.getKey(); HashSet<Long> messages = phantomQueue.getValue(); @@ -572,40 +498,20 @@ public class BDBStoreUpgrade } - //Migrate _messageMetaDataDb; + //Migrate _messageMetaDataDb _logger.info("Message MetaData"); final Database newMetaDataDB = _newMessageStore.getMetaDataDb(); - final TupleBinding<Object> oldMetaDataTupleBinding = _oldMessageStore.getMetaDataTupleBindingFactory().getInstance(); - final TupleBinding<Object> newMetaDataTupleBinding = _newMessageStore.getMetaDataTupleBindingFactory().getInstance(); - - DatabaseVisitor metaDataVisitor = new DatabaseVisitor() - { - public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException - { - _count++; - MessageMetaData metaData = (MessageMetaData) oldMetaDataTupleBinding.entryToObject(value); - - // get message id - Long messageId = TupleBinding.getPrimitiveBinding(Long.class).entryToObject(key); - // ONLY copy data if message is delivered to existing queue - if (!queueMessages.contains(messageId)) - { - return; - } - DatabaseEntry newValue = new DatabaseEntry(); - newMetaDataTupleBinding.objectToEntry(metaData, newValue); - - newMetaDataDB.put(null, key, newValue); - } - }; + MetaDataVisitor metaDataVisitor = new MetaDataVisitor(queueMessages, newMetaDataDB, + _oldMessageStore.getMetaDataTupleBindingFactory().getInstance(), + _newMessageStore.getMetaDataTupleBindingFactory().getInstance()); _oldMessageStore.visitMetaDataDb(metaDataVisitor); logCount(metaDataVisitor.getVisitedCount(), "Message MetaData"); - //Migrate _messageContentDb; + //Migrate _messageContentDb _logger.info("Message Contents"); final Database newContentDB = _newMessageStore.getContentDb(); @@ -613,74 +519,17 @@ public class BDBStoreUpgrade final TupleBinding<MessageContentKey> newContentKeyTupleBinding = new MessageContentKeyTB_5(); final TupleBinding contentTB = new ContentTB(); - DatabaseVisitor contentVisitor = new DatabaseVisitor() - { - private long _prevMsgId = -1; //Initialise to invalid value - private int _bytesSeenSoFar = 0; - - public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException - { - _count++; - - //determine the msgId of the current entry - MessageContentKey_4 contentKey = (MessageContentKey_4) oldContentKeyTupleBinding.entryToObject(key); - long msgId = contentKey.getMessageId(); - - // ONLY copy data if message is delivered to existing queue - if (!queueMessages.contains(msgId)) - { - return; - } - //if this is a new message, restart the byte offset count. - if(_prevMsgId != msgId) - { - _bytesSeenSoFar = 0; - } - - //determine the content size - ByteBuffer content = (ByteBuffer) contentTB.entryToObject(value); - int contentSize = content.limit(); - - //create the new key: id + previously seen data count - MessageContentKey_5 newKey = new MessageContentKey_5(msgId, _bytesSeenSoFar); - DatabaseEntry newKeyEntry = new DatabaseEntry(); - newContentKeyTupleBinding.objectToEntry(newKey, newKeyEntry); - - DatabaseEntry newValueEntry = new DatabaseEntry(); - contentTB.objectToEntry(content, newValueEntry); - - newContentDB.put(null, newKeyEntry, newValueEntry); - - _prevMsgId = msgId; - _bytesSeenSoFar += contentSize; - } - }; + DatabaseVisitor contentVisitor = new ContentVisitor(oldContentKeyTupleBinding, queueMessages, + contentTB, newContentKeyTupleBinding, newContentDB); _oldMessageStore.visitContentDb(contentVisitor); logCount(contentVisitor.getVisitedCount(), "Message Content"); - //Migrate _deliveryDb; + //Migrate _deliveryDb _logger.info("Delivery Records"); final Database deliveryDb =_newMessageStore.getDeliveryDb(); - DatabaseVisitor deliveryDbVisitor = new DatabaseVisitor() - { - - public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException - { - _count++; - - // get message id from entry key - QueueEntryKey entryKey = (QueueEntryKey) queueEntryTB.entryToObject(key); - AMQShortString queueName = entryKey.getQueueName(); - - // ONLY copy data if message queue exists - if (existingQueues.contains(queueName)) - { - deliveryDb.put(null, key, value); - } - } - }; + DatabaseVisitor deliveryDbVisitor = new DeliveryDbVisitor(queueEntryTB, existingQueues, deliveryDb); _oldMessageStore.visitDelivery(deliveryDbVisitor); logCount(contentVisitor.getVisitedCount(), "Delivery Record"); } @@ -711,7 +560,7 @@ public class BDBStoreUpgrade { public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException { - _count++; + incrementCount(); newDatabase.put(null, key, value); } }; @@ -1117,4 +966,280 @@ public class BDBStoreUpgrade System.exit(0); } + private static class TopicExchangeDiscoverer extends DatabaseVisitor + { + private final List<AMQShortString> topicExchanges = new ArrayList<AMQShortString>(); + private final TupleBinding exchangeTB = new ExchangeTB(); + + public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException + { + ExchangeRecord exchangeRec = (ExchangeRecord) exchangeTB.entryToObject(value); + AMQShortString type = exchangeRec.getType(); + + if (ExchangeDefaults.TOPIC_EXCHANGE_CLASS.equals(type)) + { + topicExchanges.add(exchangeRec.getNameShortString()); + } + } + + public List<AMQShortString> getTopicExchanges() + { + return topicExchanges; + } + } + + private static class MessageDeliveryCheckVisitor extends DatabaseVisitor + { + private final QueueEntryTB _queueEntryTB; + private final List<AMQShortString> _existingQueues; + + // track all message delivery to existing queues + private final HashSet<Long> _queueMessages = new HashSet<Long>(); + + // hold all non existing queues and their messages IDs + private final HashMap<String, HashSet<Long>> _phantomMessageQueues = new HashMap<String, HashSet<Long>>(); + + + + public MessageDeliveryCheckVisitor(QueueEntryTB queueEntryTB, List<AMQShortString> existingQueues) + { + _queueEntryTB = queueEntryTB; + _existingQueues = existingQueues; + } + + public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException + { + QueueEntryKey entryKey = (QueueEntryKey) _queueEntryTB.entryToObject(key); + Long messageId = entryKey.getMessageId(); + AMQShortString queueName = entryKey.getQueueName(); + if (!_existingQueues.contains(queueName)) + { + String name = queueName.asString(); + HashSet<Long> messages = _phantomMessageQueues.get(name); + if (messages == null) + { + messages = new HashSet<Long>(); + _phantomMessageQueues.put(name, messages); + } + messages.add(messageId); + incrementCount(); + } + else + { + _queueMessages.add(messageId); + } + } + + public HashSet<Long> getQueueMessages() + { + return _queueMessages; + } + + public HashMap<String, HashSet<Long>> getPhantomMessageQueues() + { + return _phantomMessageQueues; + } + } + + private static class ContentVisitor extends DatabaseVisitor + { + private long _prevMsgId; //Initialise to invalid value + private int _bytesSeenSoFar; + private final TupleBinding<MessageContentKey> _oldContentKeyTupleBinding; + private final Set<Long> _queueMessages; + private final TupleBinding _contentTB; + private final TupleBinding<MessageContentKey> _newContentKeyTupleBinding; + private final Database _newContentDB; + + public ContentVisitor(TupleBinding<MessageContentKey> oldContentKeyTupleBinding, Set<Long> queueMessages, TupleBinding contentTB, TupleBinding<MessageContentKey> newContentKeyTupleBinding, Database newContentDB) + { + _oldContentKeyTupleBinding = oldContentKeyTupleBinding; + _queueMessages = queueMessages; + _contentTB = contentTB; + _newContentKeyTupleBinding = newContentKeyTupleBinding; + _newContentDB = newContentDB; + _prevMsgId = -1; + _bytesSeenSoFar = 0; + } + + public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException + { + incrementCount(); + + //determine the msgId of the current entry + MessageContentKey_4 contentKey = (MessageContentKey_4) _oldContentKeyTupleBinding.entryToObject(key); + long msgId = contentKey.getMessageId(); + + // ONLY copy data if message is delivered to existing queue + if (!_queueMessages.contains(msgId)) + { + return; + } + //if this is a new message, restart the byte offset count. + if(_prevMsgId != msgId) + { + _bytesSeenSoFar = 0; + } + + //determine the content size + ByteBuffer content = (ByteBuffer) _contentTB.entryToObject(value); + int contentSize = content.limit(); + + //create the new key: id + previously seen data count + MessageContentKey_5 newKey = new MessageContentKey_5(msgId, _bytesSeenSoFar); + DatabaseEntry newKeyEntry = new DatabaseEntry(); + _newContentKeyTupleBinding.objectToEntry(newKey, newKeyEntry); + + DatabaseEntry newValueEntry = new DatabaseEntry(); + _contentTB.objectToEntry(content, newValueEntry); + + _newContentDB.put(null, newKeyEntry, newValueEntry); + + _prevMsgId = msgId; + _bytesSeenSoFar += contentSize; + } + } + + private static class DeliveryDbVisitor extends DatabaseVisitor + { + + private final QueueEntryTB _queueEntryTB; + private final List<AMQShortString> _existingQueues; + private final Database _deliveryDb; + + public DeliveryDbVisitor(QueueEntryTB queueEntryTB, List<AMQShortString> existingQueues, Database deliveryDb) + { + _queueEntryTB = queueEntryTB; + _existingQueues = existingQueues; + _deliveryDb = deliveryDb; + } + + public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException + { + incrementCount(); + + // get message id from entry key + QueueEntryKey entryKey = (QueueEntryKey) _queueEntryTB.entryToObject(key); + AMQShortString queueName = entryKey.getQueueName(); + + // ONLY copy data if message queue exists + if (_existingQueues.contains(queueName)) + { + _deliveryDb.put(null, key, value); + } + } + } + + private class DurableSubDiscoverer extends DatabaseVisitor + { + private final List<AMQShortString> _durableSubQueues; + private final TupleBinding<BindingKey> _bindingTB; + private final List<AMQShortString> _topicExchanges; + + + public DurableSubDiscoverer(List<AMQShortString> topicExchanges, TupleBinding<BindingKey> bindingTB) + { + _durableSubQueues = new ArrayList<AMQShortString>(); + _bindingTB = bindingTB; + _topicExchanges = topicExchanges; + } + + public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException + { + BindingKey bindingRec = _bindingTB.entryToObject(key); + AMQShortString queueName = bindingRec.getQueueName(); + AMQShortString exchangeName = bindingRec.getExchangeName(); + + if (_topicExchanges.contains(exchangeName) && queueName.asString().contains(":")) + { + _durableSubQueues.add(queueName); + } + } + + public List<AMQShortString> getDurableSubQueues() + { + return _durableSubQueues; + } + } + + private static class QueueVisitor extends DatabaseVisitor + { + private final TupleBinding<QueueRecord> _queueTupleBinding; + private final List<AMQShortString> _durableSubQueues; + private final List<AMQShortString> _existingQueues = new ArrayList<AMQShortString>(); + private final BDBMessageStore _newMessageStore; + + public QueueVisitor(TupleBinding<QueueRecord> queueTupleBinding, + List<AMQShortString> durableSubQueues, + BDBMessageStore newMessageStore) + { + _queueTupleBinding = queueTupleBinding; + _durableSubQueues = durableSubQueues; + _newMessageStore = newMessageStore; + } + + public void visit(DatabaseEntry key, DatabaseEntry value) throws AMQStoreException + { + QueueRecord queueRec = _queueTupleBinding.entryToObject(value); + AMQShortString queueName = queueRec.getNameShortString(); + + //if the queue name is in the gathered list then set its exclusivity true + if (_durableSubQueues.contains(queueName)) + { + _logger.info("Marking as possible DurableSubscription backing queue: " + queueName); + queueRec.setExclusive(true); + } + + //The simple call to createQueue with the QueueRecord object is sufficient for a v2->v3 upgrade as + //the extra 'exclusive' property in v3 will be defaulted to false in the record creation. + _newMessageStore.createQueue(queueRec); + + incrementCount(); + _existingQueues.add(queueName); + } + + public List<AMQShortString> getExistingQueues() + { + return _existingQueues; + } + } + + private static class MetaDataVisitor extends DatabaseVisitor + { + private final TupleBinding<Object> _oldMetaDataTupleBinding; + private final TupleBinding<Object> _newMetaDataTupleBinding; + private final Set<Long> _queueMessages; + private final Database _newMetaDataDB; + + public MetaDataVisitor(Set<Long> queueMessages, + Database newMetaDataDB, + TupleBinding<Object> oldMetaDataTupleBinding, + TupleBinding<Object> newMetaDataTupleBinding) + { + _queueMessages = queueMessages; + _newMetaDataDB = newMetaDataDB; + _oldMetaDataTupleBinding = oldMetaDataTupleBinding; + _newMetaDataTupleBinding = newMetaDataTupleBinding; + } + + + public void visit(DatabaseEntry key, DatabaseEntry value) throws DatabaseException + { + incrementCount(); + MessageMetaData metaData = (MessageMetaData) _oldMetaDataTupleBinding.entryToObject(value); + + // get message id + Long messageId = TupleBinding.getPrimitiveBinding(Long.class).entryToObject(key); + + // ONLY copy data if message is delivered to existing queue + if (!_queueMessages.contains(messageId)) + { + return; + } + DatabaseEntry newValue = new DatabaseEntry(); + _newMetaDataTupleBinding.objectToEntry(metaData, newValue); + + _newMetaDataDB.put(null, key, newValue); + } + } } diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/DatabaseVisitor.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/DatabaseVisitor.java index 26a3b674ae..c6a1372d7e 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/DatabaseVisitor.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/DatabaseVisitor.java @@ -28,15 +28,20 @@ import org.apache.qpid.AMQStoreException; /** Visitor Interface so that each DatabaseEntry for a database can easily be processed. */ public abstract class DatabaseVisitor { - protected int _count; + private int _count; abstract public void visit(DatabaseEntry entry, DatabaseEntry value) throws AMQStoreException, DatabaseException; - public int getVisitedCount() + public final int getVisitedCount() { return _count; } + protected final void incrementCount() + { + _count++; + } + public void resetVisitCount() { _count = 0; diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/FieldTableEncoding.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/FieldTableEncoding.java index 371f0fed05..a876a056fc 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/FieldTableEncoding.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/FieldTableEncoding.java @@ -32,6 +32,10 @@ import java.io.IOException; public class FieldTableEncoding { + private FieldTableEncoding() + { + } + public static FieldTable readFieldTable(TupleInput tupleInput) throws DatabaseException { long length = tupleInput.readLong(); diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/BindingTupleBindingFactory.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/BindingTupleBindingFactory.java index c60f981011..09d43e6a08 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/BindingTupleBindingFactory.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/BindingTupleBindingFactory.java @@ -33,7 +33,7 @@ public class BindingTupleBindingFactory extends TupleBindingFactory<BindingKey> public TupleBinding<BindingKey> getInstance() { - switch (_version) + switch (getVersion()) { default: case 5: diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/MessageContentKeyTupleBindingFactory.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/MessageContentKeyTupleBindingFactory.java index 872ec87ad6..4a320f49c9 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/MessageContentKeyTupleBindingFactory.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/MessageContentKeyTupleBindingFactory.java @@ -33,7 +33,7 @@ public class MessageContentKeyTupleBindingFactory extends TupleBindingFactory<Me public TupleBinding<MessageContentKey> getInstance() { - switch (_version) + switch (getVersion()) { default: case 5: diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/MessageMetaDataTupleBindingFactory.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/MessageMetaDataTupleBindingFactory.java index 40153c13ea..cb742e76a1 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/MessageMetaDataTupleBindingFactory.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/MessageMetaDataTupleBindingFactory.java @@ -31,7 +31,7 @@ public class MessageMetaDataTupleBindingFactory extends TupleBindingFactory<Obje public TupleBinding<Object> getInstance() { - switch (_version) + switch (getVersion()) { default: case 5: diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTupleBindingFactory.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTupleBindingFactory.java index ccdf4492e6..a189786885 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTupleBindingFactory.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTupleBindingFactory.java @@ -34,7 +34,7 @@ public class QueueTupleBindingFactory extends TupleBindingFactory<QueueRecord> public TupleBinding<QueueRecord> getInstance() { - switch (_version) + switch (getVersion()) { default: case 5: diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTuple_4.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTuple_4.java index d57534e547..d2ba4dbbca 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTuple_4.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTuple_4.java @@ -34,9 +34,7 @@ import org.apache.qpid.server.store.berkeleydb.records.QueueRecord; public class QueueTuple_4 extends TupleBinding<QueueRecord> implements QueueTuple { - protected static final Logger _logger = Logger.getLogger(QueueTuple_4.class); - - protected FieldTable _arguments; + private static final Logger _logger = Logger.getLogger(QueueTuple_4.class); public QueueTuple_4() { diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTuple_5.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTuple_5.java index 0a0163b239..c9094a132d 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTuple_5.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/QueueTuple_5.java @@ -33,9 +33,7 @@ import org.apache.qpid.server.store.berkeleydb.records.QueueRecord; public class QueueTuple_5 extends QueueTuple_4 { - protected static final Logger _logger = Logger.getLogger(QueueTuple_5.class); - - protected FieldTable _arguments; + private static final Logger _logger = Logger.getLogger(QueueTuple_5.class); public QueueTuple_5() { diff --git a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/TupleBindingFactory.java b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/TupleBindingFactory.java index 2adac1f9a3..97b1398e10 100644 --- a/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/TupleBindingFactory.java +++ b/java/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuples/TupleBindingFactory.java @@ -24,7 +24,7 @@ import com.sleepycat.bind.tuple.TupleBinding; public abstract class TupleBindingFactory<E> { - protected int _version; + private final int _version; public TupleBindingFactory(int version) { @@ -32,4 +32,9 @@ public abstract class TupleBindingFactory<E> } public abstract TupleBinding<E> getInstance(); + + public int getVersion() + { + return _version; + } } diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java index a684e52ce4..f04dd38aca 100644 --- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java +++ b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/AbstractConfiguration.java @@ -27,10 +27,10 @@ import org.apache.log4j.Logger; public abstract class AbstractConfiguration implements ConfigurationFile { - protected static final Logger _logger = Logger.getLogger(ConfigurationFile.class); + private static final Logger _logger = Logger.getLogger(ConfigurationFile.class); - protected File _file; - protected RuleSet _config; + private File _file; + private RuleSet _config; public AbstractConfiguration(File file) { diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java index fdbd96e63e..0a084c97fe 100644 --- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java +++ b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/Action.java @@ -21,8 +21,6 @@ package org.apache.qpid.server.security.access.config; import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; @@ -35,7 +33,7 @@ import org.apache.qpid.server.security.access.Operation; /** * An access control v2 rule action. * - * An action consists of an {@link Operation} on an {@link ObjectType} with certain properties, stored in a {@link Map}. + * An action consists of an {@link Operation} on an {@link ObjectType} with certain properties, stored in a {@link java.util.Map}. * The operation and object should be an allowable combination, based on the {@link ObjectType#isAllowed(Operation)} * method of the object, which is exposed as the {@link #isAllowed()} method here. The internal {@link #propertiesMatch(Map)} * and {@link #valueMatches(String, String)} methods are used to determine wildcarded matching of properties, with @@ -136,12 +134,6 @@ public class Action } else if (a.getOperation() == b.getOperation()) { - // Same operator, compare rest of action - -// || (getOperation() == a.getOperation() -// && getObjectType() == a.getObjectType() -// && _properties.matches(a.getProperties()))); - return 1; // b is more specific } else // Different operations diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java index 9f2168a31c..b299b62538 100644 --- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java +++ b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/PlainConfiguration.java @@ -78,7 +78,7 @@ public class PlainConfiguration extends AbstractConfiguration try { - _st = new StreamTokenizer(new BufferedReader(new FileReader(_file))); + _st = new StreamTokenizer(new BufferedReader(new FileReader(getFile()))); _st.resetSyntax(); // setup the tokenizer _st.commentChar(COMMENT); // single line comments diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java index 402b991419..815df99f80 100644 --- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java +++ b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/config/RuleSet.java @@ -312,9 +312,9 @@ public class RuleSet return true; } - // C++ broker authorise function prototype + // CPP broker authorise function prototype // virtual bool authorise(const std::string& id, const Action& action, const ObjectType& objType, - // const std::string& name, std::map<Property, std::string>* params=0); + // const std::string& name, std::map<Property, std::string>* params=0) // Possibly add a String name paramater? diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java index 72eac7dbe6..7c83446cf1 100644 --- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java +++ b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlActivator.java @@ -23,10 +23,9 @@ package org.apache.qpid.server.security.access.plugins; import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import org.apache.qpid.server.security.SecurityPluginActivator; import org.apache.qpid.server.security.SecurityPluginFactory; -import org.osgi.framework.BundleActivator; /** - * The OSGi {@link BundleActivator} for {@link AccessControl}. + * The OSGi {@link org.osgi.framework.BundleActivator} for {@link AccessControl}. */ public class AccessControlActivator extends SecurityPluginActivator { diff --git a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java index b5c89910a6..c4db6db820 100644 --- a/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java +++ b/java/broker-plugins/access-control/src/main/java/org/apache/qpid/server/security/access/plugins/AccessControlConfiguration.java @@ -58,7 +58,7 @@ public class AccessControlConfiguration extends ConfigurationPlugin public String getFileName() { - return _configuration.getString(""); + return getConfig().getString(""); } public void validateConfiguration() throws ConfigurationException diff --git a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java index c8e9805cd9..3a98e627b0 100644 --- a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java +++ b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/AppInfo.java @@ -42,6 +42,10 @@ public class AppInfo private static Map<String, String> appInfoMap = new TreeMap<String, String>(); + private AppInfo() + { + } + /** * getInfo method retrieves a key-value map for specific application properties * diff --git a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java index 7c0eb61f1d..cf370d7384 100644 --- a/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java +++ b/java/broker-plugins/experimental/info/src/main/java/org/apache/qpid/info/SystemInfo.java @@ -45,6 +45,10 @@ public class SystemInfo "os.arch", "os.name", "os.version", "sun.arch.data.model", "user.home", "user.dir", "user.name", "user.timezone"); + private SystemInfo() + { + } + /** * getInfo collects all the properties specified in sysprops list * @return A Map<String,String> diff --git a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java b/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java index c433433df5..6e1ea25f26 100644 --- a/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java +++ b/java/broker-plugins/extras/src/main/java/org/apache/qpid/extras/exchanges/diagnostic/DiagnosticExchange.java @@ -54,9 +54,6 @@ public class DiagnosticExchange extends AbstractExchange public static final AMQShortString DIAGNOSTIC_EXCHANGE_CLASS = new AMQShortString("x-diagnostic"); public static final AMQShortString DIAGNOSTIC_EXCHANGE_NAME = new AMQShortString("diagnostic"); - /** The logger */ - //private static final Logger _logger = Logger.getLogger(DiagnosticExchange.class); - /** * MBean class implementing the management interfaces. */ @@ -83,7 +80,6 @@ public class DiagnosticExchange extends AbstractExchange * @returns null * TODO or can there? Could this actually return all the information in one easy to read table? */ - @Override public TabularData bindings() throws OpenDataException { return null; @@ -197,13 +193,6 @@ public class DiagnosticExchange extends AbstractExchange public ArrayList<AMQQueue> doRoute(InboundMessage payload) { //TODO shouldn't modify messages... perhaps put a new message on the queue? - /* - Long value = new Long(SizeOf.getUsedMemory()); - AMQShortString key = new AMQShortString("memory"); - FieldTable headers = ((BasicContentHeaderProperties)payload.getMessageHeader().properties).getHeaders(); - headers.put(key, value); - ((BasicContentHeaderProperties)payload.getMessageHeader().properties).setHeaders(headers); - */ AMQQueue q = getQueueRegistry().getQueue(new AMQShortString("diagnosticqueue")); ArrayList<AMQQueue> queues = new ArrayList<AMQQueue>(); queues.add(q); diff --git a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java b/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java index 42086ce6ad..1669352085 100644 --- a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java +++ b/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallActivator.java @@ -20,14 +20,12 @@ */ package org.apache.qpid.server.security.access.plugins; -import org.osgi.framework.BundleActivator; - import org.apache.qpid.server.configuration.plugins.ConfigurationPluginFactory; import org.apache.qpid.server.security.SecurityPluginActivator; import org.apache.qpid.server.security.SecurityPluginFactory; /** - * The OSGi {@link BundleActivator} for {@link Firewall}. + * The OSGi {@link org.osgi.framework.BundleActivator} for {@link Firewall}. */ public class FirewallActivator extends SecurityPluginActivator { diff --git a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java b/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java index 57d7b27ee3..010d1652f0 100644 --- a/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java +++ b/java/broker-plugins/firewall/src/main/java/org/apache/qpid/server/security/access/plugins/FirewallConfiguration.java @@ -64,7 +64,7 @@ public class FirewallConfiguration extends ConfigurationPlugin public Result getDefaultAction() { - String defaultAction = _configuration.getString("[@default-action]"); + String defaultAction = getConfig().getString("[@default-action]"); if (defaultAction == null) { return Result.ABSTAIN; @@ -85,8 +85,8 @@ public class FirewallConfiguration extends ConfigurationPlugin public void validateConfiguration() throws ConfigurationException { // Valid Configuration either has xml links to new files - _finalConfig = new CompositeConfiguration(_configuration); - List subFiles = _configuration.getList("xml[@fileName]"); + _finalConfig = new CompositeConfiguration(getConfig()); + List subFiles = getConfig().getList("xml[@fileName]"); for (Object subFile : subFiles) { _finalConfig.addConfiguration(new XMLConfiguration((String) subFile)); @@ -94,7 +94,7 @@ public class FirewallConfiguration extends ConfigurationPlugin // all rules must have an access attribute or a default value if (_finalConfig.getList("rule[@access]").size() == 0 && - _configuration.getString("[@default-action]") == null) + getConfig().getString("[@default-action]") == null) { throw new ConfigurationException("No rules or default-action found in firewall configuration."); } diff --git a/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java b/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java index 96608acd42..54ca574871 100644 --- a/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java +++ b/java/broker/src/main/java/org/apache/log4j/QpidCompositeRollingAppender.java @@ -290,7 +290,6 @@ public class QpidCompositeRollingAppender extends FileAppender c.setType(i); Date next = new Date(c.getNextCheckMillis(epoch)); String r1 = sdf.format(next); - // LogLog.debug("Type = "+i+", r0 = "+r0+", r1 = "+r1); if ((r0 != null) && (r1 != null) && !r0.equals(r1)) { return i; @@ -405,19 +404,6 @@ public class QpidCompositeRollingAppender extends FileAppender } } - /* - public void setRollingStyle(String style) { - if (style == S_BY_SIZE) { - rollingStyle = BY_SIZE; - } - else if (style == S_BY_DATE) { - rollingStyle = BY_DATE; - } - else if (style == S_BY_COMPOSITE) { - rollingStyle = BY_COMPOSITE; - } - } - */ public boolean getStaticLogFileName() { return staticLogFileName; @@ -535,7 +521,6 @@ public class QpidCompositeRollingAppender extends FileAppender now.setTime(System.currentTimeMillis()); sdf = new SimpleDateFormat(datePattern); int type = computeCheckPeriod(); - // printPeriodicity(type); rc.setType(type); // next line added as this removes the name check in rollOver nextCheck = rc.getNextCheckMillis(now); @@ -783,7 +768,9 @@ public class QpidCompositeRollingAppender extends FileAppender curSizeRollBackups--; } } - // Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2} + /* + map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}. + */ for (int i = curSizeRollBackups; i >= 1; i--) { String oldName = (fileName + "." + i); diff --git a/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java b/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java index c6bfd34f45..4c083de41a 100644 --- a/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java +++ b/java/broker/src/main/java/org/apache/qpid/configuration/Configuration.java @@ -120,58 +120,8 @@ public class Configuration _devlog.debug("Using configuration file " + _configFile.getAbsolutePath()); } -// String logConfig = _commandLine.getOptionValue("l"); -// String logWatchConfig = _commandLine.getOptionValue("w", "0"); -// if (logConfig != null) -// { -// File logConfigFile = new File(logConfig); -// configureLogging(logConfigFile, logWatchConfig); -// } -// else -// { -// File configFileDirectory = _configFile.getParentFile(); -// File logConfigFile = new File(configFileDirectory, DEFAULT_LOG_CONFIG_FILENAME); -// configureLogging(logConfigFile, logWatchConfig); -// } } - -// private void configureLogging(File logConfigFile, String logWatchConfig) -// { -// int logWatchTime = 0; -// try -// { -// logWatchTime = Integer.parseInt(logWatchConfig); -// } -// catch (NumberFormatException e) -// { -// _devlog.error("Log watch configuration value of " + logWatchConfig + " is invalid. Must be " -// + "a non-negative integer. Using default of zero (no watching configured"); -// } -// -// if (logConfigFile.exists() && logConfigFile.canRead()) -// { -// _devlog.info("Configuring logger using configuration file " + logConfigFile.getAbsolutePath()); -// if (logWatchTime > 0) -// { -// _devlog.info("log file " + logConfigFile.getAbsolutePath() + " will be checked for changes every " -// + logWatchTime + " seconds"); -// // log4j expects the watch interval in milliseconds -// DOMConfigurator.configureAndWatch(logConfigFile.getAbsolutePath(), logWatchTime * 1000); -// } -// else -// { -// DOMConfigurator.configure(logConfigFile.getAbsolutePath()); -// } -// } -// else -// { -// System.err.println("Logging configuration error: unable to read file " + logConfigFile.getAbsolutePath()); -// System.err.println("Using basic log4j configuration"); -// BasicConfigurator.configure(); -// } -// } - public File getConfigFile() { return _configFile; diff --git a/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java b/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java index 70aee947c8..5314466e2a 100644 --- a/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java +++ b/java/broker/src/main/java/org/apache/qpid/qmf/QMFProperty.java @@ -67,8 +67,6 @@ public class QMFProperty public void setQMFClass(QMFClass qmfClass) { - /* _map.put(REF_CLASS, qmfClass.getName()); - _map.put(REF_PACKAGE, qmfClass.getPackage().getName());*/ } public void setReferencedClass(String refClass) diff --git a/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java b/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java index dc5f45cede..265aa7714e 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java +++ b/java/broker/src/main/java/org/apache/qpid/server/AMQBrokerManagerMBean.java @@ -212,7 +212,7 @@ public class AMQBrokerManagerMBean extends AMQManagedObject implements ManagedBr { // TODO // Check if the exchange is in use. - // boolean inUse = false; + // Check if there are queue-bindings with the exchange and unregister // when there are no bindings. CurrentActor.set(new ManagementActor(getLogActor().getRootMessageLogger())); diff --git a/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java b/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java index f4a7a07331..46657e2a9a 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java +++ b/java/broker/src/main/java/org/apache/qpid/server/AMQChannel.java @@ -784,20 +784,6 @@ public class AMQChannel implements SessionConfig, AMQSessionModel, AsyncAutoComm AMQQueue queue = message.getQueue(); - // Our Java Client will always suspend the channel when resending! - // If the client has requested the messages be resent then it is - // their responsibility to ensure that thay are capable of receiving them - // i.e. The channel hasn't been server side suspended. - // if (isSuspended()) - // { - // _logger.info("Channel is suspended so requeuing"); - // //move this message to requeue - // msgToRequeue.add(message); - // } - // else - // { - // release to allow it to be delivered - // Without any details from the client about what has been processed we have to mark // all messages in the unacked map as redelivered. message.setRedelivered(); diff --git a/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java b/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java index 48f85d9bc9..8e44da095a 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java +++ b/java/broker/src/main/java/org/apache/qpid/server/binding/Binding.java @@ -94,7 +94,7 @@ public class Binding return true; } - if (o == null || !(o instanceof Binding)) + if (!(o instanceof Binding)) { return false; } diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java index 46cf8c525c..40bafb4275 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java +++ b/java/broker/src/main/java/org/apache/qpid/server/configuration/QueueConfiguration.java @@ -205,7 +205,7 @@ public class QueueConfiguration extends ConfigurationPlugin public void validateConfiguration() throws ConfigurationException { - if (_configuration.isEmpty()) + if (getConfig().isEmpty()) { throw new ConfigurationException("Queue section cannot be empty."); } diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java index 0f7fb513d6..cb6ebb9b95 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java +++ b/java/broker/src/main/java/org/apache/qpid/server/configuration/ServerConfiguration.java @@ -176,7 +176,7 @@ public class ServerConfiguration extends ConfigurationPlugin */ public ServerConfiguration(Configuration conf) { - _configuration = conf; + setConfig(conf); } /** @@ -196,8 +196,8 @@ public class ServerConfiguration extends ConfigurationPlugin */ public void initialise() throws ConfigurationException { - setConfiguration("", _configuration); - setupVirtualHosts(_configuration); + setConfiguration("", getConfig()); + setupVirtualHosts(getConfig()); } public String[] getElementsProcessed() @@ -302,7 +302,7 @@ public class ServerConfiguration extends ConfigurationPlugin // save the default virtualhost name String defaultVirtualHost = vhostConfiguration.getString("default"); - _configuration.setProperty("virtualhosts.default", defaultVirtualHost); + getConfig().setProperty("virtualhosts.default", defaultVirtualHost); } } diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java index 024831ce6c..10e40151b0 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java +++ b/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfig.java @@ -29,7 +29,7 @@ public class TopicConfig extends ConfigurationPlugin { public TopicConfig() { - _configuration = new PropertiesConfiguration(); + setConfig(new PropertiesConfiguration()); } @Override @@ -51,7 +51,7 @@ public class TopicConfig extends ConfigurationPlugin public void validateConfiguration() throws ConfigurationException { - if (_configuration.isEmpty()) + if (getConfig().isEmpty()) { throw new ConfigurationException("Topic section cannot be empty."); } diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java index 7a919a5829..feafd3de1d 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java +++ b/java/broker/src/main/java/org/apache/qpid/server/configuration/TopicConfiguration.java @@ -68,17 +68,17 @@ public class TopicConfiguration extends ConfigurationPlugin implements ExchangeC @Override public void validateConfiguration() throws ConfigurationException { - if (_configuration.isEmpty()) + if (getConfig().isEmpty()) { throw new ConfigurationException("Topics section cannot be empty."); } - int topics = _configuration.getList("topic.name").size() + - _configuration.getList("topic.subscriptionName").size(); + int topics = getConfig().getList("topic.name").size() + + getConfig().getList("topic.subscriptionName").size(); for (int index = 0; index < topics; index++) { - Configuration topicSubset = _configuration.subset("topic(" + index + ")"); + Configuration topicSubset = getConfig().subset("topic(" + index + ")"); // This will occur when we have a subscriptionName that is bound to a // topic. @@ -91,8 +91,8 @@ public class TopicConfiguration extends ConfigurationPlugin implements ExchangeC topic.setConfiguration(VIRTUALHOSTS_VIRTUALHOST_TOPICS + ".topic", topicSubset ); - String name = _configuration.getString("topic(" + index + ").name"); - String subscriptionName = _configuration.getString("topic(" + index + ").subscriptionName"); + String name = getConfig().getString("topic(" + index + ").name"); + String subscriptionName = getConfig().getString("topic(" + index + ").subscriptionName"); // Record config if subscriptionName is there if (subscriptionName != null) diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java index de9b092e95..5fd261a081 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java +++ b/java/broker/src/main/java/org/apache/qpid/server/configuration/VirtualHostConfiguration.java @@ -76,7 +76,7 @@ public class VirtualHostConfiguration extends ConfigurationPlugin { CompositeConfiguration mungedConf = new CompositeConfiguration(); mungedConf.addConfiguration(config.subset("exchanges.exchange(" + count++ + ")")); - mungedConf.addConfiguration(_configuration.subset("exchanges")); + mungedConf.addConfiguration(getConfig().subset("exchanges")); String exchName = (String) i.next(); _exchanges.put(exchName, new ExchangeConfiguration(exchName, mungedConf)); } @@ -104,7 +104,7 @@ public class VirtualHostConfiguration extends ConfigurationPlugin public Configuration getStoreConfiguration() { - return _configuration.subset("store"); + return getConfig().subset("store"); } public String getMessageStoreClass() @@ -114,7 +114,7 @@ public class VirtualHostConfiguration extends ConfigurationPlugin public void setMessageStoreClass(String storeClass) { - _configuration.setProperty("store.class", storeClass); + getConfig().setProperty("store.class", storeClass); } public List getExchanges() diff --git a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java index 3b2224651d..d08e3bc806 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java +++ b/java/broker/src/main/java/org/apache/qpid/server/configuration/plugins/ConfigurationPlugin.java @@ -43,7 +43,7 @@ public abstract class ConfigurationPlugin private Map<String, ConfigurationPlugin> _pluginConfiguration = new HashMap<String, ConfigurationPlugin>(); - protected Configuration _configuration; + private Configuration _config; /** * The Elements that this Plugin can process. @@ -66,7 +66,7 @@ public abstract class ConfigurationPlugin public Configuration getConfig() { - return _configuration; + return _config; } public <C extends ConfigurationPlugin> C getConfiguration(String plugin) @@ -82,7 +82,7 @@ public abstract class ConfigurationPlugin */ public void setConfiguration(String path, Configuration configuration) throws ConfigurationException { - _configuration = configuration; + _config = configuration; // Extract a list of elements for processing Iterator<?> keys = configuration.getKeys(); @@ -216,7 +216,7 @@ public abstract class ConfigurationPlugin protected boolean hasConfiguration() { - return _configuration != null; + return _config != null; } /// Getters @@ -228,7 +228,7 @@ public abstract class ConfigurationPlugin protected double getDoubleValue(String property, double defaultValue) { - return _configuration.getDouble(property, defaultValue); + return _config.getDouble(property, defaultValue); } protected long getLongValue(String property) @@ -238,7 +238,7 @@ public abstract class ConfigurationPlugin protected long getLongValue(String property, long defaultValue) { - return _configuration.getLong(property, defaultValue); + return _config.getLong(property, defaultValue); } protected int getIntValue(String property) @@ -248,7 +248,7 @@ public abstract class ConfigurationPlugin protected int getIntValue(String property, int defaultValue) { - return _configuration.getInt(property, defaultValue); + return _config.getInt(property, defaultValue); } protected String getStringValue(String property) @@ -258,7 +258,7 @@ public abstract class ConfigurationPlugin protected String getStringValue(String property, String defaultValue) { - return _configuration.getString(property, defaultValue); + return _config.getString(property, defaultValue); } protected boolean getBooleanValue(String property) @@ -268,7 +268,7 @@ public abstract class ConfigurationPlugin protected boolean getBooleanValue(String property, boolean defaultValue) { - return _configuration.getBoolean(property, defaultValue); + return _config.getBoolean(property, defaultValue); } protected List getListValue(String property) @@ -278,14 +278,14 @@ public abstract class ConfigurationPlugin protected List getListValue(String property, List defaultValue) { - return _configuration.getList(property, defaultValue); + return _config.getList(property, defaultValue); } /// Validation Helpers protected boolean contains(String property) { - return _configuration.getProperty(property) != null; + return _config.getProperty(property) != null; } /** @@ -324,7 +324,7 @@ public abstract class ConfigurationPlugin throw new ConfigurationException(this.getClass().getSimpleName() + ": unable to configure invalid " + property + ":" + - _configuration.getString(property), + _config.getString(property), last); } } @@ -333,7 +333,7 @@ public abstract class ConfigurationPlugin { try { - _configuration.getLong(property); + _config.getLong(property); return true; } catch (NoSuchElementException e) @@ -346,7 +346,7 @@ public abstract class ConfigurationPlugin { try { - long value = _configuration.getLong(property); + long value = _config.getLong(property); return value > 0; } catch (NoSuchElementException e) @@ -360,7 +360,7 @@ public abstract class ConfigurationPlugin { try { - _configuration.getInt(property); + _config.getInt(property); return true; } catch (NoSuchElementException e) @@ -373,7 +373,7 @@ public abstract class ConfigurationPlugin { try { - _configuration.getBoolean(property); + _config.getBoolean(property); return true; } catch (NoSuchElementException e) @@ -454,7 +454,7 @@ public abstract class ConfigurationPlugin protected void mergeConfiguration(ConfigurationPlugin configuration) { - _configuration = configuration.getConfig(); + _config = configuration.getConfig(); } public String toString() @@ -479,6 +479,10 @@ public abstract class ConfigurationPlugin return super.toString(); } + protected void setConfig(Configuration config) + { + _config = config; + } } diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java index 782ef49d35..034331abd9 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java +++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/AbstractExchangeMBean.java @@ -23,7 +23,6 @@ package org.apache.qpid.server.exchange; import org.apache.qpid.AMQException; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.management.common.mbeans.ManagedExchange; -import org.apache.qpid.server.binding.BindingFactory; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.ManagementActor; import org.apache.qpid.server.management.AMQManagedObject; @@ -45,7 +44,7 @@ import javax.management.openmbean.OpenType; import javax.management.openmbean.SimpleType; import javax.management.openmbean.TabularType; import java.util.Collections; -import java.util.Map; + /** * Abstract MBean class. This has some of the methods implemented from @@ -159,7 +158,7 @@ public abstract class AbstractExchangeMBean<T extends AbstractExchange> extends /** * Removes a queue binding from the exchange. * - * @see BindingFactory#removeBinding(String, AMQQueue, Exchange, Map) + * @see org.apache.qpid.server.binding.BindingFactory#removeBinding(String, AMQQueue, Exchange, java.util.Map) */ public void removeBinding(String queueName, String binding) throws JMException { diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java index 1341f77c72..4bd0e8d272 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java +++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/headers/HeadersParser.java @@ -126,11 +126,11 @@ public class HeadersParser { // DFAs for "all" matches have a "success" state, a "fail" state, and states for every subset of // matches which are possible, starting with the empty subset. For example if we have a binding - // { x-match="all" + // x-match="all" // a=1 // b=1 // c=1 - // d=1 } + // d=1 // Then we would have the following states // (1) Seen none of a, b, c, or d // (2) Seen a=1 ; none of b,c, or d diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java index 6556360a91..aac696ae2d 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java +++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicNormalizer.java @@ -36,6 +36,10 @@ public class TopicNormalizer private static final AMQShortString AMQP_STAR_TOKEN = new AMQShortString("*"); private static final AMQShortString AMQP_HASH_TOKEN = new AMQShortString("#"); + private TopicNormalizer() + { + } + public static AMQShortString normalize(AMQShortString routingKey) { if(routingKey == null) diff --git a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java index 54fc4b3634..89e84e8b0b 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java +++ b/java/broker/src/main/java/org/apache/qpid/server/exchange/topic/TopicParser.java @@ -458,193 +458,4 @@ public class TopicParser } - public static void main(String[] args) - { - - printMatches("#.b.*.*.*.*.*.h.#.j.*.*.*.*.*.*.q.#.r.*.*.*.*.*.*.*.*","a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"); - printMatches(new String[]{ - "#.a.#", - "#.b.#", - "#.c.#", - "#.d.#", - "#.e.#", - "#.f.#", - "#.g.#", - "#.h.#", - "#.i.#", - "#.j.#", - "#.k.#", - "#.l.#", - "#.m.#", - "#.n.#", - "#.o.#", - "#.p.#", - "#.q.#" - - }, "a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"); -/* - printMatches(new String[]{ - "#.a.#", - "#.b.#", - "#.c.#", - "#.d.#", - "#.e.#", - "#.f.#", - "#.g.#", - "#.h.#", - "#.i.#", - "#.j.#", - "#.k.#", - "#.l.#", - "#.m.#", - "#.n.#", - "#.o.#", - "#.p.#", - "#.q.#", - "#.r.#", - "#.s.#", - "#.t.#", - "#.u.#", - "#.v.#", - "#.w.#", - "#.x.#", - "#.y.#", - "#.z.#" - - - },"a.b"); - - printMatches("#.b.*.*.*.*.*.h.#.j.*.*.*.*.*.p.#.r.*.*.*.*.*","a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"); - printMatches("#.b.*.*.*.*.*.h.#.j.*.*.*.*.*.p.#.r.*.*.*.*.*.*.*.*","a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z"); - printMatches("a.#.b.#","a.b.b.b.b.b.b.b.c"); - -*/ - - printMatches("",""); - printMatches("a","a"); - printMatches("a",""); - printMatches("","a"); - printMatches("a.b","a.b"); - printMatches("a","a.b"); - printMatches("a.b","a"); - printMatches("*","a"); - printMatches("*.b","a.b"); - printMatches("*.*","a.b"); - printMatches("a.*","a.b"); - printMatches("a.*.#","a.b"); - printMatches("a.#.b","a.b"); - - printMatches("#.b","a"); - printMatches("#.b","a.b"); - printMatches("#.a.b","a.b"); - - - printMatches("#",""); - printMatches("#","a"); - printMatches("#","a.b"); - printMatches("#.#","a.b"); - printMatches("#.*","a.b"); - - printMatches("#.a.b","a.b"); - printMatches("a.b.#","a.b"); - printMatches("a.#","a.b"); - printMatches("#.*.#","a.b"); - printMatches("#.*.b.#","a.b"); - printMatches("#.a.*.#","a.b"); - printMatches("#.a.#.b.#","a.b"); - printMatches("#.*.#.*.#","a.b"); - printMatches("*.#.*.#","a.b"); - printMatches("#.*.#.*","a.b"); - - - printMatches(new String[]{"a.#.b.#","a.*.#.b.#"},"a.b.b.b.b.b.b.b.c"); - - - printMatches(new String[]{"a.b", "a.c"},"a.b"); - printMatches(new String[]{"a.#", "a.c", "#.b"},"a.b"); - printMatches(new String[]{"a.#", "a.c", "#.b", "#", "*.*"},"a.b"); - - printMatches(new String[]{"a.b.c.d.e.#", "a.b.c.d.#", "a.b.c.d.*", "a.b.c.#", "#.e", "a.*.c.d.e","#.c.*.#.*.*"},"a.b.c.d.e"); - printMatches(new String[]{"a.b.c.d.e.#", "a.b.c.d.#", "a.b.c.d.*", "a.b.c.#", "#.e", "a.*.c.d.e","#.c.*.#.*.*"},"a.b.c.d.f.g"); - - - - - } - - private static void printMatches(final String[] bindingKeys, final String routingKey) - { - TopicMatcherDFAState sm = null; - Map<TopicMatcherResult, String> resultMap = new HashMap<TopicMatcherResult, String>(); - - TopicParser parser = new TopicParser(); - - long start = System.currentTimeMillis(); - for(int i = 0; i < bindingKeys.length; i++) - { - System.out.println((System.currentTimeMillis() - start) + ":\t" + bindingKeys[i]); - TopicMatcherResult r = new TopicMatcherResult(){}; - resultMap.put(r, bindingKeys[i]); - AMQShortString bindingKeyShortString = new AMQShortString(bindingKeys[i]); - - System.err.println("====================================================="); - System.err.println("Adding binding key: " + bindingKeyShortString); - System.err.println("-----------------------------------------------------"); - - - if(i==0) - { - sm = parser.createStateMachine(bindingKeyShortString, r); - } - else - { - sm = sm.mergeStateMachines(parser.createStateMachine(bindingKeyShortString, r)); - } - System.err.println(sm.reachableStates()); - System.err.println("====================================================="); - try - { - System.in.read(); - } - catch (IOException e) - { - e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. - } - } - AMQShortString routingKeyShortString = new AMQShortString(routingKey); - - Collection<TopicMatcherResult> results = sm.parse(parser._dictionary, routingKeyShortString); - Collection<String> resultStrings = new ArrayList<String>(); - - for(TopicMatcherResult result : results) - { - resultStrings.add(resultMap.get(result)); - } - - final ArrayList<String> nonMatches = new ArrayList<String>(Arrays.asList(bindingKeys)); - nonMatches.removeAll(resultStrings); - System.out.println("\""+routingKeyShortString+"\" matched with " + resultStrings + " DID NOT MATCH with " + nonMatches); - - - } - - private static void printMatches(String bindingKey, String routingKey) - { - printMatches(new String[] { bindingKey }, routingKey); - } - - - private static boolean matches(String bindingKey, String routingKey) - { - AMQShortString bindingKeyShortString = new AMQShortString(bindingKey); - AMQShortString routingKeyShortString = new AMQShortString(routingKey); - TopicParser parser = new TopicParser(); - - final TopicMatcherResult result = new TopicMatcherResult(){}; - - TopicMatcherDFAState sm = parser.createStateMachine(bindingKeyShortString, result); - return !sm.parse(parser._dictionary,routingKeyShortString).isEmpty(); - - } - } diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java index 748b45d7cf..703f59dda6 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java +++ b/java/broker/src/main/java/org/apache/qpid/server/filter/ArithmeticExpression.java @@ -249,13 +249,13 @@ public abstract class ArithmeticExpression extends BinaryExpression public Object evaluate(Filterable message) { - Object lvalue = left.evaluate(message); + Object lvalue = getLeft().evaluate(message); if (lvalue == null) { return null; } - Object rvalue = right.evaluate(message); + Object rvalue = getRight().evaluate(message); if (rvalue == null) { return null; diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java index 024257bea9..355630bb51 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java +++ b/java/broker/src/main/java/org/apache/qpid/server/filter/BinaryExpression.java @@ -25,8 +25,8 @@ package org.apache.qpid.server.filter; */ public abstract class BinaryExpression implements Expression { - protected Expression left; - protected Expression right; + private final Expression left; + private final Expression right; public BinaryExpression(Expression left, Expression right) { @@ -87,20 +87,4 @@ public abstract class BinaryExpression implements Expression */ public abstract String getExpressionSymbol(); - /** - * @param expression - */ - public void setRight(Expression expression) - { - right = expression; - } - - /** - * @param expression - */ - public void setLeft(Expression expression) - { - left = expression; - } - } diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java index d0d58004ab..b04197121c 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java +++ b/java/broker/src/main/java/org/apache/qpid/server/filter/ComparisonExpression.java @@ -150,7 +150,6 @@ public abstract class ComparisonExpression extends BinaryExpression implements B { return Boolean.FALSE; - // throw new RuntimeException("LIKE can only operate on String identifiers. LIKE attemped on: '" + rv.getClass()); } return likePattern.matcher((String) rv).matches() ? Boolean.TRUE : Boolean.FALSE; @@ -388,13 +387,13 @@ public abstract class ComparisonExpression extends BinaryExpression implements B public Object evaluate(Filterable message) { - Comparable lv = (Comparable) left.evaluate(message); + Comparable lv = (Comparable) getLeft().evaluate(message); if (lv == null) { return null; } - Comparable rv = (Comparable) right.evaluate(message); + Comparable rv = (Comparable) getRight().evaluate(message); if (rv == null) { return null; @@ -564,8 +563,8 @@ public abstract class ComparisonExpression extends BinaryExpression implements B public Object evaluate(Filterable message) { - Object lv = left.evaluate(message); - Object rv = right.evaluate(message); + Object lv = getLeft().evaluate(message); + Object rv = getRight().evaluate(message); // Iff one of the values is null if ((lv == null) ^ (rv == null)) diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java b/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java index 80379134c9..45cd3cb57e 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java +++ b/java/broker/src/main/java/org/apache/qpid/server/filter/FilterManagerFactory.java @@ -34,6 +34,10 @@ public class FilterManagerFactory private final static Logger _logger = Logger.getLogger(FilterManagerFactory.class); + private FilterManagerFactory() + { + } + //fixme move to a common class so it can be refered to from client code. public static FilterManager createManager(FieldTable filters) throws AMQException diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java index fdba184da4..f867b4d4c5 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java +++ b/java/broker/src/main/java/org/apache/qpid/server/filter/LogicExpression.java @@ -66,14 +66,14 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea public Object evaluate(Filterable message) { - Boolean lv = (Boolean) left.evaluate(message); + Boolean lv = (Boolean) getLeft().evaluate(message); // Can we do an OR shortcut?? if ((lv != null) && lv.booleanValue()) { return Boolean.TRUE; } - Boolean rv = (Boolean) right.evaluate(message); + Boolean rv = (Boolean) getRight().evaluate(message); return (rv == null) ? null : rv; } @@ -94,7 +94,7 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea public Object evaluate(Filterable message) { - Boolean lv = (Boolean) left.evaluate(message); + Boolean lv = (Boolean) getLeft().evaluate(message); // Can we do an AND shortcut?? if (lv == null) @@ -107,7 +107,7 @@ public abstract class LogicExpression extends BinaryExpression implements Boolea return Boolean.FALSE; } - Boolean rv = (Boolean) right.evaluate(message); + Boolean rv = (Boolean) getRight().evaluate(message); return (rv == null) ? null : rv; } diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java index 11b06890f1..fdd651a046 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java +++ b/java/broker/src/main/java/org/apache/qpid/server/filter/UnaryExpression.java @@ -38,7 +38,7 @@ public abstract class UnaryExpression implements Expression { private static final BigDecimal BD_LONG_MIN_VALUE = BigDecimal.valueOf(Long.MIN_VALUE); - protected Expression right; + private Expression right; public static Expression createNegate(Expression left) { @@ -205,7 +205,7 @@ public abstract class UnaryExpression implements Expression public Object evaluate(Filterable message) { - Object rvalue = right.evaluate(message); + Object rvalue = getRight().evaluate(message); if (rvalue == null) { return null; @@ -240,7 +240,7 @@ public abstract class UnaryExpression implements Expression public Object evaluate(Filterable message) { - Object rvalue = right.evaluate(message); + Object rvalue = getRight().evaluate(message); if (rvalue == null) { return null; @@ -265,7 +265,7 @@ public abstract class UnaryExpression implements Expression public String toString() { StringBuffer answer = new StringBuffer(); - answer.append(right); + answer.append(getRight()); answer.append(" "); answer.append(getExpressionSymbol()); answer.append(" ( "); @@ -310,7 +310,7 @@ public abstract class UnaryExpression implements Expression public Object evaluate(Filterable message) { - Boolean lvalue = (Boolean) right.evaluate(message); + Boolean lvalue = (Boolean) getRight().evaluate(message); if (lvalue == null) { return null; @@ -334,7 +334,7 @@ public abstract class UnaryExpression implements Expression public Object evaluate(Filterable message) { - Object rvalue = right.evaluate(message); + Object rvalue = getRight().evaluate(message); if (rvalue == null) { return null; @@ -350,7 +350,7 @@ public abstract class UnaryExpression implements Expression public String toString() { - return right.toString(); + return getRight().toString(); } public String getExpressionSymbol() diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java index 1e638ae6c2..ead385d1ba 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java +++ b/java/broker/src/main/java/org/apache/qpid/server/filter/XPathExpression.java @@ -22,7 +22,6 @@ package org.apache.qpid.server.filter; import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; import org.apache.qpid.server.queue.Filterable; import java.lang.reflect.Constructor; @@ -94,19 +93,7 @@ public final class XPathExpression implements BooleanExpression { } public Object evaluate(Filterable message) { -// try { -//FIXME this is flow to disk work -// if( message.isDropped() ) -// return null; return evaluator.evaluate(message) ? Boolean.TRUE : Boolean.FALSE; -// } catch (IOException e) { -// -// JMSException exception = new JMSException(e.getMessage()); -// exception.initCause(e); -// throw exception; -// -// } - } public String toString() { @@ -116,7 +103,6 @@ public final class XPathExpression implements BooleanExpression { /** * @param message * @return true if the expression evaluates to Boolean.TRUE. - * @throws AMQException */ public boolean matches(Filterable message) { diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java index ae22f17413..c16684ce64 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java +++ b/java/broker/src/main/java/org/apache/qpid/server/filter/XQueryExpression.java @@ -17,7 +17,6 @@ */ package org.apache.qpid.server.filter; -import org.apache.qpid.AMQException; import org.apache.qpid.server.queue.Filterable; // @@ -46,7 +45,6 @@ public final class XQueryExpression implements BooleanExpression { /** * @param message * @return true if the expression evaluates to Boolean.TRUE. - * @throws AMQException */ public boolean matches(Filterable message) { diff --git a/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java b/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java index ebab3a5386..ab85cb1b55 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java +++ b/java/broker/src/main/java/org/apache/qpid/server/filter/XalanXPathEvaluator.java @@ -45,18 +45,6 @@ public class XalanXPathEvaluator implements XPathExpression.XPathEvaluator { { // TODO - we would have to check the content type and then evaluate the content // here... is this really a feature we wish to implement? - RobG - /* - - if( m instanceof TextMessage ) { - String text = ((TextMessage)m).getText(); - return evaluate(text); - } else if ( m instanceof BytesMessage ) { - BytesMessage bm = (BytesMessage) m; - byte data[] = new byte[(int) bm.getBodyLength()]; - bm.readBytes(data); - return evaluate(data); - } - */ return false; } diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java index c6771177ac..ce10c40244 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java +++ b/java/broker/src/main/java/org/apache/qpid/server/flow/CreditCreditManager.java @@ -67,9 +67,6 @@ public class CreditCreditManager extends AbstractFlowCreditManager implements Fl public synchronized void restoreCredit(final long messageCredit, final long bytesCredit) { - /*_bytesCredit = 0l; - _messageCredit = 0l; - setSuspended(true);*/ } @@ -138,7 +135,6 @@ public class CreditCreditManager extends AbstractFlowCreditManager implements Fl } else { - //setSuspended(true); return false; } } @@ -158,7 +154,6 @@ public class CreditCreditManager extends AbstractFlowCreditManager implements Fl } else { - //setSuspended(true); return false; } diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java index a193f8fae4..fc2d4bfb53 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java +++ b/java/broker/src/main/java/org/apache/qpid/server/flow/Pre0_10CreditManager.java @@ -155,7 +155,6 @@ public class Pre0_10CreditManager extends AbstractFlowCreditManager implements F } else { - //setSuspended(true); return false; } } @@ -183,7 +182,6 @@ public class Pre0_10CreditManager extends AbstractFlowCreditManager implements F } else { - //setSuspended(true); return false; } } diff --git a/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java b/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java index a0c2e9f977..2215c7bb3d 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java +++ b/java/broker/src/main/java/org/apache/qpid/server/flow/WindowCreditManager.java @@ -144,7 +144,6 @@ public class WindowCreditManager extends AbstractFlowCreditManager implements Fl } else { - //setSuspended(true); return false; } } @@ -164,7 +163,6 @@ public class WindowCreditManager extends AbstractFlowCreditManager implements Fl } else { - //setSuspended(true); return false; } diff --git a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java index 321903b920..db312cc8bc 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java +++ b/java/broker/src/main/java/org/apache/qpid/server/handler/QueueDeclareHandler.java @@ -57,9 +57,7 @@ public class QueueDeclareHandler implements StateAwareMethodListener<QueueDeclar return _instance; } - public boolean autoRegister = ApplicationRegistry.getInstance().getConfiguration().getQueueAutoRegister(); - - private final AtomicInteger _counter = new AtomicInteger(); + private boolean autoRegister = ApplicationRegistry.getInstance().getConfiguration().getQueueAutoRegister(); public void methodReceived(AMQStateManager stateManager, QueueDeclareBody body, int channelId) throws AMQException { diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java index e0bf180cc4..e8c6c9c323 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java +++ b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/AbstractActor.java @@ -27,9 +27,9 @@ import org.apache.qpid.server.logging.RootMessageLogger; public abstract class AbstractActor implements LogActor { - public final String _msgPrefix = System.getProperty("qpid.logging.prefix",""); + private final String _msgPrefix = System.getProperty("qpid.logging.prefix",""); - protected RootMessageLogger _rootLogger; + private RootMessageLogger _rootLogger; public AbstractActor(RootMessageLogger rootLogger) { diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java index 2ebbfeb734..feacf35d41 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java +++ b/java/broker/src/main/java/org/apache/qpid/server/logging/actors/CurrentActor.java @@ -68,6 +68,10 @@ public class CurrentActor private static LogActor _defaultActor; + private CurrentActor() + { + } + /** * Set a new {@link LogActor} to be the Current Actor * <p/> diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java index 885b039e18..859d7e2a27 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java +++ b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/ChannelLogSubject.java @@ -36,8 +36,7 @@ public class ChannelLogSubject extends AbstractLogSubject /** * LOG FORMAT used by the AMQPConnectorActor follows - * ChannelLogSubject.CHANNEL_FORMAT : - * con:{0}({1}@{2}/{3})/ch:{4} + * ChannelLogSubject.CHANNEL_FORMAT : con:{0}({1}@{2}/{3})/ch:{4}. * * Uses a MessageFormat call to insert the required values according to * these indices: @@ -60,8 +59,7 @@ public class ChannelLogSubject extends AbstractLogSubject { /** * LOG FORMAT used by the AMQPConnectorActor follows - * ChannelLogSubject.CHANNEL_FORMAT : - * con:{0}({1}@{2}/{3})/ch:{4} + * ChannelLogSubject.CHANNEL_FORMAT : con:{0}({1}@{2}/{3})/ch:{4}. * * Uses a MessageFormat call to insert the required values according to * these indices: diff --git a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java index ff2bb90140..28c4f0d52a 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java +++ b/java/broker/src/main/java/org/apache/qpid/server/logging/subjects/LogSubjectFormat.java @@ -32,7 +32,10 @@ package org.apache.qpid.server.logging.subjects; public class LogSubjectFormat { - + private LogSubjectFormat() + { + } + /** * LOG FORMAT for the Subscription Log Subject * 0 - Subscription ID diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java index 3be28036aa..89b74f939d 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java +++ b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanIntrospector.java @@ -50,6 +50,10 @@ class MBeanIntrospector { private static final String _defaultConstructorDescription = "MBean constructor"; private static final String _defaultMbeanDescription = "Management interface of the MBean"; + private MBeanIntrospector() + { + } + /** * Introspects the management interface class for MBean attributes. * @param interfaceClass @@ -347,7 +351,6 @@ class MBeanIntrospector { for (Constructor cons : implClass.getConstructors()) { MBeanConstructorInfo constructorInfo = getMBeanConstructorInfo(cons); - //MBeanConstructorInfo constructorInfo = new MBeanConstructorInfo("desc", cons); if (constructorInfo != null) { constructors.add(constructorInfo); @@ -375,9 +378,6 @@ class MBeanIntrospector { } } - //MBeanParameterInfo[] paramsInfo = getParametersInfo(cons.getParameterAnnotations(), - // cons.getParameterTypes()); - return new MBeanConstructorInfo(cons.getName(), desc, null); } diff --git a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java index d85c802fda..2aeef1c2a4 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java +++ b/java/broker/src/main/java/org/apache/qpid/server/management/MBeanInvocationHandlerImpl.java @@ -339,7 +339,7 @@ public class MBeanInvocationHandlerImpl implements InvocationHandler, Notificati // Normally JMXManagedObjectRegistry provides a Map as handback data containing a map // between connection id and username. String user = null; - if (handback != null && handback instanceof Map) + if (handback instanceof Map) { final Map<String, String> connectionIdUsernameMap = (Map<String, String>) handback; user = connectionIdUsernameMap.get(connectionId); diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java b/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java index c6f8cac779..72d14456ed 100755 --- a/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java +++ b/java/broker/src/main/java/org/apache/qpid/server/output/HeaderPropertiesConverter.java @@ -39,6 +39,9 @@ import java.util.Map; public class HeaderPropertiesConverter { + private HeaderPropertiesConverter() + { + } public static BasicContentHeaderProperties convert(MessageTransferMessage messageTransferMessage, VirtualHost vhost) { diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java index d11d03ea3d..5d1ae48535 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java +++ b/java/broker/src/main/java/org/apache/qpid/server/output/ProtocolOutputConverterRegistry.java @@ -47,6 +47,10 @@ public class ProtocolOutputConverterRegistry register(ProtocolVersion.v0_91, org.apache.qpid.server.output.amqp0_9_1.ProtocolOutputConverterImpl.getInstanceFactory());
}
+ private ProtocolOutputConverterRegistry()
+ {
+ }
+
private static void register(ProtocolVersion version, Factory converter)
{
diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java index b2728be856..f90afa0be9 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java +++ b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_8/ProtocolOutputConverterImpl.java @@ -240,7 +240,7 @@ public class ProtocolOutputConverterImpl implements ProtocolOutputConverter final AMQBody returnBlock = new AMQBody() { - public AMQBody _underlyingBody; + private AMQBody _underlyingBody; public AMQBody createAMQBody() { diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java index 054d8b98e8..8bee368b80 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java +++ b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9/ProtocolOutputConverterImpl.java @@ -237,7 +237,7 @@ public class ProtocolOutputConverterImpl implements ProtocolOutputConverter final AMQBody returnBlock = new AMQBody() { - public AMQBody _underlyingBody; + private AMQBody _underlyingBody; public AMQBody createAMQBody() { diff --git a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java index cf097fa923..8d49481c25 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java +++ b/java/broker/src/main/java/org/apache/qpid/server/output/amqp0_9_1/ProtocolOutputConverterImpl.java @@ -244,7 +244,7 @@ public class ProtocolOutputConverterImpl implements ProtocolOutputConverter final AMQBody returnBlock = new AMQBody() { - public AMQBody _underlyingBody; + private AMQBody _underlyingBody; public AMQBody createAMQBody() { diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java index 251c3dd0cd..4908121f45 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java +++ b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolEngine.java @@ -119,7 +119,7 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr private Object _lastSent; - protected volatile boolean _closed; + private volatile boolean _closed; // maximum number of channels this session should have private long _maxNoOfChannels = ApplicationRegistry.getInstance().getConfiguration().getMaxChannelCount(); @@ -721,7 +721,7 @@ public class AMQProtocolEngine implements ServerProtocolEngine, Managable, AMQPr // However, due to the poor exception handling on the client. The client-user will be notified of the // InvalidArgument and if they then decide to close the session/connection then the there will be time // for that to occur i.e. a new close method be sent before the exeption handling can mark the session closed. - //removeChannel(channelId); + _closingChannelsList.remove(channelId); } diff --git a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java index 2f4becc129..105aa1f260 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java +++ b/java/broker/src/main/java/org/apache/qpid/server/protocol/AMQProtocolSessionMBean.java @@ -22,7 +22,7 @@ * * Copyright (c) 2006 The Apache Software Foundation * - * Licensed under the Apache License, Version 2.0 (the "License"); + * 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 * diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java index b51c41f2a8..f6bf6626a0 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java +++ b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQPriorityQueue.java @@ -40,6 +40,6 @@ public class AMQPriorityQueue extends OutOfOrderQueue public int getPriorities() { - return ((PriorityQueueList) _entries).getPriorities(); + return ((PriorityQueueList) getEntries()).getPriorities(); } } diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java index d3b1c18ef3..aca5891d2e 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java +++ b/java/broker/src/main/java/org/apache/qpid/server/queue/AMQQueueFactory.java @@ -49,6 +49,10 @@ public class AMQQueueFactory public static final String X_QPID_MAXIMUM_DELIVERY_COUNT = "x-qpid-maximum-delivery-count"; public static final String DEFAULT_DLQ_NAME_SUFFIX = "_DLQ"; + private AMQQueueFactory() + { + } + private abstract static class QueueProperty { diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java index b5293f51be..2c645cc555 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java +++ b/java/broker/src/main/java/org/apache/qpid/server/queue/ConflationQueue.java @@ -41,7 +41,7 @@ public class ConflationQueue extends SimpleAMQQueue public String getConflationKey() { - return ((ConflationQueueList) _entries).getConflationKey(); + return ((ConflationQueueList) getEntries()).getConflationKey(); } } diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/OutOfOrderQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/OutOfOrderQueue.java index cb34f69ff8..53121fc031 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/OutOfOrderQueue.java +++ b/java/broker/src/main/java/org/apache/qpid/server/queue/OutOfOrderQueue.java @@ -20,7 +20,7 @@ public abstract class OutOfOrderQueue extends SimpleAMQQueue protected void checkSubscriptionsNotAheadOfDelivery(final QueueEntry entry) { // check that all subscriptions are not in advance of the entry - SubscriptionList.SubscriptionNodeIterator subIter = _subscriptionList.iterator(); + SubscriptionList.SubscriptionNodeIterator subIter = getSubscriptionList().iterator(); while(subIter.advance() && !entry.isAcquired()) { final Subscription subscription = subIter.getNode().getSubscription(); diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java index a6518e857f..c4df3dd092 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java +++ b/java/broker/src/main/java/org/apache/qpid/server/queue/SimpleAMQQueue.java @@ -100,13 +100,10 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes private Exchange _alternateExchange; - /** Used to track bindings to exchanges so that on deletion they can easily be cancelled. */ - - - protected final QueueEntryList _entries; + private final QueueEntryList _entries; - protected final SubscriptionList _subscriptionList = new SubscriptionList(); + private final SubscriptionList _subscriptionList = new SubscriptionList(); private volatile Subscription _exclusiveSubscriber; @@ -138,19 +135,19 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes private final AtomicInteger _bindingCountHigh = new AtomicInteger(); /** max allowed size(KB) of a single message */ - public long _maximumMessageSize = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageSize(); + private long _maximumMessageSize = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageSize(); /** max allowed number of messages on a queue. */ - public long _maximumMessageCount = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageCount(); + private long _maximumMessageCount = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageCount(); /** max queue depth for the queue */ - public long _maximumQueueDepth = ApplicationRegistry.getInstance().getConfiguration().getMaximumQueueDepth(); + private long _maximumQueueDepth = ApplicationRegistry.getInstance().getConfiguration().getMaximumQueueDepth(); /** maximum message age before alerts occur */ - public long _maximumMessageAge = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageAge(); + private long _maximumMessageAge = ApplicationRegistry.getInstance().getConfiguration().getMaximumMessageAge(); /** the minimum interval between sending out consecutive alerts of the same type */ - public long _minimumAlertRepeatGap = ApplicationRegistry.getInstance().getConfiguration().getMinimumAlertRepeatGap(); + private long _minimumAlertRepeatGap = ApplicationRegistry.getInstance().getConfiguration().getMinimumAlertRepeatGap(); private long _capacity = ApplicationRegistry.getInstance().getConfiguration().getCapacity(); @@ -1075,6 +1072,17 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes return _stateChangeCount.get(); } + /** Used to track bindings to exchanges so that on deletion they can easily be cancelled. */ + protected QueueEntryList getEntries() + { + return _entries; + } + + protected SubscriptionList getSubscriptionList() + { + return _subscriptionList; + } + public static interface QueueEntryFilter { @@ -1676,7 +1684,6 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes public void deliverAsync(Subscription sub) { - //_stateChangeCount.incrementAndGet(); if(_exclusiveSubscriber == null) { deliverAsync(); @@ -2215,8 +2222,7 @@ public class SimpleAMQQueue implements AMQQueue, Subscription.StateListener, Mes public boolean equals(Object o) { - return o != null - && o instanceof SimpleAMQQueue.QueueEntryListener + return o instanceof SimpleAMQQueue.QueueEntryListener && _sub == ((QueueEntryListener) o)._sub; } diff --git a/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueueEntryList.java b/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueueEntryList.java index 41a87a4c31..7f742d455d 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueueEntryList.java +++ b/java/broker/src/main/java/org/apache/qpid/server/queue/SortedQueueEntryList.java @@ -362,7 +362,7 @@ public class SortedQueueEntryList implements QueueEntryList<SortedQueueEntryImpl if(chosenChild != null) { - // we have one child (x), we can move it up to replace x; + // we have one child (x), we can move it up to replace x chosenChild.setParent(entry.getParent()); if(chosenChild.getParent() == null) { diff --git a/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java b/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java index f6c766d73f..99a80ddff8 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java +++ b/java/broker/src/main/java/org/apache/qpid/server/registry/ApplicationRegistry.java @@ -429,57 +429,71 @@ public abstract class ApplicationRegistry implements IApplicationRegistry { _reportingTimer = new Timer("Statistics-Reporting", true); - class StatisticsReportingTask extends TimerTask + + + _reportingTimer.scheduleAtFixedRate(new StatisticsReportingTask(broker, virtualhost, reset), + report / 2, + report); + } + } + + private class StatisticsReportingTask extends TimerTask + { + private final int DELIVERED = 0; + private final int RECEIVED = 1; + + private boolean _broker; + private boolean _virtualhost; + private boolean _reset; + + + public StatisticsReportingTask(boolean broker, boolean virtualhost, boolean reset) + { + _broker = broker; + _virtualhost = virtualhost; + _reset = reset; + } + + public void run() + { + CurrentActor.set(new AbstractActor(ApplicationRegistry.getInstance().getRootMessageLogger()) { + public String getLogMessage() + { + return "[" + Thread.currentThread().getName() + "] "; + } + }); + + if (_broker) + { + CurrentActor.get().message(BrokerMessages.STATS_DATA(DELIVERED, _dataDelivered.getPeak() / 1024.0, _dataDelivered.getTotal())); + CurrentActor.get().message(BrokerMessages.STATS_MSGS(DELIVERED, _messagesDelivered.getPeak(), _messagesDelivered.getTotal())); + CurrentActor.get().message(BrokerMessages.STATS_DATA(RECEIVED, _dataReceived.getPeak() / 1024.0, _dataReceived.getTotal())); + CurrentActor.get().message(BrokerMessages.STATS_MSGS(RECEIVED, _messagesReceived.getPeak(), _messagesReceived.getTotal())); + } + + if (_virtualhost) { - private final int DELIVERED = 0; - private final int RECEIVED = 1; - - public void run() + for (VirtualHost vhost : getVirtualHostRegistry().getVirtualHosts()) { - CurrentActor.set(new AbstractActor(ApplicationRegistry.getInstance().getRootMessageLogger()) { - public String getLogMessage() - { - return "[" + Thread.currentThread().getName() + "] "; - } - }); - - if (broker) - { - CurrentActor.get().message(BrokerMessages.STATS_DATA(DELIVERED, _dataDelivered.getPeak() / 1024.0, _dataDelivered.getTotal())); - CurrentActor.get().message(BrokerMessages.STATS_MSGS(DELIVERED, _messagesDelivered.getPeak(), _messagesDelivered.getTotal())); - CurrentActor.get().message(BrokerMessages.STATS_DATA(RECEIVED, _dataReceived.getPeak() / 1024.0, _dataReceived.getTotal())); - CurrentActor.get().message(BrokerMessages.STATS_MSGS(RECEIVED, _messagesReceived.getPeak(), _messagesReceived.getTotal())); - } - - if (virtualhost) - { - for (VirtualHost vhost : getVirtualHostRegistry().getVirtualHosts()) - { - String name = vhost.getName(); - StatisticsCounter dataDelivered = vhost.getDataDeliveryStatistics(); - StatisticsCounter messagesDelivered = vhost.getMessageDeliveryStatistics(); - StatisticsCounter dataReceived = vhost.getDataReceiptStatistics(); - StatisticsCounter messagesReceived = vhost.getMessageReceiptStatistics(); - - CurrentActor.get().message(VirtualHostMessages.STATS_DATA(name, DELIVERED, dataDelivered.getPeak() / 1024.0, dataDelivered.getTotal())); - CurrentActor.get().message(VirtualHostMessages.STATS_MSGS(name, DELIVERED, messagesDelivered.getPeak(), messagesDelivered.getTotal())); - CurrentActor.get().message(VirtualHostMessages.STATS_DATA(name, RECEIVED, dataReceived.getPeak() / 1024.0, dataReceived.getTotal())); - CurrentActor.get().message(VirtualHostMessages.STATS_MSGS(name, RECEIVED, messagesReceived.getPeak(), messagesReceived.getTotal())); - } - } - - if (reset) - { - resetStatistics(); - } - - CurrentActor.remove(); + String name = vhost.getName(); + StatisticsCounter dataDelivered = vhost.getDataDeliveryStatistics(); + StatisticsCounter messagesDelivered = vhost.getMessageDeliveryStatistics(); + StatisticsCounter dataReceived = vhost.getDataReceiptStatistics(); + StatisticsCounter messagesReceived = vhost.getMessageReceiptStatistics(); + + CurrentActor.get().message(VirtualHostMessages.STATS_DATA(name, DELIVERED, dataDelivered.getPeak() / 1024.0, dataDelivered.getTotal())); + CurrentActor.get().message(VirtualHostMessages.STATS_MSGS(name, DELIVERED, messagesDelivered.getPeak(), messagesDelivered.getTotal())); + CurrentActor.get().message(VirtualHostMessages.STATS_DATA(name, RECEIVED, dataReceived.getPeak() / 1024.0, dataReceived.getTotal())); + CurrentActor.get().message(VirtualHostMessages.STATS_MSGS(name, RECEIVED, messagesReceived.getPeak(), messagesReceived.getTotal())); } } - _reportingTimer.scheduleAtFixedRate(new StatisticsReportingTask(), - report / 2, - report); + if (_reset) + { + resetStatistics(); + } + + CurrentActor.remove(); } } diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java index 68b1fa6500..236931e8cd 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/AbstractProxyPlugin.java @@ -20,8 +20,6 @@ */ package org.apache.qpid.server.security; -import org.apache.commons.configuration.Configuration; - import org.apache.qpid.server.security.access.ObjectProperties; import org.apache.qpid.server.security.access.ObjectType; import org.apache.qpid.server.security.access.Operation; @@ -29,8 +27,6 @@ import org.apache.qpid.server.security.access.Operation; /** * This {@link SecurityPlugin} proxies the authorise calls to a serries of methods, one per {@link Operation}. * - * Plugins that extend this class should override the relevant authorise method and implement their own - * {@link #setConfiguration(Configuration)} method. */ public abstract class AbstractProxyPlugin extends AbstractPlugin { diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/AuthorizationHolder.java b/java/broker/src/main/java/org/apache/qpid/server/security/AuthorizationHolder.java index 44bf60ea15..8f3bdf7738 100755 --- a/java/broker/src/main/java/org/apache/qpid/server/security/AuthorizationHolder.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/AuthorizationHolder.java @@ -20,9 +20,6 @@ */ package org.apache.qpid.server.security; -import org.apache.qpid.server.security.auth.sasl.GroupPrincipal; -import org.apache.qpid.server.security.auth.sasl.UsernamePrincipal; - import javax.security.auth.Subject; import java.security.Principal; @@ -34,8 +31,8 @@ public interface AuthorizationHolder { /** * Returns the {@link Subject} of the authorized user. This is guaranteed to - * contain at least one {@link UsernamePrincipal}, representing the the identity - * used when the user logged on to the application, and zero or more {@link GroupPrincipal} + * contain at least one {@link org.apache.qpid.server.security.auth.sasl.UsernamePrincipal}, representing the the identity + * used when the user logged on to the application, and zero or more {@link org.apache.qpid.server.security.auth.sasl.GroupPrincipal} * representing the group(s) to which the user belongs. * * @return the Subject diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java index 18c975cd04..436660cfaf 100755 --- a/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/SecurityManager.java @@ -45,7 +45,6 @@ import static org.apache.qpid.server.security.access.Operation.UNBIND; import javax.security.auth.Subject; import java.net.SocketAddress; -import java.security.Principal; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -66,7 +65,7 @@ public class SecurityManager { private static final Logger _logger = Logger.getLogger(SecurityManager.class); - /** Container for the {@link Principal} that is using to this thread. */ + /** Container for the {@link java.security.Principal} that is using to this thread. */ private static final ThreadLocal<Subject> _subject = new ThreadLocal<Subject>(); private static final ThreadLocal<Boolean> _accessChecksDisabled = new ThreadLocal<Boolean>() { @@ -106,7 +105,7 @@ public class SecurityManager public void validateConfiguration() throws ConfigurationException { - if (_configuration.isEmpty()) + if (getConfig().isEmpty()) { throw new ConfigurationException("security section is incomplete, no elements found."); } diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java index 006a7813e0..8260e8d91e 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/AllowAll.java @@ -55,10 +55,6 @@ public class AllowAll extends BasicPlugin public void validateConfiguration() throws ConfigurationException { -// if (!_configuration.isEmpty()) -// { -// throw new ConfigurationException("allow-all section takes no elements."); -// } } } diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java index 0c3d5b6f9a..4df135a4ca 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/BasicPlugin.java @@ -22,13 +22,12 @@ package org.apache.qpid.server.security.access.plugins; import org.apache.qpid.server.security.AbstractPlugin; import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.SecurityPlugin; import org.apache.qpid.server.security.access.ObjectProperties; import org.apache.qpid.server.security.access.ObjectType; import org.apache.qpid.server.security.access.Operation; /** - * This {@link SecurityPlugin} simply abstains from all authorisation requests and ignores configuration. + * This {@link org.apache.qpid.server.security.SecurityPlugin} simply abstains from all authorisation requests and ignores configuration. */ public abstract class BasicPlugin extends AbstractPlugin { diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java index e9d0170968..6d28699832 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/access/plugins/DenyAll.java @@ -55,7 +55,7 @@ public class DenyAll extends BasicPlugin public void validateConfiguration() throws ConfigurationException { - if (!_configuration.isEmpty()) + if (!getConfig().isEmpty()) { throw new ConfigurationException("deny-all section takes no elements."); } diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java index 8c2d60a660..949c0f2b89 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/auth/AuthenticationResult.java @@ -53,8 +53,8 @@ public class AuthenticationResult ERROR } - public final AuthenticationStatus _status; - public final byte[] _challenge; + private final AuthenticationStatus _status; + private final byte[] _challenge; private final Exception _cause; private final Subject _subject; diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java index fcd64f3a23..52ddc092b5 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/auth/database/Base64MD5PasswordFilePrincipalDatabase.java @@ -86,15 +86,6 @@ public class Base64MD5PasswordFilePrincipalDatabase implements PrincipalDatabase _saslServers.put(cramHex.getMechanismName(), cramHex); //fixme The PDs should setup a PD Mangement MBean -// try -// { -// _mbean = new AMQUserManagementMBean(); -// _mbean.setPrincipalDatabase(this); -// } -// catch (JMException e) -// { -// _logger.warn("User management disabled as unable to create MBean:" + e); -// } } public void setPasswordFile(String passwordFile) throws IOException diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java index e434fa62b1..4ffa5a4bc2 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/AuthenticationManager.java @@ -24,7 +24,6 @@ import org.apache.qpid.common.Closeable; import org.apache.qpid.server.plugins.Plugin; import org.apache.qpid.server.security.auth.AuthenticationResult; -import javax.security.auth.Subject; import javax.security.sasl.SaslException; import javax.security.sasl.SaslServer; @@ -33,7 +32,7 @@ import javax.security.sasl.SaslServer; * the authenticity of a user's credentials. * * If the authentication is successful, the manager is responsible for producing a populated - * {@link Subject} containing the user's identity and zero or more principals representing + * {@link javax.security.auth.Subject} containing the user's identity and zero or more principals representing * groups to which the user belongs. * <p> * The {@link #initialise()} method is responsible for registering SASL mechanisms required by diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java index 739fc414c6..3fa0de2af0 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/auth/manager/PrincipalDatabaseAuthenticationManager.java @@ -95,9 +95,9 @@ public class PrincipalDatabaseAuthenticationManager implements AuthenticationMan */ private final Map<String, Map<String, ?>> _serverCreationProperties = new HashMap<String, Map<String, ?>>(); - protected PrincipalDatabase _principalDatabase = null; + private PrincipalDatabase _principalDatabase = null; - protected AMQUserManagementMBean _mbean = null; + private AMQUserManagementMBean _mbean = null; public static final AuthenticationManagerPluginFactory<PrincipalDatabaseAuthenticationManager> FACTORY = new AuthenticationManagerPluginFactory<PrincipalDatabaseAuthenticationManager>() { @@ -160,13 +160,13 @@ public class PrincipalDatabaseAuthenticationManager implements AuthenticationMan public String getPrincipalDatabaseClass() { - return _configuration.getString("principal-database.class"); + return getConfig().getString("principal-database.class"); } public Map<String,String> getPdClassAttributeMap() throws ConfigurationException { - final List<String> argumentNames = _configuration.getList("principal-database.attributes.attribute.name"); - final List<String> argumentValues = _configuration.getList("principal-database.attributes.attribute.value"); + final List<String> argumentNames = getConfig().getList("principal-database.attributes.attribute.name"); + final List<String> argumentValues = getConfig().getList("principal-database.attributes.attribute.value"); final Map<String,String> attributes = new HashMap<String,String>(argumentNames.size()); for (int i = 0; i < argumentNames.size(); i++) diff --git a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java index e77bf7c24f..c1f306dce9 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java +++ b/java/broker/src/main/java/org/apache/qpid/server/security/auth/sasl/plain/PlainSaslServer.java @@ -65,7 +65,6 @@ public class PlainSaslServer implements SaslServer } // we do not currently support authcid in any meaningful way - // String authcid = new String(response, 0, authzidNullPosition, "utf8"); String authzid = new String(response, authzidNullPosition + 1, authcidNullPosition - authzidNullPosition - 1, "utf8"); // TODO: should not get pwd as a String but as a char array... diff --git a/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java b/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java index 8d662863ca..f97b77a4fe 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java +++ b/java/broker/src/main/java/org/apache/qpid/server/state/AMQStateManager.java @@ -50,16 +50,6 @@ public class AMQStateManager implements AMQMethodListener /** The current state */ private AMQState _currentState; - /** - * Maps from an AMQState instance to a Map from Class to StateTransitionHandler. The class must be a subclass of - * AMQFrame. - */ -/* private final EnumMap<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>> _state2HandlersMap = - new EnumMap<AMQState, Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>>( - AMQState.class); - */ - - private CopyOnWriteArraySet<StateListener> _stateListeners = new CopyOnWriteArraySet<StateListener>(); public AMQStateManager(VirtualHostRegistry virtualHostRegistry, AMQProtocolSession protocolSession) @@ -71,64 +61,6 @@ public class AMQStateManager implements AMQMethodListener } - /* - protected void registerListeners() - { - Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>> frame2handlerMap; - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_STARTED, frame2handlerMap); - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_AUTH, frame2handlerMap); - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_TUNED, frame2handlerMap); - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - frame2handlerMap.put(ConnectionOpenBody.class, ConnectionOpenMethodHandler.getInstance()); - _state2HandlersMap.put(AMQState.CONNECTION_NOT_OPENED, frame2handlerMap); - - // - // ConnectionOpen handlers - // - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - ChannelOpenHandler.getInstance(); - ChannelCloseHandler.getInstance(); - ChannelCloseOkHandler.getInstance(); - ConnectionCloseMethodHandler.getInstance(); - ConnectionCloseOkMethodHandler.getInstance(); - ConnectionTuneOkMethodHandler.getInstance(); - ConnectionSecureOkMethodHandler.getInstance(); - ConnectionStartOkMethodHandler.getInstance(); - ExchangeDeclareHandler.getInstance(); - ExchangeDeleteHandler.getInstance(); - ExchangeBoundHandler.getInstance(); - BasicAckMethodHandler.getInstance(); - BasicRecoverMethodHandler.getInstance(); - BasicConsumeMethodHandler.getInstance(); - BasicGetMethodHandler.getInstance(); - BasicCancelMethodHandler.getInstance(); - BasicPublishMethodHandler.getInstance(); - BasicQosHandler.getInstance(); - QueueBindHandler.getInstance(); - QueueDeclareHandler.getInstance(); - QueueDeleteHandler.getInstance(); - QueuePurgeHandler.getInstance(); - ChannelFlowHandler.getInstance(); - TxSelectHandler.getInstance(); - TxCommitHandler.getInstance(); - TxRollbackHandler.getInstance(); - BasicRejectMethodHandler.getInstance(); - - _state2HandlersMap.put(AMQState.CONNECTION_OPEN, frame2handlerMap); - - frame2handlerMap = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>(); - - _state2HandlersMap.put(AMQState.CONNECTION_CLOSING, frame2handlerMap); - - } */ - public AMQState getCurrentState() { return _currentState; @@ -189,30 +121,6 @@ public class AMQStateManager implements AMQMethodListener } } -/* - protected <B extends AMQMethodBody> StateAwareMethodListener<B> findStateTransitionHandler(AMQState currentState, - B frame) - // throws IllegalStateTransitionException - { - final Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>> classToHandlerMap = - _state2HandlersMap.get(currentState); - - final StateAwareMethodListener<B> handler = - (classToHandlerMap == null) ? null : (StateAwareMethodListener<B>) classToHandlerMap.get(frame.getClass()); - - if (handler == null) - { - _logger.debug("No state transition handler defined for receiving frame " + frame); - - return null; - } - else - { - return handler; - } - } -*/ - public void addStateListener(StateListener listener) { _logger.debug("Adding state listener"); diff --git a/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java b/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java index 465f8ecc7c..2877e25645 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java +++ b/java/broker/src/main/java/org/apache/qpid/server/store/DerbyMessageStore.java @@ -1111,11 +1111,7 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor insertStmt.setString(3, routingKey == null ? null : routingKey.toString()); if(args != null) { - /* This would be the Java 6 way of setting a Blob - Blob blobArgs = conn.createBlob(); - blobArgs.setBytes(0, args.getDataAsBytes()); - stmt.setBlob(4, blobArgs); - */ + // TODO - In Java 6 we could use create/set Blob byte[] bytes = args.getDataAsBytes(); ByteArrayInputStream bis = new ByteArrayInputStream(bytes); insertStmt.setBinaryStream(4, bis, bytes.length); @@ -1713,7 +1709,7 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor if (_logger.isDebugEnabled()) { - _logger.debug("Dequeuing message " + messageId + " on queue " + name );//+ "[Connection" + conn + "]"); + _logger.debug("Dequeuing message " + messageId + " on queue " + name ); } } finally @@ -2032,11 +2028,8 @@ public class DerbyMessageStore implements MessageStore, DurableConfigurationStor stmt.setInt(3, offset+chunkData.length); - /* this would be the Java 6 way of doing things - Blob dataAsBlob = conn.createBlob(); - dataAsBlob.setBytes(1L, chunkData); - stmt.setBlob(3, dataAsBlob); - */ + // TODO in Java 6 we could just use blobs + ByteArrayInputStream bis = new ByteArrayInputStream(chunkData); stmt.setBinaryStream(4, bis, chunkData.length); stmt.executeUpdate(); diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java index 95b0a40497..1e37675c98 100755 --- a/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java +++ b/java/broker/src/main/java/org/apache/qpid/server/subscription/ImplicitAcceptDispositionChangeListener.java @@ -72,8 +72,6 @@ class ImplicitAcceptDispositionChangeListener implements ServerSession.MessageDi public boolean acquire() { boolean acquired = _entry.acquire(getSubscription()); - //TODO - why acknowledge here??? seems bizarre... - // getSubscription().getSession().acknowledge(getSubscription(), _entry); return acquired; } diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java index b84971d8c3..c410b822a5 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java +++ b/java/broker/src/main/java/org/apache/qpid/server/subscription/SubscriptionImpl.java @@ -490,7 +490,6 @@ public abstract class SubscriptionImpl implements Subscription, FlowCreditManage { _logger.debug("Subscription:" + this + " rejected message:" + entry); } -// return false; } if (_noLocal) @@ -585,7 +584,7 @@ public abstract class SubscriptionImpl implements Subscription, FlowCreditManage public boolean wouldSuspend(QueueEntry msg) { - return !_creditManager.useCreditForMessage(msg.getMessage().getSize());//_channel.wouldSuspend(msg.getMessage()); + return !_creditManager.useCreditForMessage(msg.getMessage().getSize()); } public boolean trySendLock() diff --git a/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java b/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java index 68ab4664c7..9a7d69b10d 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java +++ b/java/broker/src/main/java/org/apache/qpid/server/subscription/Subscription_0_10.java @@ -559,36 +559,8 @@ public class Subscription_0_10 implements Subscription, FlowCreditManager.FlowCr messageProps.setCorrelationId(serverMsg.getMessageHeader().getCorrelationId().getBytes()); } - // TODO - ReplyTo - - final Map<String, Object> appHeaders = new HashMap<String, Object>(); - - /*properties.getHeaders().processOverElements( - new FieldTable.FieldTableElementProcessor() - { - - public boolean processElement(String propertyName, AMQTypedValue value) - { - Object val = value.getValue(); - if(val instanceof AMQShortString) - { - val = val.toString(); - } - appHeaders.put(propertyName, val); - return true; - } - - public Object getResult() - { - return appHeaders; - } - }); - - - messageProps.setApplicationHeaders(appHeaders); -*/ Header header = new Header(deliveryProps, messageProps, null); xfr = batch ? new MessageTransfer(_destination,_acceptMode,_acquireMode,header, body, BATCHED) : new MessageTransfer(_destination,_acceptMode,_acquireMode,header, body); diff --git a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java b/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java index e90c8bafe1..7e6caf7979 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java +++ b/java/broker/src/main/java/org/apache/qpid/server/transport/ServerSessionDelegate.java @@ -155,7 +155,12 @@ public class ServerSessionDelegate extends SessionDelegate @Override public void messageSubscribe(Session session, MessageSubscribe method) { - //TODO - work around broken Python tests + /* + TODO - work around broken Python tests + Correct code should read like + if not hasAcceptMode() exception ILLEGAL_ARGUMENT "Accept-mode not supplied" + else if not method.hasAcquireMode() exception ExecutionErrorCode.ILLEGAL_ARGUMENT, "Acquire-mode not supplied" + */ if(!method.hasAcceptMode()) { method.setAcceptMode(MessageAcceptMode.EXPLICIT); @@ -166,15 +171,7 @@ public class ServerSessionDelegate extends SessionDelegate } - /* if(!method.hasAcceptMode()) - { - exception(session,method,ExecutionErrorCode.ILLEGAL_ARGUMENT, "Accept-mode not supplied"); - } - else if(!method.hasAcquireMode()) - { - exception(session,method,ExecutionErrorCode.ILLEGAL_ARGUMENT, "Acquire-mode not supplied"); - } - else */if(!method.hasQueue()) + if(!method.hasQueue()) { exception(session,method,ExecutionErrorCode.ILLEGAL_ARGUMENT, "queue not supplied"); } @@ -711,15 +708,10 @@ public class ServerSessionDelegate extends SessionDelegate { exception(session, method, ExecutionErrorCode.INVALID_ARGUMENT, "Bind not allowed for default exchange"); } -/* - else if (!method.hasBindingKey()) - { - exception(session, method, ExecutionErrorCode.ILLEGAL_ARGUMENT, "binding-key not set"); - } -*/ else { //TODO - here because of non-compiant python tests + // should raise exception ILLEGAL_ARGUMENT "binding-key not set" if (!method.hasBindingKey()) { method.setBindingKey(method.getQueue()); diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java index f365d33b34..266d23af97 100755 --- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java +++ b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostConfigRecoveryHandler.java @@ -171,9 +171,6 @@ public class VirtualHostConfigRecoveryHandler implements ConfigurationRecoveryHa throw new RuntimeException("Unknown message type retrieved from store " + message.getMetaData().getClass()); } - //_logger.debug("Recovered message with id " + serverMessage); - - _recoveredMessages.put(message.getMessageNumber(), serverMessage); _unusedMessages.put(message.getMessageNumber(), message); } diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java index 82e41abb8d..51b60f7980 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java +++ b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/VirtualHostImpl.java @@ -95,7 +95,7 @@ public class VirtualHostImpl implements VirtualHost private MessageStore _messageStore; - protected VirtualHostMBean _virtualHostMBean; + private VirtualHostMBean _virtualHostMBean; private AMQBrokerManagerMBean _brokerMBean; @@ -257,54 +257,9 @@ public class VirtualHostImpl implements VirtualHost { if (period != 0L) { - class VirtualHostHouseKeepingTask extends HouseKeepingTask - { - public VirtualHostHouseKeepingTask(VirtualHost vhost) - { - super(vhost); - } - public void execute() - { - for (AMQQueue q : _queueRegistry.getQueues()) - { - _logger.debug("Checking message status for queue: " - + q.getName()); - try - { - q.checkMessageStatus(); - } - catch (Exception e) - { - _logger.error("Exception in housekeeping for queue: " - + q.getNameShortString().toString(), e); - //Don't throw exceptions as this will stop the - // house keeping task from running. - } - } - for (AMQConnectionModel connection : getConnectionRegistry().getConnections()) - { - _logger.debug("Checking for long running open transactions on connection " + connection); - for (AMQSessionModel session : connection.getSessionModels()) - { - _logger.debug("Checking for long running open transactions on session " + session); - try - { - session.checkTransactionStatus(_configuration.getTransactionTimeoutOpenWarn(), - _configuration.getTransactionTimeoutOpenClose(), - _configuration.getTransactionTimeoutIdleWarn(), - _configuration.getTransactionTimeoutIdleClose()); - } - catch (Exception e) - { - _logger.error("Exception in housekeeping for connection: " + connection.toString(), e); - } - } - } - } - } - scheduleHouseKeepingTask(period, new VirtualHostHouseKeepingTask(this)); + scheduleHouseKeepingTask(period, new VirtualHostHouseKeepingTask()); Map<String, VirtualHostPluginFactory> plugins = ApplicationRegistry.getInstance().getPluginManager().getVirtualHostPlugins(); @@ -337,6 +292,53 @@ public class VirtualHostImpl implements VirtualHost } } + private class VirtualHostHouseKeepingTask extends HouseKeepingTask + { + public VirtualHostHouseKeepingTask() + { + super(VirtualHostImpl.this); + } + + public void execute() + { + for (AMQQueue q : _queueRegistry.getQueues()) + { + _logger.debug("Checking message status for queue: " + + q.getName()); + try + { + q.checkMessageStatus(); + } + catch (Exception e) + { + _logger.error("Exception in housekeeping for queue: " + + q.getNameShortString().toString(), e); + //Don't throw exceptions as this will stop the + // house keeping task from running. + } + } + for (AMQConnectionModel connection : getConnectionRegistry().getConnections()) + { + _logger.debug("Checking for long running open transactions on connection " + connection); + for (AMQSessionModel session : connection.getSessionModels()) + { + _logger.debug("Checking for long running open transactions on session " + session); + try + { + session.checkTransactionStatus(_configuration.getTransactionTimeoutOpenWarn(), + _configuration.getTransactionTimeoutOpenClose(), + _configuration.getTransactionTimeoutIdleWarn(), + _configuration.getTransactionTimeoutIdleClose()); + } + catch (Exception e) + { + _logger.error("Exception in housekeeping for connection: " + connection.toString(), e); + } + } + } + } + } + /** * Allow other broker components to register a HouseKeepingTask * @@ -791,11 +793,11 @@ public class VirtualHostImpl implements VirtualHost */ private static class StartupRoutingTable implements DurableConfigurationStore { - public List<Exchange> exchange = new LinkedList<Exchange>(); - public List<CreateQueueTuple> queue = new LinkedList<CreateQueueTuple>(); - public List<CreateBindingTuple> bindings = new LinkedList<CreateBindingTuple>(); - public List<BrokerLink> links = new LinkedList<BrokerLink>(); - public List<Bridge> bridges = new LinkedList<Bridge>(); + private List<Exchange> exchange = new LinkedList<Exchange>(); + private List<CreateQueueTuple> queue = new LinkedList<CreateQueueTuple>(); + private List<CreateBindingTuple> bindings = new LinkedList<CreateBindingTuple>(); + private List<BrokerLink> links = new LinkedList<BrokerLink>(); + private List<Bridge> bridges = new LinkedList<Bridge>(); public void configure(VirtualHost virtualHost, String base, VirtualHostConfiguration config) throws Exception { @@ -862,8 +864,8 @@ public class VirtualHostImpl implements VirtualHost private static class CreateQueueTuple { - public AMQQueue queue; - public FieldTable arguments; + private AMQQueue queue; + private FieldTable arguments; public CreateQueueTuple(AMQQueue queue, FieldTable arguments) { @@ -874,10 +876,10 @@ public class VirtualHostImpl implements VirtualHost private static class CreateBindingTuple { - public AMQQueue queue; - public FieldTable arguments; - public Exchange exchange; - public AMQShortString routingKey; + private AMQQueue queue; + private FieldTable arguments; + private Exchange exchange; + private AMQShortString routingKey; public CreateBindingTuple(Exchange exchange, AMQShortString routingKey, AMQQueue queue, FieldTable args) { diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java index 520608f428..12886f400a 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java +++ b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/ConfiguredQueueBindingListener.java @@ -30,7 +30,6 @@ import org.apache.qpid.server.queue.AMQQueue; import java.util.Collections; import java.util.HashSet; -import java.util.Iterator; import java.util.Set; /** @@ -93,7 +92,7 @@ public class ConfiguredQueueBindingListener implements BindingListener /** * Lookup and return the cache of configured {@link AMQQueue}s. * - * Note that when accessing the cached queues, the {@link Iterator} is not thread safe + * Note that when accessing the cached queues, the {@link java.util.Iterator} is not thread safe * (see the {@link Collections#synchronizedSet(Set)} documentation) so a copy of the * cache is returned. * diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java index 68c5ae89ed..2c6705bb3b 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java +++ b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/SlowConsumerDetection.java @@ -25,7 +25,6 @@ import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionConfigu import org.apache.qpid.server.configuration.plugins.SlowConsumerDetectionQueueConfiguration; import org.apache.qpid.server.exchange.ExchangeRegistry; import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.plugins.Plugin; import org.apache.qpid.server.queue.AMQQueue; import org.apache.qpid.server.virtualhost.VirtualHost; import org.apache.qpid.server.virtualhost.plugins.logging.SlowConsumerDetectionMessages; @@ -61,7 +60,7 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin * virtual host to record all the configured queues in a cache for processing by the housekeeping * thread. * - * @see Plugin#configure(ConfigurationPlugin) + * @see org.apache.qpid.server.plugins.Plugin#configure(ConfigurationPlugin) */ public void configure(ConfigurationPlugin config) { @@ -98,7 +97,7 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin if (policy == null) { // We would only expect to see this during shutdown - _logger.warn("No slow consumer policy for queue " + q.getName()); + getLogger().warn("No slow consumer policy for queue " + q.getName()); } else { @@ -110,7 +109,7 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin catch (Exception e) { // Don't throw exceptions as this will stop the house keeping task from running. - _logger.error("Exception in SlowConsumersDetection for queue: " + q.getName(), e); + getLogger().error("Exception in SlowConsumersDetection for queue: " + q.getName(), e); } } @@ -139,9 +138,9 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin { if (config != null) { - if (_logger.isInfoEnabled()) + if (getLogger().isInfoEnabled()) { - _logger.info("Retrieved Queue(" + q.getName() + ") Config:" + config); + getLogger().info("Retrieved Queue(" + q.getName() + ") Config:" + config); } int count = q.getMessageCount(); @@ -157,12 +156,12 @@ public class SlowConsumerDetection extends VirtualHostHouseKeepingPlugin ((count > 0) && q.getOldestMessageArrivalTime() >= config.getMessageAge()))) { - if (_logger.isDebugEnabled()) + if (getLogger().isDebugEnabled()) { - _logger.debug("Detected Slow Consumer on Queue(" + q.getName() + ")"); - _logger.debug("Queue Count:" + q.getMessageCount() + ":" + config.getMessageCount()); - _logger.debug("Queue Depth:" + q.getQueueDepth() + ":" + config.getDepth()); - _logger.debug("Queue Arrival:" + q.getOldestMessageArrivalTime() + ":" + config.getMessageAge()); + getLogger().debug("Detected Slow Consumer on Queue(" + q.getName() + ")"); + getLogger().debug("Queue Count:" + q.getMessageCount() + ":" + config.getMessageCount()); + getLogger().debug("Queue Depth:" + q.getQueueDepth() + ":" + config.getDepth()); + getLogger().debug("Queue Arrival:" + q.getOldestMessageArrivalTime() + ":" + config.getMessageAge()); } return true; diff --git a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java index 9d0cd07e47..191f8041d2 100644 --- a/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java +++ b/java/broker/src/main/java/org/apache/qpid/server/virtualhost/plugins/VirtualHostHouseKeepingPlugin.java @@ -29,7 +29,7 @@ import java.util.concurrent.TimeUnit; public abstract class VirtualHostHouseKeepingPlugin extends HouseKeepingTask implements VirtualHostPlugin { - protected final Logger _logger = Logger.getLogger(getClass()); + private final Logger _logger = Logger.getLogger(getClass()); public VirtualHostHouseKeepingPlugin(VirtualHost vhost) { @@ -52,4 +52,10 @@ public abstract class VirtualHostHouseKeepingPlugin extends HouseKeepingTask imp * @see java.util.concurrent.TimeUnit for valid value. */ public abstract TimeUnit getTimeUnit(); + + + protected Logger getLogger() + { + return _logger; + } } diff --git a/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java b/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java index 94bc3a899a..ae150708ca 100644 --- a/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java +++ b/java/broker/src/main/java/org/apache/qpid/tools/security/Passwd.java @@ -30,6 +30,10 @@ import java.security.NoSuchAlgorithmException; public class Passwd { + private Passwd() + { + } + public static void main(String args[]) throws NoSuchAlgorithmException, DigestException, IOException { if (args.length != 2) diff --git a/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java b/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java index a39799a6b6..a10d3b6a77 100644 --- a/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java +++ b/java/broker/src/velocity/java/org/apache/qpid/server/logging/GenerateLogMessages.java @@ -68,8 +68,7 @@ public class GenerateLogMessages } catch (InvalidTypeException e) { - // This occurs when a type other than 'number' appears in the - // paramater config {0, number...} + // This occurs when a type other than 'number' appears in the paramater config {0, number...}. System.err.println(e.getMessage()); System.exit(-1); } @@ -365,9 +364,9 @@ public class GenerateLogMessages // Taking an example of: // 'Text {n,type,format} [option] text {m} [option with param{p}] more' // This would give us: - // 0 - Text {n,type,format} - // 1 - option] text {m} - // 2 - option with param{p}] more + // 0 - Text {n,type,format}. + // 1 - option] text {m}. + // 2 - option with param{p}] more. // Create the parameter list for this item List<HashMap<String, String>> options = new LinkedList<HashMap<String, String>>(); @@ -442,17 +441,20 @@ public class GenerateLogMessages String[] parametersString = logMessage.split("\\{"); // Taking an example of 'Text {n[,type]} text {m} more text {p}' // This would give us: - // 0 - Text - // 1 - n[,type]} text - // 2 - m} more text - // 3 - p} + // 0 - Text. + // 1 - n[,type]} text. + // 2 - m} more text. + // 3 - p}. // Create the parameter list for this item List<HashMap<String, String>> parameters = new LinkedList<HashMap<String, String>>(); - // Check that we have some parameters to process - // Skip 0 as that will not be the first entry - // Text {n[,type]} text {m} more text {p} + /* + Check that we have some parameters to process + Skip 0 as that will not be the first entry + Text {n[,type]} text {m} more text {p}. + */ + if (parametersString.length > 1) { for (int index = 1; index < parametersString.length; index++) @@ -461,8 +463,11 @@ public class GenerateLogMessages // for easy retrieval in the macro template HashMap<String, String> parameter = new HashMap<String, String>(); - // Check for any properties of the parameter : - // e.g. {0} vs {0,number} vs {0,number,xxxx} + /* + Check for any properties of the parameter : + e.g. {0} vs {0,number} vs {0,number,xxxx}. + */ + int typeIndex = parametersString[index].indexOf(","); // The parameter type diff --git a/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm b/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm index fd847fd513..02bf155c44 100644 --- a/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm +++ b/java/broker/src/velocity/templates/org/apache/qpid/server/logging/messages/LogMessages.vm @@ -43,8 +43,8 @@ import java.util.ResourceBundle; */ public class ${type.name}Messages { - static ResourceBundle _messages; - static Locale _currentLocale; + private static ResourceBundle _messages; + private static Locale _currentLocale; public static final String ${type.name.toUpperCase()}_LOG_HIERARCHY = DEFAULT_LOG_HIERARCHY_PREFIX + "${type.name.toLowerCase()}"; #foreach( $message in ${type.list} ) @@ -146,7 +146,7 @@ public class ${type.name}Messages ## append it to the log. #foreach($option in ${message.options}) - // Add Option : ${option.value} + // Add Option : ${option.value}. end = parts[${velocityCount}].indexOf(']'); if (${option.name}) { @@ -197,4 +197,8 @@ public class ${type.name}Messages #end + private ${type.name}Messages() + { + } + } diff --git a/java/client/example/src/main/java/org/apache/qpid/example/Drain.java b/java/client/example/src/main/java/org/apache/qpid/example/Drain.java index b43031ad23..28e1d5a87e 100644 --- a/java/client/example/src/main/java/org/apache/qpid/example/Drain.java +++ b/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/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java b/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java index 6cc6db1974..6aa12f07fa 100644 --- a/java/client/example/src/main/java/org/apache/qpid/example/OptionParser.java +++ b/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) { @@ -283,7 +283,17 @@ 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 final String shortForm; diff --git a/java/client/example/src/main/java/org/apache/qpid/example/Spout.java b/java/client/example/src/main/java/org/apache/qpid/example/Spout.java index 5da319a658..61ff2dfc19 100644 --- a/java/client/example/src/main/java/org/apache/qpid/example/Spout.java +++ b/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/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java index 6c684e593d..39ad282422 100644 --- a/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java +++ b/java/client/src/main/java/org/apache/qpid/client/AMQConnection.java @@ -809,13 +809,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); } } } @@ -1241,8 +1241,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); } @@ -1253,7 +1253,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); } diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java index 5068b1bc50..40323844f6 100644 --- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java +++ b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionDelegate_8_0.java @@ -213,7 +213,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; @@ -307,7 +306,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/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java index da57fefd27..cc91746d98 100644 --- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java +++ b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionFactory.java @@ -27,7 +27,6 @@ import org.apache.qpid.url.URLSyntaxException; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.JMSException; -import javax.jms.JMSSecurityException; import javax.jms.QueueConnection; import javax.jms.QueueConnectionFactory; import javax.jms.TopicConnection; @@ -278,7 +277,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 { @@ -305,7 +304,7 @@ 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 { @@ -346,7 +345,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 { @@ -363,7 +362,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 { @@ -378,7 +377,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 { @@ -395,7 +394,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/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java index e96689b7b1..d59f48542f 100644 --- a/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java +++ b/java/client/src/main/java/org/apache/qpid/client/AMQConnectionURL.java @@ -276,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/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java b/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java index 9e19cc8969..2479f89b52 100644 --- a/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java +++ b/java/client/src/main/java/org/apache/qpid/client/AMQDestination.java @@ -622,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(); diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java b/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java index 2ea9c4b468..c413f71906 100644 --- a/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java +++ b/java/client/src/main/java/org/apache/qpid/client/AMQQueue.java @@ -155,7 +155,6 @@ public class AMQQueue extends AMQDestination implements Queue public AMQShortString getRoutingKey() { - //return getAMQQueueName(); if (getAMQQueueName() != null && getAMQQueueName().equals(super.getRoutingKey())) { return getAMQQueueName(); diff --git a/java/client/src/main/java/org/apache/qpid/client/AMQSession.java b/java/client/src/main/java/org/apache/qpid/client/AMQSession.java index 92579c31f0..25a2875b3f 100644 --- a/java/client/src/main/java/org/apache/qpid/client/AMQSession.java +++ b/java/client/src/main/java/org/apache/qpid/client/AMQSession.java @@ -826,15 +826,13 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic { if (_logger.isInfoEnabled()) { - // StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); - _logger.info("Closing session: " + this); // + ":" - // Arrays.asList(stackTrace).subList(3, stackTrace.length - 1)); + _logger.info("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 @@ -911,9 +909,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) { @@ -1012,9 +1010,7 @@ 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()) { @@ -1694,7 +1690,6 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic public MessageListener getMessageListener() throws JMSException { - // checkNotClosed(); return _messageListener; } @@ -1981,31 +1976,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); - // } - } /** @@ -2279,7 +2249,7 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic */ void markClosed() { - _closed.set(true); + setClosed(); _connection.deregisterSession(_channelId); markClosedProducersAndConsumers(); @@ -2294,7 +2264,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 @@ -2346,7 +2316,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 @@ -2518,32 +2488,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()) @@ -3372,7 +3316,6 @@ public abstract class AMQSession<C extends BasicMessageConsumer, P extends Basic else { // should perhaps clear the _SQ here. - // consumer._synchronousQueue.clear(); consumer.clearReceiveQueue(); } @@ -3595,30 +3538,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; @@ -3662,7 +3581,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(); } /** @@ -3674,7 +3593,7 @@ 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() diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java index f0f2c85c2f..1def0c4237 100644 --- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java +++ b/java/client/src/main/java/org/apache/qpid/client/BasicMessageConsumer.java @@ -536,7 +536,7 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa } else if (o instanceof CloseConsumerMessage) { - _closed.set(true); + setClosed(); deregisterConsumer(); return null; } @@ -558,9 +558,9 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa _logger.info("Closing consumer:" + debugIdentity()); } - if (!_closed.getAndSet(true)) + if (!setClosed()) { - _closing.set(true); + setClosing(true); if (_logger.isDebugEnabled()) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); @@ -606,12 +606,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 @@ -640,7 +636,7 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa { // synchronized (_closed) { - _closed.set(true); + setClosed(); if (_logger.isDebugEnabled()) { @@ -817,7 +813,7 @@ public abstract class BasicMessageConsumer<U> extends Closeable implements Messa { // synchronized (_closed) { - _closed.set(true); + setClosed(); if (_logger.isDebugEnabled()) { StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace(); @@ -1002,8 +998,6 @@ 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() {} diff --git a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java b/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java index 84747d6f09..75f198e1fa 100644 --- a/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java +++ b/java/client/src/main/java/org/apache/qpid/client/BasicMessageProducer.java @@ -327,7 +327,7 @@ public abstract class BasicMessageProducer extends Closeable implements org.apac public void close() throws JMSException { - _closed.set(true); + setClosed(); _session.deregisterProducer(_producerId); } diff --git a/java/client/src/main/java/org/apache/qpid/client/Closeable.java b/java/client/src/main/java/org/apache/qpid/client/Closeable.java index 770e3e73fa..ba26bfc485 100644 --- a/java/client/src/main/java/org/apache/qpid/client/Closeable.java +++ b/java/client/src/main/java/org/apache/qpid/client/Closeable.java @@ -48,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. @@ -90,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/java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.java b/java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.java index 7059588367..b778ee22d6 100644 --- a/java/client/src/main/java/org/apache/qpid/client/QueueReceiverAdaptor.java +++ b/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/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java index 61ed8ba864..4099da18d2 100644 --- a/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java +++ b/java/client/src/main/java/org/apache/qpid/client/failover/FailoverHandler.java @@ -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/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java index 59cf805709..2cf7b089eb 100644 --- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java +++ b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionCloseMethodHandler.java @@ -54,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/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java index 12dab8134f..8fc51f7799 100644 --- a/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java +++ b/java/client/src/main/java/org/apache/qpid/client/handler/ConnectionStartMethodHandler.java @@ -180,14 +180,19 @@ 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")); + StringBuilder fullSystemInfo = new StringBuilder(System.getProperty("java.runtime.name")); + fullSystemInfo.append(", "); + fullSystemInfo.append(System.getProperty("java.runtime.version")); + fullSystemInfo.append(", "); + fullSystemInfo.append(System.getProperty("java.vendor")); + fullSystemInfo.append(", "); + fullSystemInfo.append(System.getProperty("os.arch")); + fullSystemInfo.append(", "); + fullSystemInfo.append(System.getProperty("os.name")); + fullSystemInfo.append(", "); + fullSystemInfo.append(System.getProperty("os.version")); + fullSystemInfo.append(", "); + fullSystemInfo.append(System.getProperty("sun.os.patch.level")); return fullSystemInfo.toString(); } diff --git a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java b/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java index 8f2cf80974..0973815231 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java +++ b/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_10.java @@ -947,7 +947,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/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java b/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java index 5d5fbad88b..fe9f9f4d00 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java +++ b/java/client/src/main/java/org/apache/qpid/client/message/AMQMessageDelegate_0_8.java @@ -28,7 +28,6 @@ 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.collections.ReferenceMap; import org.apache.qpid.framing.AMQShortString; import org.apache.qpid.framing.BasicContentHeaderProperties; import org.apache.qpid.framing.ContentHeaderProperties; @@ -41,12 +40,28 @@ 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; + 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"; @@ -234,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 @@ -271,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/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java index 62822fd528..11d99f5446 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java +++ b/java/client/src/main/java/org/apache/qpid/client/message/AMQPEncodedMapMessage.java @@ -67,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 { @@ -81,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(); } @@ -93,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/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java b/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java index 79f8924e33..31a0440b04 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java +++ b/java/client/src/main/java/org/apache/qpid/client/message/FieldTableSupport.java @@ -28,27 +28,31 @@ 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 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 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; + } - return map; - } + 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; + } } diff --git a/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java index 7b4bfd2e2a..122a5c4ef2 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java +++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSHeaderAdapter.java @@ -59,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."); } @@ -88,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."); } @@ -159,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."); } @@ -227,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."); } @@ -284,7 +284,7 @@ public final class JMSHeaderAdapter s = String.valueOf(o); } } - }//else return s // null; + } } return s; @@ -526,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/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java b/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java index 580bc5647d..e18ed80f6d 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java +++ b/java/client/src/main/java/org/apache/qpid/client/message/JMSMapMessage.java @@ -39,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 { @@ -483,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/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java b/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java index 78766ea036..5abd02f150 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java +++ b/java/client/src/main/java/org/apache/qpid/client/message/MessageConverter.java @@ -41,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/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java b/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java index 4540692190..fa39b4c93c 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java +++ b/java/client/src/main/java/org/apache/qpid/client/message/MessageFactoryRegistry.java @@ -44,7 +44,7 @@ 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/java/client/src/main/java/org/apache/qpid/client/message/QpidMessageProperties.java b/java/client/src/main/java/org/apache/qpid/client/message/QpidMessageProperties.java index b30afafa35..663dfd39b1 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/QpidMessageProperties.java +++ b/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/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java b/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java index c78b6ced93..5ed98dc8ea 100644 --- a/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java +++ b/java/client/src/main/java/org/apache/qpid/client/message/UnprocessedMessage_0_8.java @@ -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; diff --git a/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java b/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java index bb5bba9068..0da0327885 100644 --- a/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java +++ b/java/client/src/main/java/org/apache/qpid/client/messaging/address/Node.java @@ -104,8 +104,8 @@ 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() { @@ -125,8 +125,8 @@ 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() { diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java index d4da0ede32..2bc2d2ef03 100644 --- a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java +++ b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolHandler.java @@ -299,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); @@ -313,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 diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java index c9b2e9cdc4..ced734f70f 100644 --- a/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java +++ b/java/client/src/main/java/org/apache/qpid/client/protocol/AMQProtocolSession.java @@ -90,8 +90,6 @@ public class AMQProtocolSession implements AMQVersionAwareProtocolSession private final Object _queueIdLock = new Object(); private ProtocolVersion _protocolVersion; -// private VersionSpecificRegistry _registry = -// MainRegistry.getVersionSpecificRegistry(ProtocolVersion.getLatestSupportedVersion()); private MethodRegistry _methodRegistry = MethodRegistry.getMethodRegistry(ProtocolVersion.getLatestSupportedVersion()); diff --git a/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java b/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java index d44faeab04..d387a8ba93 100644 --- a/java/client/src/main/java/org/apache/qpid/client/protocol/HeartbeatDiagnostics.java +++ b/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/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java b/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java index cb3d1dea28..9198903408 100644 --- a/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java +++ b/java/client/src/main/java/org/apache/qpid/client/security/DynamicSaslRegistrar.java @@ -62,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() { @@ -121,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/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java b/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java index bbf90d725c..4a91f805f6 100644 --- a/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java +++ b/java/client/src/main/java/org/apache/qpid/client/security/JCAProvider.java @@ -51,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/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java b/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java index 616c02f3aa..7d028e022a 100644 --- a/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java +++ b/java/client/src/main/java/org/apache/qpid/client/state/AMQStateManager.java @@ -111,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/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java b/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java index 9b85ee3a60..d81868f924 100644 --- a/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java +++ b/java/client/src/main/java/org/apache/qpid/client/url/URLParser_0_10.java @@ -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/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java b/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java index c371341265..80d171592f 100644 --- a/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java +++ b/java/client/src/main/java/org/apache/qpid/client/util/BlockingWaiter.java @@ -184,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/java/client/src/main/java/org/apache/qpid/collections/KeyValue.java b/java/client/src/main/java/org/apache/qpid/collections/KeyValue.java deleted file mode 100644 index e890aba968..0000000000 --- a/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/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java b/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java deleted file mode 100644 index 84e4704867..0000000000 --- a/java/client/src/main/java/org/apache/qpid/collections/ReferenceMap.java +++ /dev/null @@ -1,1038 +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 org.apache.qpid.collections.keyvalue.DefaultMapEntry; - -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; - -/** - * 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 { - - private Object key; - private Object value; - private int hash; - private 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. - private int index; - private Entry entry; - private 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. - private Object nextKey, nextValue; - private Object currentKey, currentValue; - - private 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/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java b/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java deleted file mode 100644 index f1b6d11bee..0000000000 --- a/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractKeyValue.java +++ /dev/null @@ -1,98 +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 */ - private Object key; - /** The value */ - private 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; - } - - /** - * 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; - } - - /** - * 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/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java b/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java deleted file mode 100644 index 7135c31fd7..0000000000 --- a/java/client/src/main/java/org/apache/qpid/collections/keyvalue/AbstractMapEntry.java +++ /dev/null @@ -1,81 +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; - -/** - * 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 - //------------------------------------------------------------------------- - - - /** - * 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/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java b/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java deleted file mode 100644 index 27cc4236d3..0000000000 --- a/java/client/src/main/java/org/apache/qpid/collections/keyvalue/DefaultMapEntry.java +++ /dev/null @@ -1,66 +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 org.apache.qpid.collections.KeyValue; - -import java.util.Map; - -/** - * 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/java/client/src/main/java/org/apache/qpid/filter/ComparisonExpression.java b/java/client/src/main/java/org/apache/qpid/filter/ComparisonExpression.java index 87d43ec343..bf5220f695 100644 --- a/java/client/src/main/java/org/apache/qpid/filter/ComparisonExpression.java +++ b/java/client/src/main/java/org/apache/qpid/filter/ComparisonExpression.java @@ -145,7 +145,6 @@ public abstract class ComparisonExpression extends BinaryExpression implements B { return Boolean.FALSE; - // throw new RuntimeException("LIKE can only operate on String identifiers. LIKE attemped on: '" + rv.getClass()); } return likePattern.matcher((String) rv).matches() ? Boolean.TRUE : Boolean.FALSE; diff --git a/java/client/src/main/java/org/apache/qpid/filter/UnaryExpression.java b/java/client/src/main/java/org/apache/qpid/filter/UnaryExpression.java index 857fbd3ba4..55fb044839 100644 --- a/java/client/src/main/java/org/apache/qpid/filter/UnaryExpression.java +++ b/java/client/src/main/java/org/apache/qpid/filter/UnaryExpression.java @@ -33,7 +33,7 @@ public abstract class UnaryExpression implements Expression { private static final BigDecimal BD_LONG_MIN_VALUE = BigDecimal.valueOf(Long.MIN_VALUE); - protected Expression right; + private final Expression right; public static Expression createNegate(Expression left) { @@ -41,7 +41,7 @@ public abstract class UnaryExpression implements Expression { public Object evaluate(AbstractJMSMessage message) throws AMQInternalException { - Object rvalue = right.evaluate(message); + Object rvalue = getRight().evaluate(message); if (rvalue == null) { return null; @@ -87,7 +87,7 @@ public abstract class UnaryExpression implements Expression public Object evaluate(AbstractJMSMessage message) throws AMQInternalException { - Object rvalue = right.evaluate(message); + Object rvalue = getRight().evaluate(message); if (rvalue == null) { return null; @@ -112,7 +112,7 @@ public abstract class UnaryExpression implements Expression public String toString() { StringBuffer answer = new StringBuffer(); - answer.append(right); + answer.append(getRight()); answer.append(" "); answer.append(getExpressionSymbol()); answer.append(" ( "); @@ -172,7 +172,7 @@ public abstract class UnaryExpression implements Expression { public Object evaluate(AbstractJMSMessage message) throws AMQInternalException { - Boolean lvalue = (Boolean) right.evaluate(message); + Boolean lvalue = (Boolean) getRight().evaluate(message); if (lvalue == null) { return null; @@ -193,7 +193,7 @@ public abstract class UnaryExpression implements Expression { public Object evaluate(AbstractJMSMessage message) throws AMQInternalException { - Object rvalue = right.evaluate(message); + Object rvalue = getRight().evaluate(message); if (rvalue == null) { return null; @@ -209,7 +209,7 @@ public abstract class UnaryExpression implements Expression public String toString() { - return right.toString(); + return getRight().toString(); } public String getExpressionSymbol() @@ -270,17 +270,12 @@ public abstract class UnaryExpression implements Expression return right; } - public void setRight(Expression expression) - { - right = expression; - } - /** * @see Object#toString() */ public String toString() { - return "(" + getExpressionSymbol() + " " + right.toString() + ")"; + return "(" + getExpressionSymbol() + " " + getRight().toString() + ")"; } /** diff --git a/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java b/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java index 1a4b8937ae..f4d2ecc36d 100644 --- a/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java +++ b/java/client/src/main/java/org/apache/qpid/jms/FailoverPolicy.java @@ -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/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java index fcadc7bbc7..a5eda29274 100644 --- a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java +++ b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverExchangeMethod.java @@ -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/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java index 17eb8fc613..84c1794723 100644 --- a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java +++ b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverRoundRobinServers.java @@ -50,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/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java index 4da6d86ebc..1ef71eccba 100644 --- a/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java +++ b/java/client/src/main/java/org/apache/qpid/jms/failover/FailoverSingleServer.java @@ -37,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) @@ -65,6 +65,11 @@ public class FailoverSingleServer implements FailoverMethod _currentRetries = 0; } + protected void setCurrentRetries(int currentRetries) + { + _currentRetries = currentRetries; + } + public boolean failoverAllowed() { return _currentRetries < _retries; @@ -151,6 +156,11 @@ public class FailoverSingleServer implements FailoverMethod _retries = retries; } + public int getRetries() + { + return _retries; + } + public String methodName() { return "Single Server"; diff --git a/java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.java b/java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.java index 1231324397..82cb0f9153 100644 --- a/java/client/src/main/java/org/apache/qpid/jms/failover/NoFailover.java +++ b/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/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java b/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java index 4a02f9b341..bc3f89849e 100644 --- a/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java +++ b/java/client/src/main/java/org/apache/qpid/jndi/PropertiesFileInitialContextFactory.java @@ -53,7 +53,7 @@ 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/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java b/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java index e9190a278f..76ec5f9498 100644 --- a/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java +++ b/java/client/src/main/java/org/apache/qpid/jndi/ReadOnlyContext.java @@ -65,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/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java b/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java index 2216d8796a..62e6672289 100644 --- a/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java +++ b/java/client/src/main/java/org/apache/qpid/naming/ReadOnlyContext.java @@ -64,9 +64,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/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java b/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java index 802cbe7270..7134f0a960 100644 --- a/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java +++ b/java/client/src/main/java/org/apache/qpid/nclient/util/ByteBufferMessage.java @@ -45,7 +45,7 @@ import java.util.List; */ 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/java/common/Type.tpl b/java/common/Type.tpl index 7f9cfee268..4635c4e367 100644 --- a/java/common/Type.tpl +++ b/java/common/Type.tpl @@ -56,9 +56,9 @@ for t in types: out(" $name((byte) $code, $width, $fixed)") }; - public byte code; - public int width; - public boolean fixed; + private final byte code; + private final int width; + private final boolean fixed; Type(byte code, int width, boolean fixed) { @@ -67,6 +67,21 @@ for t in types: this.fixed = fixed; } + public byte getCode() + { + return code; + } + + public int getWidth() + { + return width; + } + + public boolean isFixed() + { + return fixed; + } + public static Type get(byte code) { switch (code) diff --git a/java/common/src/main/java/org/apache/configuration/PropertyNameResolver.java b/java/common/src/main/java/org/apache/configuration/PropertyNameResolver.java index 73ee747c07..1029544fd6 100644 --- a/java/common/src/main/java/org/apache/configuration/PropertyNameResolver.java +++ b/java/common/src/main/java/org/apache/configuration/PropertyNameResolver.java @@ -32,7 +32,7 @@ public class PropertyNameResolver } private static Map<Class<?>,Accessor> accessors = new HashMap<Class<?>,Accessor>(); - protected Map<String,QpidProperty> properties; + private Map<String,QpidProperty> properties; private static class BooleanAccessor implements Accessor { diff --git a/java/common/src/main/java/org/apache/qpid/AMQStoreException.java b/java/common/src/main/java/org/apache/qpid/AMQStoreException.java index 8389fe5efa..45aa36a20b 100644 --- a/java/common/src/main/java/org/apache/qpid/AMQStoreException.java +++ b/java/common/src/main/java/org/apache/qpid/AMQStoreException.java @@ -20,10 +20,8 @@ */ package org.apache.qpid; -import java.sql.SQLException; - /** - * StoreException is a specific type of internal error relating to errors in the message store, such as {@link SQLException}. + * StoreException is a specific type of internal error relating to errors in the message store, such as {@link java.sql.SQLException}. */ public class AMQStoreException extends AMQInternalException { diff --git a/java/common/src/main/java/org/apache/qpid/common/ServerPropertyNames.java b/java/common/src/main/java/org/apache/qpid/common/ServerPropertyNames.java index aa262bdde5..dd94f8251b 100644 --- a/java/common/src/main/java/org/apache/qpid/common/ServerPropertyNames.java +++ b/java/common/src/main/java/org/apache/qpid/common/ServerPropertyNames.java @@ -26,6 +26,10 @@ package org.apache.qpid.common; */ public final class ServerPropertyNames { + private ServerPropertyNames() + { + } + /** * Server property: federation tag UUID */ diff --git a/java/common/src/main/java/org/apache/qpid/configuration/ClientProperties.java b/java/common/src/main/java/org/apache/qpid/configuration/ClientProperties.java index a36e7c214e..69a6602baf 100644 --- a/java/common/src/main/java/org/apache/qpid/configuration/ClientProperties.java +++ b/java/common/src/main/java/org/apache/qpid/configuration/ClientProperties.java @@ -116,16 +116,7 @@ public class ClientProperties */ public static final String REJECT_BEHAVIOUR_PROP_NAME = "qpid.reject.behaviour"; - /* - public static final QpidProperty<Boolean> IGNORE_SET_CLIENTID_PROP_NAME = - QpidProperty.booleanProperty(false,"qpid.ignore_set_client_id","ignore_setclientID"); - - public static final QpidProperty<Boolean> SYNC_PERSISTENT_PROP_NAME = - QpidProperty.booleanProperty(false,"qpid.sync_persistence","sync_persistence"); - - - public static final QpidProperty<Integer> MAX_PREFETCH_PROP_NAME = - QpidProperty.intProperty(500,"qpid.max_prefetch","max_prefetch"); */ - - + private ClientProperties() + { + } } diff --git a/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java b/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java index 6e2b25fb2c..19e998733a 100644 --- a/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java +++ b/java/common/src/main/java/org/apache/qpid/configuration/PropertyUtils.java @@ -40,6 +40,10 @@ import java.util.Iterator; */ public class PropertyUtils { + private PropertyUtils() + { + } + /** * Given a string that contains substrings of the form <code>${xxx}</code>, looks up the valuea of 'xxx' as a * system properties and substitutes tham back into the original string, to provide a property value expanded diff --git a/java/common/src/main/java/org/apache/qpid/configuration/QpidProperty.java b/java/common/src/main/java/org/apache/qpid/configuration/QpidProperty.java index 9c0aaaec89..e88c7784a2 100644 --- a/java/common/src/main/java/org/apache/qpid/configuration/QpidProperty.java +++ b/java/common/src/main/java/org/apache/qpid/configuration/QpidProperty.java @@ -24,7 +24,7 @@ abstract class QpidProperty<T> { private T defValue; private String[] names; - protected Accessor accessor; + private Accessor accessor; QpidProperty(T defValue, String... names) { @@ -101,7 +101,12 @@ abstract class QpidProperty<T> { return new QpidStringProperty(accessor,defaultValue, names); } - + + protected Accessor getAccessor() + { + return accessor; + } + static class QpidBooleanProperty extends QpidProperty<Boolean> { QpidBooleanProperty(Boolean defValue, String... names) @@ -117,7 +122,7 @@ abstract class QpidProperty<T> @Override protected Boolean getByName(String name) { - return accessor.getBoolean(name); + return getAccessor().getBoolean(name); } } @@ -136,7 +141,7 @@ abstract class QpidProperty<T> @Override protected Integer getByName(String name) { - return accessor.getInt(name); + return getAccessor().getInt(name); } } @@ -155,7 +160,7 @@ abstract class QpidProperty<T> @Override protected Long getByName(String name) { - return accessor.getLong(name); + return getAccessor().getLong(name); } } @@ -174,7 +179,7 @@ abstract class QpidProperty<T> @Override protected String getByName(String name) { - return accessor.getString(name); + return getAccessor().getString(name); } } diff --git a/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java b/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java index 1989ade4ac..975ec4daca 100644 --- a/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java +++ b/java/common/src/main/java/org/apache/qpid/exchange/ExchangeDefaults.java @@ -36,6 +36,10 @@ import org.apache.qpid.framing.AMQShortString; */ public class ExchangeDefaults { + private ExchangeDefaults() + { + } + /** The default direct exchange, which is a special internal exchange that cannot be explicitly bound to. */ public static final AMQShortString DEFAULT_EXCHANGE_NAME = new AMQShortString("<<default>>"); diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java index f5fbbac42b..966a03605c 100644 --- a/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java +++ b/java/common/src/main/java/org/apache/qpid/framing/AMQMethodBody.java @@ -52,10 +52,6 @@ public interface AMQMethodBody extends AMQBody public void writePayload(DataOutput buffer) throws IOException; - //public abstract void populateMethodBodyFromBuffer(ByteBuffer buffer) throws AMQFrameDecodingException; - - //public void populateFromBuffer(ByteBuffer buffer, long size) throws AMQFrameDecodingException; - public AMQFrame generateFrame(int channelId); public String toString(); diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java b/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java index 3951f17681..85870e68c5 100644 --- a/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java +++ b/java/common/src/main/java/org/apache/qpid/framing/AMQShortString.java @@ -321,7 +321,6 @@ public final class AMQShortString implements CharSequence, Comparable<AMQShortSt { final int size = length(); - //buffer.setAutoExpand(true); buffer.writeByte(size); buffer.write(_data, _offset, size); diff --git a/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java b/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java index a07fd78c8c..94a7d127b3 100644 --- a/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java +++ b/java/common/src/main/java/org/apache/qpid/framing/AMQTypeMap.java @@ -27,6 +27,10 @@ public class AMQTypeMap { public static final Map<Byte, AMQType> _reverseTypeMap = new HashMap<Byte, AMQType>(); + private AMQTypeMap() + { + } + static { for(AMQType type : AMQType.values()) diff --git a/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java b/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java index f942d33389..a6883917d5 100644 --- a/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java +++ b/java/common/src/main/java/org/apache/qpid/framing/BasicContentHeaderProperties.java @@ -294,85 +294,83 @@ public class BasicContentHeaderProperties implements CommonContentHeaderProperti private void decode(ByteArrayDataInput buffer) throws IOException, AMQFrameDecodingException { - // ByteBuffer buffer = ByteBuffer.wrap(_encodedForm); + int headersOffset = 0; - int headersOffset = 0; - - if ((_propertyFlags & (CONTENT_TYPE_MASK)) != 0) - { - _contentType = buffer.readAMQShortString(); - headersOffset += EncodingUtils.encodedShortStringLength(_contentType); - } + if ((_propertyFlags & (CONTENT_TYPE_MASK)) != 0) + { + _contentType = buffer.readAMQShortString(); + headersOffset += EncodingUtils.encodedShortStringLength(_contentType); + } - if ((_propertyFlags & ENCODING_MASK) != 0) - { - _encoding = buffer.readAMQShortString(); - headersOffset += EncodingUtils.encodedShortStringLength(_encoding); - } + if ((_propertyFlags & ENCODING_MASK) != 0) + { + _encoding = buffer.readAMQShortString(); + headersOffset += EncodingUtils.encodedShortStringLength(_encoding); + } - if ((_propertyFlags & HEADERS_MASK) != 0) - { - long length = EncodingUtils.readUnsignedInteger(buffer); + if ((_propertyFlags & HEADERS_MASK) != 0) + { + long length = EncodingUtils.readUnsignedInteger(buffer); - _headers = new FieldTable(_encodedForm, headersOffset+4, (int)length); + _headers = new FieldTable(_encodedForm, headersOffset+4, (int)length); - buffer.skipBytes((int)length); - } + buffer.skipBytes((int)length); + } - if ((_propertyFlags & DELIVERY_MODE_MASK) != 0) - { - _deliveryMode = buffer.readByte(); - } + if ((_propertyFlags & DELIVERY_MODE_MASK) != 0) + { + _deliveryMode = buffer.readByte(); + } - if ((_propertyFlags & PRIORITY_MASK) != 0) - { - _priority = buffer.readByte(); - } + if ((_propertyFlags & PRIORITY_MASK) != 0) + { + _priority = buffer.readByte(); + } - if ((_propertyFlags & CORRELATION_ID_MASK) != 0) - { - _correlationId = buffer.readAMQShortString(); - } + if ((_propertyFlags & CORRELATION_ID_MASK) != 0) + { + _correlationId = buffer.readAMQShortString(); + } - if ((_propertyFlags & REPLY_TO_MASK) != 0) - { - _replyTo = buffer.readAMQShortString(); - } + if ((_propertyFlags & REPLY_TO_MASK) != 0) + { + _replyTo = buffer.readAMQShortString(); + } - if ((_propertyFlags & EXPIRATION_MASK) != 0) - { - _expiration = EncodingUtils.readLongAsShortString(buffer); - } + if ((_propertyFlags & EXPIRATION_MASK) != 0) + { + _expiration = EncodingUtils.readLongAsShortString(buffer); + } - if ((_propertyFlags & MESSAGE_ID_MASK) != 0) - { - _messageId = buffer.readAMQShortString(); - } + if ((_propertyFlags & MESSAGE_ID_MASK) != 0) + { + _messageId = buffer.readAMQShortString(); + } - if ((_propertyFlags & TIMESTAMP_MASK) != 0) - { - _timestamp = EncodingUtils.readTimestamp(buffer); - } + if ((_propertyFlags & TIMESTAMP_MASK) != 0) + { + _timestamp = EncodingUtils.readTimestamp(buffer); + } - if ((_propertyFlags & TYPE_MASK) != 0) - { - _type = buffer.readAMQShortString(); - } + if ((_propertyFlags & TYPE_MASK) != 0) + { + _type = buffer.readAMQShortString(); + } - if ((_propertyFlags & USER_ID_MASK) != 0) - { - _userId = buffer.readAMQShortString(); - } + if ((_propertyFlags & USER_ID_MASK) != 0) + { + _userId = buffer.readAMQShortString(); + } - if ((_propertyFlags & APPLICATION_ID_MASK) != 0) - { - _appId = buffer.readAMQShortString(); - } + if ((_propertyFlags & APPLICATION_ID_MASK) != 0) + { + _appId = buffer.readAMQShortString(); + } - if ((_propertyFlags & CLUSTER_ID_MASK) != 0) - { - _clusterId = buffer.readAMQShortString(); - } + if ((_propertyFlags & CLUSTER_ID_MASK) != 0) + { + _clusterId = buffer.readAMQShortString(); + } } diff --git a/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java b/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java index 538e0e1327..6d05c2fd3a 100644 --- a/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java +++ b/java/common/src/main/java/org/apache/qpid/framing/EncodingUtils.java @@ -41,6 +41,10 @@ public class EncodingUtils public static final int SIZEOF_UNSIGNED_INT = 4; private static final boolean[] ALL_FALSE_ARRAY = new boolean[8]; + private EncodingUtils() + { + } + public static int encodedShortStringLength(String s) { if (s == null) @@ -115,7 +119,7 @@ public class EncodingUtils { return len + 6 + encodedShortStringLength((short) (i / 1000000)); } - else // if (i > 99999) + else // if i > 99999 { return len + 5 + encodedShortStringLength((short) (i / 100000)); } @@ -737,8 +741,6 @@ public class EncodingUtils public static long readTimestamp(DataInput buffer) throws IOException { - // Discard msb from AMQ timestamp - // buffer.getUnsignedInt(); return buffer.readLong(); } @@ -803,8 +805,6 @@ public class EncodingUtils byte[] from = new byte[size]; - // Is this not the same. - // bb.get(from, 0, length); for (int i = 0; i < size; i++) { from[i] = bb.get(i); @@ -959,7 +959,6 @@ public class EncodingUtils else { // really writing out unsigned byte - //buffer.put((byte) 0); writeUnsignedInteger(buffer, 0L); } } diff --git a/java/common/src/main/java/org/apache/qpid/framing/FieldTableFactory.java b/java/common/src/main/java/org/apache/qpid/framing/FieldTableFactory.java index b2b78ebcef..a2d4d27396 100644 --- a/java/common/src/main/java/org/apache/qpid/framing/FieldTableFactory.java +++ b/java/common/src/main/java/org/apache/qpid/framing/FieldTableFactory.java @@ -25,6 +25,10 @@ import java.io.IOException; public class FieldTableFactory { + private FieldTableFactory() + { + } + public static FieldTable newFieldTable() { return new FieldTable(); diff --git a/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java b/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java index 3c1e67f488..0a06f0f1e9 100644 --- a/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java +++ b/java/common/src/main/java/org/apache/qpid/framing/ProtocolInitiation.java @@ -43,9 +43,6 @@ public class ProtocolInitiation extends AMQDataBlock implements EncodableAMQData private final byte _protocolMajor; private final byte _protocolMinor; - -// public ProtocolInitiation() {} - public ProtocolInitiation(byte[] protocolHeader, byte protocolClass, byte protocolInstance, byte protocolMajor, byte protocolMinor) { _protocolHeader = protocolHeader; diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/JAddr.java b/java/common/src/main/java/org/apache/qpid/messaging/util/JAddr.java index 225f7c11e9..c5c2cacd1a 100644 --- a/java/common/src/main/java/org/apache/qpid/messaging/util/JAddr.java +++ b/java/common/src/main/java/org/apache/qpid/messaging/util/JAddr.java @@ -35,6 +35,9 @@ import java.util.List; public class JAddr { + private JAddr() + { + } public static final void main(String[] args) throws Exception { diff --git a/java/common/src/main/java/org/apache/qpid/messaging/util/PyPrint.java b/java/common/src/main/java/org/apache/qpid/messaging/util/PyPrint.java index ef6c724371..2681893482 100644 --- a/java/common/src/main/java/org/apache/qpid/messaging/util/PyPrint.java +++ b/java/common/src/main/java/org/apache/qpid/messaging/util/PyPrint.java @@ -33,6 +33,9 @@ import java.util.Map; public class PyPrint { + private PyPrint() + { + } public static String pprint(Object obj) { diff --git a/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java b/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java index 260c17f193..185c01d3df 100644 --- a/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java +++ b/java/common/src/main/java/org/apache/qpid/protocol/AMQVersionAwareProtocolSession.java @@ -51,7 +51,6 @@ public interface AMQVersionAwareProtocolSession extends AMQProtocolWriter, Proto * * @return The method registry for a specific version of the AMQP. */ -// public VersionSpecificRegistry getRegistry(); MethodRegistry getMethodRegistry(); diff --git a/java/common/src/main/java/org/apache/qpid/thread/Threading.java b/java/common/src/main/java/org/apache/qpid/thread/Threading.java index 603e8a7441..265b336157 100644 --- a/java/common/src/main/java/org/apache/qpid/thread/Threading.java +++ b/java/common/src/main/java/org/apache/qpid/thread/Threading.java @@ -24,7 +24,11 @@ package org.apache.qpid.thread; public final class Threading { private static ThreadFactory threadFactory; - + + private Threading() + { + } + static { try { diff --git a/java/common/src/main/java/org/apache/qpid/transport/RangeSetFactory.java b/java/common/src/main/java/org/apache/qpid/transport/RangeSetFactory.java index 0f19d7e2b2..0f049aba8e 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/RangeSetFactory.java +++ b/java/common/src/main/java/org/apache/qpid/transport/RangeSetFactory.java @@ -22,6 +22,10 @@ package org.apache.qpid.transport; public class RangeSetFactory { + private RangeSetFactory() + { + } + public static RangeSet createRangeSet() { return new RangeSetImpl(); diff --git a/java/common/src/main/java/org/apache/qpid/transport/Session.java b/java/common/src/main/java/org/apache/qpid/transport/Session.java index 6784bc2279..d450746eaa 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/Session.java +++ b/java/common/src/main/java/org/apache/qpid/transport/Session.java @@ -410,7 +410,6 @@ public class Session extends SessionInvoker log.debug("ID: [%s] %s", this.channel, id); } - //if ((id % 65536) == 0) if ((id & 0xff) == 0) { flushProcessed(TIMELY_REPLY); diff --git a/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractDecoder.java b/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractDecoder.java index 8ac8093645..27fce6e167 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractDecoder.java +++ b/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractDecoder.java @@ -361,13 +361,13 @@ abstract class AbstractDecoder implements Decoder private long readSize(Type t) { - if (t.fixed) + if (t.isFixed()) { - return t.width; + return t.getWidth(); } else { - return readSize(t.width); + return readSize(t.getWidth()); } } diff --git a/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractEncoder.java b/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractEncoder.java index 5e0207c979..a38c83d4cb 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractEncoder.java +++ b/java/common/src/main/java/org/apache/qpid/transport/codec/AbstractEncoder.java @@ -359,7 +359,7 @@ abstract class AbstractEncoder implements Encoder Object value = entry.getValue(); Type type = encoding(value); writeStr8(key); - put(type.code); + put(type.getCode()); write(type, value); } } @@ -380,7 +380,7 @@ abstract class AbstractEncoder implements Encoder for (Object value : list) { Type type = encoding(value); - put(type.code); + put(type.getCode()); write(type, value); } } @@ -408,7 +408,7 @@ abstract class AbstractEncoder implements Encoder type = encoding(array.get(0)); } - put(type.code); + put(type.getCode()); writeUint32(array.size()); @@ -420,18 +420,18 @@ abstract class AbstractEncoder implements Encoder private void writeSize(Type t, int size) { - if (t.fixed) + if (t.isFixed()) { - if (size != t.width) + if (size != t.getWidth()) { throw new IllegalArgumentException - ("size does not match fixed width " + t.width + ": " + + ("size does not match fixed width " + t.getWidth() + ": " + size); } } else { - writeSize(t.width, size); + writeSize(t.getWidth(), size); } } diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/Transport.java b/java/common/src/main/java/org/apache/qpid/transport/network/Transport.java index 6a6a2b75d1..55ba95ad75 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/network/Transport.java +++ b/java/common/src/main/java/org/apache/qpid/transport/network/Transport.java @@ -54,6 +54,10 @@ public class Transport OUTGOING_PROTOCOL_TO_IMPLDEFAULTS_MAP = Collections.unmodifiableMap(map); } + private Transport() + { + } + public static IncomingNetworkTransport getIncomingTransportInstance() { return (IncomingNetworkTransport) loadTransportClass( diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/SecurityLayerFactory.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/SecurityLayerFactory.java index 6388762026..d51491862b 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/network/security/SecurityLayerFactory.java +++ b/java/common/src/main/java/org/apache/qpid/transport/network/security/SecurityLayerFactory.java @@ -37,6 +37,10 @@ import java.nio.ByteBuffer; public class SecurityLayerFactory { + private SecurityLayerFactory() + { + } + public static SecurityLayer newInstance(ConnectionSettings settings) { diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLEncryptor.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLEncryptor.java index 6c615c05b6..625e1a77c2 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLEncryptor.java +++ b/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLEncryptor.java @@ -30,10 +30,10 @@ import javax.security.sasl.SaslClient; public abstract class SASLEncryptor implements ConnectionListener { - protected SaslClient saslClient; - protected boolean securityLayerEstablished = false; - protected int sendBuffSize; - protected int recvBuffSize; + private SaslClient saslClient; + private boolean securityLayerEstablished = false; + private int sendBuffSize; + private int recvBuffSize; public boolean isSecurityLayerEstablished() { @@ -61,4 +61,19 @@ public abstract class SASLEncryptor implements ConnectionListener public void closed(Connection conn) {} public abstract void securityLayerEstablished(); + + public SaslClient getSaslClient() + { + return saslClient; + } + + public int getSendBuffSize() + { + return sendBuffSize; + } + + public int getRecvBuffSize() + { + return recvBuffSize; + } } diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLReceiver.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLReceiver.java index a9321fbec1..a100b96412 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLReceiver.java +++ b/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLReceiver.java @@ -56,11 +56,11 @@ public class SASLReceiver extends SASLEncryptor implements Receiver<ByteBuffer> { while (buf.hasRemaining()) { - int length = Math.min(buf.remaining(),recvBuffSize); + int length = Math.min(buf.remaining(), getRecvBuffSize()); buf.get(netData, 0, length); try { - byte[] out = saslClient.unwrap(netData, 0, length); + byte[] out = getSaslClient().unwrap(netData, 0, length); delegate.received(ByteBuffer.wrap(out)); } catch (SaslException e) @@ -77,7 +77,7 @@ public class SASLReceiver extends SASLEncryptor implements Receiver<ByteBuffer> public void securityLayerEstablished() { - netData = new byte[recvBuffSize]; + netData = new byte[getRecvBuffSize()]; log.debug("SASL Security Layer Established"); } diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLSender.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLSender.java index ce80f32eb8..61d54a8386 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLSender.java +++ b/java/common/src/main/java/org/apache/qpid/transport/network/security/sasl/SASLSender.java @@ -31,7 +31,7 @@ import java.util.concurrent.atomic.AtomicBoolean; public class SASLSender extends SASLEncryptor implements Sender<ByteBuffer> { - protected Sender<ByteBuffer> delegate; + private Sender<ByteBuffer> delegate; private byte[] appData; private final AtomicBoolean closed = new AtomicBoolean(false); private static final Logger log = Logger.get(SASLSender.class); @@ -52,7 +52,7 @@ public class SASLSender extends SASLEncryptor implements Sender<ByteBuffer> { { try { - saslClient.dispose(); + getSaslClient().dispose(); } catch (SaslException e) { @@ -78,14 +78,14 @@ public class SASLSender extends SASLEncryptor implements Sender<ByteBuffer> { { while (buf.hasRemaining()) { - int length = Math.min(buf.remaining(),sendBuffSize); - log.debug("sendBuffSize %s", sendBuffSize); + int length = Math.min(buf.remaining(), getSendBuffSize()); + log.debug("sendBuffSize %s", getSendBuffSize()); log.debug("buf.remaining() %s", buf.remaining()); buf.get(appData, 0, length); try { - byte[] out = saslClient.wrap(appData, 0, length); + byte[] out = getSaslClient().wrap(appData, 0, length); log.debug("out.length %s", out.length); delegate.send(ByteBuffer.wrap(out)); @@ -110,7 +110,7 @@ public class SASLSender extends SASLEncryptor implements Sender<ByteBuffer> { public void securityLayerEstablished() { - appData = new byte[sendBuffSize]; + appData = new byte[getSendBuffSize()]; log.debug("SASL Security Layer Established"); } diff --git a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLUtil.java b/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLUtil.java index 8f01719935..71a73db71f 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLUtil.java +++ b/java/common/src/main/java/org/apache/qpid/transport/network/security/ssl/SSLUtil.java @@ -38,7 +38,11 @@ import java.security.cert.X509Certificate; public class SSLUtil { private static final Logger log = Logger.get(SSLUtil.class); - + + private SSLUtil() + { + } + public static void verifyHostname(SSLEngine engine,String hostnameExpected) { try diff --git a/java/common/src/main/java/org/apache/qpid/transport/util/Functions.java b/java/common/src/main/java/org/apache/qpid/transport/util/Functions.java index d76d0e249f..bd3e9bbcbc 100644 --- a/java/common/src/main/java/org/apache/qpid/transport/util/Functions.java +++ b/java/common/src/main/java/org/apache/qpid/transport/util/Functions.java @@ -31,8 +31,11 @@ import static java.lang.Math.min; * @author Rafael H. Schloming */ -public class Functions +public final class Functions { + private Functions() + { + } public static final int mod(int n, int m) { diff --git a/java/common/src/main/java/org/apache/qpid/url/BindingURLParser.java b/java/common/src/main/java/org/apache/qpid/url/BindingURLParser.java index 6da468d1b8..fe7b01761b 100644 --- a/java/common/src/main/java/org/apache/qpid/url/BindingURLParser.java +++ b/java/common/src/main/java/org/apache/qpid/url/BindingURLParser.java @@ -184,7 +184,7 @@ public class BindingURLParser char nextChar = _url[_index]; // check for the following special cases. - // "myQueue?durable='true'" or just "myQueue"; + // "myQueue?durable='true'" or just "myQueue" StringBuilder builder = new StringBuilder(); while (nextChar != COLON_CHAR && nextChar != QUESTION_MARK_CHAR && nextChar != END_OF_URL_MARKER_CHAR) diff --git a/java/common/src/main/java/org/apache/qpid/url/URLHelper.java b/java/common/src/main/java/org/apache/qpid/url/URLHelper.java index 94d97d3023..8516e7fa0e 100644 --- a/java/common/src/main/java/org/apache/qpid/url/URLHelper.java +++ b/java/common/src/main/java/org/apache/qpid/url/URLHelper.java @@ -28,6 +28,10 @@ public class URLHelper public static final char ALTERNATIVE_OPTION_SEPARATOR = ','; public static final char BROKER_SEPARATOR = ';'; + private URLHelper() + { + } + public static void parseOptions(Map<String, String> optionMap, String options) throws URLSyntaxException { if ((options == null) || (options.indexOf('=') == -1)) diff --git a/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java b/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java index e4cebb6926..3d17bbf6ea 100644 --- a/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java +++ b/java/common/src/main/java/org/apache/qpid/util/CommandLineParser.java @@ -329,9 +329,6 @@ public class CommandLineParser expectingArgs = true; optionExpectingArgs = matchedOption; - // In the mean time set this options argument to the empty string in case no argument is ever - // supplied. - // options.put(matchedOption, ""); } // Check if the option was matched on its own and is a flag in which case set that flag. diff --git a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java b/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java deleted file mode 100644 index 0f9bd64233..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedMessageQueueAtomicSize.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - * - */ -package org.apache.qpid.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Collection; -import java.util.Iterator; -import java.util.Queue; -import java.util.concurrent.atomic.AtomicInteger; - -public class ConcurrentLinkedMessageQueueAtomicSize<E> extends ConcurrentLinkedQueueAtomicSize<E> implements MessageQueue<E> -{ - private static final Logger _logger = LoggerFactory.getLogger(ConcurrentLinkedMessageQueueAtomicSize.class); - - protected Queue<E> _messageHead = new ConcurrentLinkedQueueAtomicSize<E>(); - - protected AtomicInteger _messageHeadSize = new AtomicInteger(0); - - @Override - public int size() - { - return super.size() + _messageHeadSize.get(); - } - - public int headSize() - { - return _messageHeadSize.get(); - } - - @Override - public E poll() - { - if (_messageHead.isEmpty()) - { - return super.poll(); - } - else - { - E e = _messageHead.poll(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Providing item(" + e + ")from message head"); - } - - if (e != null) - { - _messageHeadSize.decrementAndGet(); - } - - return e; - } - } - - @Override - public boolean remove(Object o) - { - - if (_messageHead.isEmpty()) - { - return super.remove(o); - } - else - { - if (_messageHead.remove(o)) - { - _messageHeadSize.decrementAndGet(); - - return true; - } - - return super.remove(o); - } - } - - @Override - public boolean removeAll(Collection<?> c) - { - if (_messageHead.isEmpty()) - { - return super.removeAll(c); - } - else - { - // fixme this is super.removeAll but iterator here doesn't work - // we need to be able to correctly decrement _messageHeadSize - // boolean modified = false; - // Iterator<?> e = iterator(); - // while (e.hasNext()) - // { - // if (c.contains(e.next())) - // { - // e.remove(); - // modified = true; - // _size.decrementAndGet(); - // } - // } - // return modified; - - throw new RuntimeException("Not implemented"); - } - } - - @Override - public boolean isEmpty() - { - return (_messageHead.isEmpty() && super.isEmpty()); - } - - @Override - public void clear() - { - super.clear(); - _messageHead.clear(); - } - - @Override - public boolean contains(Object o) - { - return _messageHead.contains(o) || super.contains(o); - } - - @Override - public boolean containsAll(Collection<?> o) - { - return _messageHead.containsAll(o) || super.containsAll(o); - } - - @Override - public E element() - { - if (_messageHead.isEmpty()) - { - return super.element(); - } - else - { - return _messageHead.element(); - } - } - - @Override - public E peek() - { - if (_messageHead.isEmpty()) - { - return super.peek(); - } - else - { - E o = _messageHead.peek(); - if (_logger.isDebugEnabled()) - { - _logger.debug("Peeking item (" + o + ") from message head"); - } - - return o; - } - - } - - @Override - public Iterator<E> iterator() - { - final Iterator<E> mainMessageIterator = super.iterator(); - - return new Iterator<E>() - { - private final Iterator<E> _headIterator = _messageHead.iterator(); - private final Iterator<E> _mainIterator = mainMessageIterator; - - private Iterator<E> last; - - public boolean hasNext() - { - return _headIterator.hasNext() || _mainIterator.hasNext(); - } - - public E next() - { - if (_headIterator.hasNext()) - { - last = _headIterator; - - return _headIterator.next(); - } - else - { - last = _mainIterator; - - return _mainIterator.next(); - } - } - - public void remove() - { - last.remove(); - if(last == _mainIterator) - { - decrementSize(); - } - else - { - _messageHeadSize.decrementAndGet(); - } - } - }; - } - - @Override - public boolean retainAll(Collection<?> c) - { - throw new RuntimeException("Not Implemented"); - } - - @Override - public Object[] toArray() - { - throw new RuntimeException("Not Implemented"); - } - - public boolean pushHead(E o) - { - if (_logger.isDebugEnabled()) - { - _logger.debug("Adding item(" + o + ") to head of queue"); - } - - if (_messageHead.offer(o)) - { - _messageHeadSize.incrementAndGet(); - - return true; - } - - return false; - } -} diff --git a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java b/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java deleted file mode 100644 index dd91a067b5..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/ConcurrentLinkedQueueAtomicSize.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.util; - -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.atomic.AtomicInteger; - -public class ConcurrentLinkedQueueAtomicSize<E> extends ConcurrentLinkedQueue<E> -{ - private AtomicInteger _size = new AtomicInteger(0); - - public int size() - { - return _size.get(); - } - - protected final void decrementSize() - { - _size.decrementAndGet(); - } - - - - public boolean offer(E o) - { - - if (super.offer(o)) - { - _size.incrementAndGet(); - return true; - } - - return false; - } - - public E poll() - { - E e = super.poll(); - - if (e != null) - { - _size.decrementAndGet(); - } - - return e; - } - - @Override - public boolean remove(Object o) - { - if (super.remove(o)) - { - _size.decrementAndGet(); - return true; - } - - return false; - } -} diff --git a/java/common/src/main/java/org/apache/qpid/util/FileUtils.java b/java/common/src/main/java/org/apache/qpid/util/FileUtils.java index ac8e3da3c2..2d3e321812 100644 --- a/java/common/src/main/java/org/apache/qpid/util/FileUtils.java +++ b/java/common/src/main/java/org/apache/qpid/util/FileUtils.java @@ -46,6 +46,10 @@ import java.util.List; */ public class FileUtils { + private FileUtils() + { + } + /** * Reads a text file as a string. * diff --git a/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java b/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java deleted file mode 100644 index 93266f2486..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/PrettyPrintingUtils.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.util; - -/** - * Contains pretty printing convenienve methods for producing formatted logging output, mostly for debugging purposes. - * - * <p><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * </table> - * - * @todo Drop this. There are already array pretty printing methods it java.utils.Arrays. - */ -public class PrettyPrintingUtils -{ - /** - * Pretty prints an array of ints as a string. - * - * @param array The array to pretty print. - * - * @return The pretty printed string. - */ - public static String printArray(int[] array) - { - StringBuilder result = new StringBuilder("["); - for (int i = 0; i < array.length; i++) - { - result.append(array[i]) - .append((i < (array.length - 1)) ? ", " : ""); - } - - result.append(']'); - - return result.toString(); - } - - /** - * Pretty prints an array of strings as a string. - * - * @param array The array to pretty print. - * - * @return The pretty printed string. - */ - public static String printArray(String[] array) - { - String result = "["; - for (int i = 0; i < array.length; i++) - { - result += array[i]; - result += (i < (array.length - 1)) ? ", " : ""; - } - - result += "]"; - - return result; - } -} diff --git a/java/common/src/main/java/org/apache/qpid/util/Serial.java b/java/common/src/main/java/org/apache/qpid/util/Serial.java index 7961e4ba3c..451d5d60eb 100644 --- a/java/common/src/main/java/org/apache/qpid/util/Serial.java +++ b/java/common/src/main/java/org/apache/qpid/util/Serial.java @@ -30,6 +30,9 @@ import java.util.Comparator; public class Serial { + private Serial() + { + } public static final Comparator<Integer> COMPARATOR = new Comparator<Integer>() { diff --git a/java/common/src/main/java/org/apache/qpid/util/Strings.java b/java/common/src/main/java/org/apache/qpid/util/Strings.java index da3aab3192..f2d51ccfde 100644 --- a/java/common/src/main/java/org/apache/qpid/util/Strings.java +++ b/java/common/src/main/java/org/apache/qpid/util/Strings.java @@ -36,6 +36,9 @@ import java.util.regex.Pattern; public final class Strings { + private Strings() + { + } private static final byte[] EMPTY = new byte[0]; diff --git a/java/common/src/main/java/org/apache/qpid/util/UUIDs.java b/java/common/src/main/java/org/apache/qpid/util/UUIDs.java index 4bf6b7f0a2..d9b2dd8413 100644 --- a/java/common/src/main/java/org/apache/qpid/util/UUIDs.java +++ b/java/common/src/main/java/org/apache/qpid/util/UUIDs.java @@ -28,6 +28,9 @@ package org.apache.qpid.util; public final class UUIDs { + private UUIDs() + { + } public static final UUIDGen newGenerator() { diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java deleted file mode 100644 index e0c0337898..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/AlreadyUnblockedException.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -/** - * Used to signal that a data element and its producer cannot be requeued or sent an error message when using a - * {@link BatchSynchQueue} because the producer has already been unblocked by an unblocking take on the queue. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Signal that an unblocking take has already occurred. - * </table> - */ -public class AlreadyUnblockedException extends RuntimeException -{ } diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java deleted file mode 100644 index 63d8f77edb..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueue.java +++ /dev/null @@ -1,122 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -import java.util.Collection; -import java.util.concurrent.BlockingQueue; - -/** - * BatchSynchQueue is an abstraction of the classic producer/consumer buffer pattern for thread interaction. In this - * pattern threads can deposit data onto a buffer whilst other threads take data from the buffer and perform usefull - * work with it. A BatchSynchQueue adds to this the possibility that producers can be blocked until their data is - * consumed or until a consumer chooses to release the producer some time after consuming the data from the queue. - * - * <p>There are a number of possible advantages to using this technique when compared with having the producers - * processing their own data: - * - * <ul> - * <li>Data may be deposited asynchronously in the buffer allowing the producers to continue running.</li> - * <li>Data may be deposited synchronously in the buffer so that producers wait until their data has been processed - * before being allowed to continue.</li> - * <li>Variable rates of production/consumption can be smoothed over by the buffer as it provides space in memory to - * hold data between production and consumption.</li> - * <li>Consumers may be able to batch data as they consume it leading to more efficient consumption over - * individual data item consumption where latency associated with the consume operation can be ammortized. - * For example, it may be possibly to ammortize the cost of a disk seek over many producers.</li> - * <li>Data from seperate threads can be combined together in the buffer, providing a convenient way of spreading work - * amongst many workers and gathering the results together again.</li> - * <li>Different types of queue can be used to hold the buffer, resulting in different processing orders. For example, - * lifo, fifo, priority heap, etc.</li> - * </ul> - * - * <p/>The asynchronous type of producer/consumer buffers is already well supported by the java.util.concurrent package - * (in Java 5) and there is also a synchronous queue implementation available there too. This interface extends the - * blocking queue with some more methods for controlling a synchronous blocking queue. In particular it adds additional - * take methods that can be used to take data from a queue without releasing producers, so that consumers have an - * opportunity to confirm correct processing of the data before producers are released. It also adds a put method with - * exceptions so that consumers can signal exception cases back to producers where there are errors in the data. - * - * <p/>This type of queue is usefull in situations where consumers can obtain an efficiency gain by batching data - * from many threads but where synchronous handling of that data is neccessary because producers need to know that - * their data has been processed before they continue. For example, sending a bundle of messages together, or writing - * many records to disk at once, may result in improved performance but the originators of the messages or disk records - * need confirmation that their data has really been sent or saved to disk. - * - * <p/>The consumer can put an element back onto the queue or send an error message to the elements producer using the - * {@link SynchRecord} interface. - * - * <p/>The {@link #take()}, {@link #drainTo(java.util.Collection<? super E>)} and - * {@link #drainTo(java.util.Collection<? super E>, int)} methods from {@link BlockingQueue} should behave as if they - * have been called with unblock set to false. That is they take elements from the queue but leave the producers - * blocked. These methods do not return collections of {@link SynchRecord}s so they do not supply an interface through - * which errors or re-queuings can be applied. If these methods are used then the consumer must succesfully process - * all the records it takes. - * - * <p/>The {@link #put} method should silently swallow any exceptions that consumers attempt to return to the caller. - * In order to handle exceptions the {@link #tryPut} method must be used. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Handle synchronous puts, with possible exceptions. - * <tr><td> Allow consumers to take many records from a queue in a batch. - * <tr><td> Allow consumers to decide when to unblock synchronous producers. - * </table> - */ -public interface BatchSynchQueue<E> extends BlockingQueue<E> -{ - /** - * Tries a synchronous put into the queue. If a consumer encounters an exception condition whilst processing the - * data that is put, then this is returned to the caller wrapped inside a {@link SynchException}. - * - * @param e The data element to put into the queue. - * - * @throws InterruptedException If the thread is interrupted whilst waiting to write to the queue or whilst waiting - * on its entry in the queue being consumed. - * @throws SynchException If a consumer encounters an error whilst processing the data element. - */ - public void tryPut(E e) throws InterruptedException, SynchException; - - /** - * Takes all available data items from the queue or blocks until some become available. The returned items - * are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their - * producers, where the producers are still blocked. - * - * @param c The collection to drain the data items into. - * @param unblock If set to <tt>true</tt> the producers for the taken items will be immediately unblocked. - * - * @return A count of the number of elements that were drained from the queue. - */ - public SynchRef drainTo(Collection<SynchRecord<E>> c, boolean unblock); - - /** - * Takes up to maxElements available data items from the queue or blocks until some become available. The returned - * items are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their - * producers, where the producers are still blocked. - * - * @param c The collection to drain the data items into. - * @param maxElements The maximum number of elements to drain. - * @param unblock If set to <tt>true</tt> the producers for the taken items will be immediately unblocked. - * - * @return A count of the number of elements that were drained from the queue. - */ - public SynchRef drainTo(Collection<SynchRecord<E>> c, int maxElements, boolean unblock); -} diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java deleted file mode 100644 index 1d5f3b5e46..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/BatchSynchQueueBase.java +++ /dev/null @@ -1,837 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.AbstractQueue; -import java.util.Collection; -import java.util.Iterator; -import java.util.Queue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.ReentrantLock; - - -/** - * Synchronous/Asynchronous puts. Asynchronous is easiest, just wait till can write to queue and deposit data. - * Synchronous is harder. Deposit data, but then must wait until deposited element/elements are taken before being - * allowed to unblock and continue. Consumer needs some options here too. Can just get the data from the buffer and - * allow any producers unblocked as a result to continue, or can get data but continue blocking while the data is - * processed before sending a message to do the unblocking. Synch/Asynch mode to be controlled by a switch. - * Unblocking/not unblocking during consumer processing to be controlled by the consumers calls. - * - * <p/>Implementing sub-classes only need to supply an implementation of a queue to produce a valid concrete - * implementation of this. This queue is only accessed through the methods {@link #insert}, {@link #extract}, - * {@link #getBufferCapacity()}, {@link #peekAtBufferHead()}. An implementation can override these methods to implement - * the buffer other than by a queue, for example, by using an array. - * - * <p/>Normal queue methods to work asynchronously. - * <p/>Put, take and drain methods from the BlockingQueue interface work synchronously but unblock producers immediately - * when their data is taken. - * <p/>The additional put, take and drain methods from the BatchSynchQueue interface work synchronously and provide the - * option to keep producers blocked until the consumer decides to release them. - * - * <p/>Removed take method that keeps producers blocked as it is pointless. Essentially it reduces this class to - * synchronous processing of individual data items, which negates the point of the hand-off design. The efficiency - * gain of the hand off design comes in being able to batch consume requests, ammortizing latency (such as caused by io) - * accross many producers. The only advantage of the single blocking take method is that it did take advantage of the - * queue ordering, which ma be usefull, for example to apply a priority ordering amongst producers. This is also an - * advantage over the java.util.concurrent.SynchronousQueue which doesn't have a backing queue which can be used to - * apply orderings. If a single item take is really needed can just use the drainTo method with a maximum of one item. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * </table> - */ -public abstract class BatchSynchQueueBase<E> extends AbstractQueue<E> implements BatchSynchQueue<E> -{ - /** Used for logging. */ - private static final Logger log = LoggerFactory.getLogger(BatchSynchQueueBase.class); - - /** Holds a reference to the queue implementation that holds the buffer. */ - private Queue<SynchRecordImpl<E>> buffer; - - /** Holds the number of items in the queue */ - private int count; - - /** Main lock guarding all access */ - private ReentrantLock lock; - - /** Condition for waiting takes */ - private Condition notEmpty; - - /** Condition for waiting puts */ - private Condition notFull; - - /** - * Creates a batch synch queue without fair thread scheduling. - */ - public BatchSynchQueueBase() - { - this(false); - } - - /** - * Ensures that the underlying buffer implementation is created. - * - * @param fair <tt>true</tt> if fairness is to be applied to threads waiting to access the buffer. - */ - public BatchSynchQueueBase(boolean fair) - { - buffer = this.createQueue(); - - // Create the buffer lock with the fairness flag set accordingly. - lock = new ReentrantLock(fair); - - // Create the non-empty and non-full condition monitors on the buffer lock. - notEmpty = lock.newCondition(); - notFull = lock.newCondition(); - } - - /** - * Returns an iterator over the elements contained in this collection. - * - * @return An iterator over the elements contained in this collection. - */ - public Iterator<E> iterator() - { - throw new RuntimeException("Not implemented."); - } - - /** - * Returns the number of elements in this collection. If the collection contains more than - * <tt>Integer.MAX_VALUE</tt> elements, returns <tt>Integer.MAX_VALUE</tt>. - * - * @return The number of elements in this collection. - */ - public int size() - { - final ReentrantLock lock = this.lock; - lock.lock(); - - try - { - return count; - } - finally - { - lock.unlock(); - } - } - - /** - * Inserts the specified element into this queue, if possible. When using queues that may impose insertion - * restrictions (for example capacity bounds), method <tt>offer</tt> is generally preferable to method - * {@link java.util.Collection#add}, which can fail to insert an element only by throwing an exception. - * - * @param e The element to insert. - * - * @return <tt>true</tt> if it was possible to add the element to this queue, else <tt>false</tt> - */ - public boolean offer(E e) - { - if (e == null) - { - throw new NullPointerException(); - } - - final ReentrantLock lock = this.lock; - lock.lock(); - - try - { - return insert(e, false); - } - finally - { - lock.unlock(); - } - } - - /** - * Inserts the specified element into this queue, waiting if necessary up to the specified wait time for space to - * become available. - * - * @param e The element to add. - * @param timeout How long to wait before giving up, in units of <tt>unit</tt> - * @param unit A <tt>TimeUnit</tt> determining how to interpret the <tt>timeout</tt> parameter. - * - * @return <tt>true</tt> if successful, or <tt>false</tt> if the specified waiting time elapses before space is - * available. - * - * @throws InterruptedException If interrupted while waiting. - * @throws NullPointerException If the specified element is <tt>null</tt>. - */ - public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException - { - if (e == null) - { - throw new NullPointerException(); - } - - final ReentrantLock lock = this.lock; - lock.lockInterruptibly(); - - long nanos = unit.toNanos(timeout); - - try - { - do - { - if (insert(e, false)) - { - return true; - } - - try - { - nanos = notFull.awaitNanos(nanos); - } - catch (InterruptedException ie) - { - notFull.signal(); // propagate to non-interrupted thread - throw ie; - } - } - while (nanos > 0); - - return false; - } - finally - { - lock.unlock(); - } - } - - /** - * Retrieves and removes the head of this queue, or <tt>null</tt> if this queue is empty. - * - * @return The head of this queue, or <tt>null</tt> if this queue is empty. - */ - public E poll() - { - final ReentrantLock lock = this.lock; - - lock.lock(); - try - { - if (count == 0) - { - return null; - } - - E x = extract(true, true).getElement(); - - return x; - } - finally - { - lock.unlock(); - } - } - - /** - * Retrieves and removes the head of this queue, waiting if necessary up to the specified wait time if no elements - * are present on this queue. - * - * @param timeout How long to wait before giving up, in units of <tt>unit</tt>. - * @param unit A <tt>TimeUnit</tt> determining how to interpret the <tt>timeout</tt> parameter. - * - * @return The head of this queue, or <tt>null</tt> if the specified waiting time elapses before an element is present. - * - * @throws InterruptedException If interrupted while waiting. - */ - public E poll(long timeout, TimeUnit unit) throws InterruptedException - { - final ReentrantLock lock = this.lock; - lock.lockInterruptibly(); - try - { - long nanos = unit.toNanos(timeout); - - do - { - if (count != 0) - { - E x = extract(true, true).getElement(); - - return x; - } - - try - { - nanos = notEmpty.awaitNanos(nanos); - } - catch (InterruptedException ie) - { - notEmpty.signal(); // propagate to non-interrupted thread - throw ie; - } - } - while (nanos > 0); - - return null; - } - finally - { - lock.unlock(); - } - } - - /** - * Retrieves, but does not remove, the head of this queue, returning <tt>null</tt> if this queue is empty. - * - * @return The head of this queue, or <tt>null</tt> if this queue is empty. - */ - public E peek() - { - final ReentrantLock lock = this.lock; - lock.lock(); - - try - { - return peekAtBufferHead(); - } - finally - { - lock.unlock(); - } - } - - /** - * Returns the number of elements that this queue can ideally (in the absence of memory or resource constraints) - * accept without blocking, or <tt>Integer.MAX_VALUE</tt> if there is no intrinsic limit. - * - * <p>Note that you <em>cannot</em> always tell if an attempt to <tt>add</tt> an element will succeed by - * inspecting <tt>remainingCapacity</tt> because it may be the case that another thread is about to <tt>put</tt> - * or <tt>take</tt> an element. - * - * @return The remaining capacity. - */ - public int remainingCapacity() - { - final ReentrantLock lock = this.lock; - lock.lock(); - - try - { - return getBufferCapacity() - count; - } - finally - { - lock.unlock(); - } - } - - /** - * Adds the specified element to this queue, waiting if necessary for space to become available. - * - * <p/>This method delegated to {@link #tryPut} which can raise {@link SynchException}s. If any are raised - * this method silently ignores them. Use the {@link #tryPut} method directly if you want to catch these - * exceptions. - * - * @param e The element to add. - * - * @throws InterruptedException If interrupted while waiting. - */ - public void put(E e) throws InterruptedException - { - try - { - tryPut(e); - } - catch (SynchException ex) - { - // This exception is deliberately ignored. See the method comment for information about this. - } - } - - /** - * Tries a synchronous put into the queue. If a consumer encounters an exception condition whilst processing the - * data that is put, then this is returned to the caller wrapped inside a {@link SynchException}. - * - * @param e The data element to put into the queue. Cannot be null. - * - * @throws InterruptedException If the thread is interrupted whilst waiting to write to the queue or whilst waiting - * on its entry in the queue being consumed. - * @throws SynchException If a consumer encounters an error whilst processing the data element. - */ - public void tryPut(E e) throws InterruptedException, SynchException - { - if (e == null) - { - throw new NullPointerException(); - } - - // final Queue<E> items = this.buffer; - final ReentrantLock lock = this.lock; - lock.lockInterruptibly(); - - try - { - while (count == getBufferCapacity()) - { - // Release the lock and wait until the queue is not full. - notFull.await(); - } - } - catch (InterruptedException ie) - { - notFull.signal(); // propagate to non-interrupted thread - throw ie; - } - - // There is room in the queue so insert must succeed. Insert into the queu, release the lock and block - // the producer until its data is taken. - insert(e, true); - } - - /** - * Retrieves and removes the head of this queue, waiting if no elements are present on this queue. - * Any producer that has its data element taken by this call will be immediately unblocked. To keep the - * producer blocked whilst taking just a single item, use the - * {@link #drainTo(java.util.Collection<org.apache.qpid.util.concurrent.SynchRecord<E>>, int, boolean)} - * method. There is no take method to do that because there is not usually any advantage in a synchronous hand - * off design that consumes data one item at a time. It is normal to consume data in chunks to ammortize consumption - * latencies accross many producers where possible. - * - * @return The head of this queue. - * - * @throws InterruptedException if interrupted while waiting. - */ - public E take() throws InterruptedException - { - final ReentrantLock lock = this.lock; - lock.lockInterruptibly(); - - try - { - try - { - while (count == 0) - { - // Release the lock and wait until the queue becomes non-empty. - notEmpty.await(); - } - } - catch (InterruptedException ie) - { - notEmpty.signal(); // propagate to non-interrupted thread - throw ie; - } - - // There is data in the queue so extraction must succeed. Notify any waiting threads that the queue is - // not full, and unblock the producer that owns the data item that is taken. - E x = extract(true, true).getElement(); - - return x; - } - finally - { - lock.unlock(); - } - } - - /** - * Removes all available elements from this queue and adds them into the given collection. This operation may be - * more efficient than repeatedly polling this queue. A failure encountered while attempting to <tt>add</tt> elements - * to collection <tt>c</tt> may result in elements being in neither, either or both collections when the associated - * exception is thrown. Attempts to drain a queue to itself result in <tt>IllegalArgumentException</tt>. Further, - * the behavior of this operation is undefined if the specified collection is modified while the operation is in - * progress. - * - * @param objects The collection to transfer elements into. - * - * @return The number of elements transferred. - * - * @throws NullPointerException If objects is null. - * @throws IllegalArgumentException If objects is this queue. - */ - public int drainTo(Collection<? super E> objects) - { - return drainTo(objects, -1); - } - - /** - * Removes at most the given number of available elements from this queue and adds them into the given collection. - * A failure encountered while attempting to <tt>add</tt> elements to collection <tt>c</tt> may result in elements - * being in neither, either or both collections when the associated exception is thrown. Attempts to drain a queue - * to itself result in <tt>IllegalArgumentException</tt>. Further, the behavior of this operation is undefined if - * the specified collection is modified while the operation is in progress. - * - * @param objects The collection to transfer elements into. - * @param maxElements The maximum number of elements to transfer. If this is -1 then that is interpreted as meaning - * all elements. - * - * @return The number of elements transferred. - * - * @throws NullPointerException If c is null. - * @throws IllegalArgumentException If c is this queue. - */ - public int drainTo(Collection<? super E> objects, int maxElements) - { - if (objects == null) - { - throw new NullPointerException(); - } - - if (objects == this) - { - throw new IllegalArgumentException(); - } - - // final Queue<E> items = this.buffer; - final ReentrantLock lock = this.lock; - lock.lock(); - - try - { - int n = 0; - - for (int max = ((maxElements >= count) || (maxElements < 0)) ? count : maxElements; n < max; n++) - { - // Take items from the queue, do unblock the producers, but don't send not full signals yet. - objects.add(extract(true, false).getElement()); - } - - if (n > 0) - { - // count -= n; - notFull.signalAll(); - } - - return n; - } - finally - { - lock.unlock(); - } - } - - /** - * Takes all available data items from the queue or blocks until some become available. The returned items - * are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their - * producers, where the producers are still blocked. - * - * @param c The collection to drain the data items into. - * @param unblock If set to <tt>true</tt> the producers for the taken items will be immediately unblocked. - * - * @return A count of the number of elements that were drained from the queue. - */ - public SynchRef drainTo(Collection<SynchRecord<E>> c, boolean unblock) - { - return drainTo(c, -1, unblock); - } - - /** - * Takes up to maxElements available data items from the queue or blocks until some become available. The returned - * items are wrapped in a {@link SynchRecord} which provides an interface to requeue them or send errors to their - * producers, where the producers are still blocked. - * - * @param coll The collection to drain the data items into. - * @param maxElements The maximum number of elements to drain. - * @param unblock If set to <tt>true</tt> the producers for the taken items will be immediately unblocked. - * - * @return A count of the number of elements that were drained from the queue. - */ - public SynchRef drainTo(Collection<SynchRecord<E>> coll, int maxElements, boolean unblock) - { - if (coll == null) - { - throw new NullPointerException(); - } - - // final Queue<E> items = this.buffer; - final ReentrantLock lock = this.lock; - lock.lock(); - - try - { - int n = 0; - - for (int max = ((maxElements >= count) || (maxElements < 0)) ? count : maxElements; n < max; n++) - { - // Extract the next record from the queue, don't signall the not full condition yet and release - // producers depending on whether the caller wants to or not. - coll.add(extract(false, unblock)); - } - - if (n > 0) - { - // count -= n; - notFull.signalAll(); - } - - return new SynchRefImpl(n, coll); - } - finally - { - lock.unlock(); - } - } - - /** - * This abstract method should be overriden to return an empty queue. Different implementations of producer - * consumer buffers can control the order in which data is accessed using different queue implementations. - * This method allows the type of queue to be abstracted out of this class and to be supplied by concrete - * implementations. - * - * @return An empty queue. - */ - protected abstract <T> Queue<T> createQueue(); - - /** - * Insert element into the queue, then possibly signal that the queue is not empty and block the producer - * on the element until permission to procede is given. - * - * <p/>If the producer is to be blocked then the lock must be released first, otherwise no other process - * will be able to get access to the queue. Hence, unlock and block are always set together. - * - * <p/>Call only when holding the global lock. - * - * @param unlockAndBlock <tt>true</tt>If the global queue lock should be released and the producer should be blocked. - * - * @return <tt>true</tt> if the operation succeeded, <tt>false</tt> otherwise. If the result is <tt>true</tt> this - * method may not return straight away, but only after the producer is unblocked by having its data - * consumed if the unlockAndBlock flag is set. In the false case the method will return straight away, no - * matter what value the unlockAndBlock flag has, leaving the global lock on. - */ - protected boolean insert(E x, boolean unlockAndBlock) - { - // Create a new record for the data item. - SynchRecordImpl<E> record = new SynchRecordImpl<E>(x); - - boolean result = buffer.offer(record); - - if (result) - { - count++; - - // Tell any waiting consumers that the queue is not empty. - notEmpty.signal(); - - if (unlockAndBlock) - { - // Allow other threads to read/write the queue. - lock.unlock(); - - // Wait until a consumer takes this data item. - record.waitForConsumer(); - } - - return true; - } - else - { - return false; - } - } - - /** - * Extract element at current take position, advance, and signal. - * - * <p/>Call only when holding lock. - */ - protected SynchRecordImpl<E> extract(boolean unblock, boolean signal) - { - SynchRecordImpl<E> result = buffer.remove(); - count--; - - if (signal) - { - notFull.signal(); - } - - if (unblock) - { - result.releaseImmediately(); - } - - return result; - } - - /** - * Get the capacity of the buffer. If the buffer has no maximum capacity then Integer.MAX_VALUE is returned. - * - * <p/>Call only when holding lock. - * - * @return The maximum capacity of the buffer. - */ - protected int getBufferCapacity() - { - if (buffer instanceof Capacity) - { - return ((Capacity) buffer).getCapacity(); - } - else - { - return Integer.MAX_VALUE; - } - } - - /** - * Return the head element from the buffer. - * - * <p/>Call only when holding lock. - * - * @return The head element from the buffer. - */ - protected E peekAtBufferHead() - { - return buffer.peek().getElement(); - } - - public class SynchRefImpl implements SynchRef - { - /** Holds the number of synch records associated with this reference. */ - private int numRecords; - - /** Holds a reference to the collection of synch records managed by this. */ - private Collection<SynchRecord<E>> records; - - public SynchRefImpl(int n, Collection<SynchRecord<E>> records) - { - this.numRecords = n; - this.records = records; - } - - public int getNumRecords() - { - return numRecords; - } - - /** - * Any producers that have had their data elements taken from the queue but have not been unblocked are unblocked - * when this method is called. The exception to this is producers that have had their data put back onto the queue - * by a consumer. Producers that have had exceptions for their data items registered by consumers will be unblocked - * but will not return from their put call normally, but with an exception instead. - */ - public void unblockProducers() - { - log.debug("public void unblockProducers(): called"); - - if (records != null) - { - for (SynchRecord<E> record : records) - { - // This call takes account of items that have already been released, are to be requeued or are in - // error. - record.releaseImmediately(); - } - } - - records = null; - } - } - - /** - * A SynchRecordImpl is used by a {@link BatchSynchQueue} to pair together a producer with its data. This allows - * the producer of data to be identified so that it can be unblocked when its data is consumed or sent errors when - * its data cannot be consumed. - */ - public class SynchRecordImpl<E> implements SynchRecord<E> - { - /** A boolean latch that determines when the producer for this data item will be allowed to continue. */ - private BooleanLatch latch = new BooleanLatch(); - - /** The data element associated with this item. */ - private E element; - - /** - * Create a new synch record. - * - * @param e The data element that the record encapsulates. - */ - public SynchRecordImpl(E e) - { - // Keep the data element. - element = e; - } - - /** - * Waits until the producer is given permission to proceded by a consumer. - */ - public void waitForConsumer() - { - latch.await(); - } - - /** - * Gets the data element contained by this record. - * - * @return The data element contained by this record. - */ - public E getElement() - { - return element; - } - - /** - * Immediately releases the producer of this data record. Consumers can bring the synchronization time of - * producers to a minimum by using this method to release them at the earliest possible moment when batch - * consuming records from sychronized producers. - */ - public void releaseImmediately() - { - // Check that the record has not already been released, is in error or is to be requeued. - latch.signal(); - - // Propagate errors to the producer. - - // Requeue items to be requeued. - } - - /** - * Tells the synch queue to put this element back onto the queue instead of releasing its producer. - * The element is not requeued immediately but upon calling the {@link SynchRef#unblockProducers()} method or - * the {@link #releaseImmediately()} method. - * - * <p/>This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this - * element has already been unblocked. - */ - public void reQueue() - { - throw new RuntimeException("Not implemented."); - } - - /** - * Tells the synch queue to raise an exception with this elements producer. The exception is not raised - * immediately but upon calling the {@link SynchRef#unblockProducers()} method or the - * {@link #releaseImmediately()} method. The exception will be wrapped in a {@link SynchException} before it is - * raised on the producer. - * - * <p/>This method is unusual in that it accepts an exception as an argument. This is non-standard but is used - * because the exception is to be passed onto a different thread. - * - * <p/>This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this - * element has already been unblocked. - * - * @param e The exception to raise on the producer. - */ - public void inError(Exception e) - { - throw new RuntimeException("Not implemented."); - } - } -} diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java deleted file mode 100644 index 0e4a07594f..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/BooleanLatch.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -import java.util.concurrent.locks.AbstractQueuedSynchronizer; - -/** - * A BooleanLatch is like a set of traffic lights, where threads can wait at a red light until another thread gives - * the green light. When threads arrive at the latch it is initially red. They queue up until the green signal is - * given, at which point they can all acquire the latch in shared mode and continue to run concurrently. Once the latch - * is signalled it cannot be reset to red again. - * - * <p/> The latch uses a {@link java.util.concurrent.locks.AbstractQueuedSynchronizer} to implement its synchronization. - * This has two internal states, 0 which means that the latch is blocked, and 1 which means that the latch is open. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Block threads until a go signal is given. - * </table> - * - * @todo Might be better to use a countdown latch to count down from 1. Its await method can throw interrupted - * exception which makes the possibility of interruption more explicit, and provides a reminder to recheck the - * latch condition before continuing. - */ -public class BooleanLatch -{ - /** Holds the synchronizer that provides the thread queueing synchronization. */ - private final Sync sync = new Sync(); - - /** - * Tests whether or not the latch has been signalled, that is to say that, the light is green. - * - * <p/>This method is non-blocking. - * - * @return <tt>true</tt> if the latch may be acquired; the light is green. - */ - public boolean isSignalled() - { - return sync.isSignalled(); - } - - /** - * Waits on the latch until the signal is given and the light is green. If the light is already green then the - * latch will be acquired and the thread will not have to wait. - * - * <p/>This method will block until the go signal is given or the thread is otherwise interrupted. Before carrying - * out any processing threads that return from this method should confirm that the go signal has really been given - * on this latch by calling the {@link #isSignalled()} method. - */ - public void await() - { - sync.acquireShared(1); - } - - /** - * Releases any threads currently waiting on the latch. This flips the light to green allowing any threads that - * were waiting for this condition to now run. - * - * <p/>This method is non-blocking. - */ - public void signal() - { - sync.releaseShared(1); - } - - /** - * Implements a thread queued synchronizer. The internal state 0 means that the queue is blocked and the internl - * state 1 means that the queue is released and that all waiting threads can acquire the synchronizer in shared - * mode. - */ - private static class Sync extends AbstractQueuedSynchronizer - { - /** - * Attempts to acquire this synchronizer in shared mode. It may be acquired once it has been released. - * - * @param ignore This parameter is ignored. - * - * @return 1 if the shared acquisition succeeds and -1 if it fails. - */ - protected int tryAcquireShared(int ignore) - { - return isSignalled() ? 1 : -1; - } - - /** - * Releases the synchronizer, setting its internal state to 1. - * - * @param ignore This parameter is ignored. - * - * @return <tt>true</tt> always. - */ - protected boolean tryReleaseShared(int ignore) - { - setState(1); - - return true; - } - - /** - * Tests if the synchronizer is signalled. It is signalled when its internal state it 1. - * - * @return <tt>true</tt> if the internal state is 1, <tt>false</tt> otherwise. - */ - boolean isSignalled() - { - return getState() != 0; - } - } -} diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java deleted file mode 100644 index a97ce0e172..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/Capacity.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -/** - * An interface exposed by data structures that have a maximum capacity. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Report the maximum capacity. - * </table> - */ -public interface Capacity -{ - public int getCapacity(); -} diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java deleted file mode 100644 index bc63eb0353..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchBuffer.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -import java.util.Queue; - -/** - * SynchBuffer completes the {@link BatchSynchQueueBase} abstract class by providing an implementation of the underlying - * queue as an array. This uses FIFO ordering for the queue but restricts the maximum size of the queue to a fixed - * amount. It also has the advantage that, as the buffer does not grow and shrink dynamically, memory for the buffer - * is allocated up front and does not create garbage during the operation of the queue. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Provide array based FIFO queue to create a batch synched queue around. - * </table> - * - * @todo Write an array based buffer implementation that implements Queue. - */ -public class SynchBuffer<E> extends BatchSynchQueueBase<E> -{ - /** - * Returns an empty queue, implemented as an array. - * - * @return An empty queue, implemented as an array. - */ - protected <T> Queue<T> createQueue() - { - throw new RuntimeException("Not implemented."); - } -} diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java deleted file mode 100644 index 23ee695079..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchException.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -/** - * SynchException is used to encapsulate exceptions with the data elements that caused them in order to send exceptions - * back from the consumers of a {@link BatchSynchQueue} to producers. The underlying exception should be retrieved from - * the {@link #getCause} method. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Encapsulate a data element and exception. - * </table> - */ -public class SynchException extends Exception -{ - /** Holds the data element that is in error. */ - private Object element; - - /** - * Creates a new BaseApplicationException object. - * - * @param message The exception message. - * @param cause The underlying throwable cause. This may be null. - */ - public SynchException(String message, Throwable cause, Object element) - { - super(message, cause); - - // Keep the data element that was in error. - this.element = element; - } -} diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java deleted file mode 100644 index 95833f398a..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchQueue.java +++ /dev/null @@ -1,48 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -import java.util.LinkedList; -import java.util.Queue; - -/** - * SynchQueue completes the {@link BatchSynchQueueBase} abstract class by providing an implementation of the underlying - * queue as a linked list. This uses FIFO ordering for the queue and allows the queue to grow to accomodate more - * elements as needed. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Provide linked list FIFO queue to create a batch synched queue around. - * </table> - */ -public class SynchQueue<E> extends BatchSynchQueueBase<E> -{ - /** - * Returns an empty queue, implemented as a linked list. - * - * @return An empty queue, implemented as a linked list. - */ - protected <T> Queue<T> createQueue() - { - return new LinkedList<T>(); - } -} diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java deleted file mode 100644 index fd740c20cd..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRecord.java +++ /dev/null @@ -1,74 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -/** - * SynchRecord associates a data item from a {@link BatchSynchQueue} with its producer. This enables the data item data - * item to be put back on the queue without unblocking its producer, or to send exceptions to the producer. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities <th> Collaborations - * <tr><td> Get the underlying data element. - * <tr><td> Put the data element back on the queue without unblocking its producer. - * <tr><td> Send and exception to the data elements producer. - * </table> - */ -public interface SynchRecord<E> -{ - /** - * Gets the data element contained by this record. - * - * @return The data element contained by this record. - */ - public E getElement(); - - /** - * Tells the synch queue to put this element back onto the queue instead of releasing its producer. - * The element is not requeued immediately but upon calling the {@link SynchRef#unblockProducers()} method. - * - * <p/>This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this element - * has already been unblocked. - */ - public void reQueue(); - - /** - * Immediately releases the producer of this data record. Consumers can bring the synchronization time of - * producers to a minimum by using this method to release them at the earliest possible moment when batch - * consuming records from sychronized producers. - */ - public void releaseImmediately(); - - /** - * Tells the synch queue to raise an exception with this elements producer. The exception is not raised immediately - * but upon calling the {@link SynchRef#unblockProducers()} method. The exception will be wrapped in a - * {@link SynchException} before it is raised on the producer. - * - * <p/>This method is unusual in that it accepts an exception as an argument. This is non-standard but is used - * because the exception is to be passed onto a different thread. - * - * <p/>This method will raise a runtime exception {@link AlreadyUnblockedException} if the producer for this element - * has already been unblocked. - * - * @param e The exception to raise on the producer. - */ - public void inError(Exception e); -} diff --git a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java b/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java deleted file mode 100644 index efe2344c06..0000000000 --- a/java/common/src/main/java/org/apache/qpid/util/concurrent/SynchRef.java +++ /dev/null @@ -1,51 +0,0 @@ -package org.apache.qpid.util.concurrent; -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - - -/** - * A SynchRef is an interface which is returned from the synchronous take and drain methods of {@link BatchSynchQueue}, - * allowing call-backs to be made against the synchronizing strucutre. It allows the consumer to communicate when it - * wants producers that have their data taken to be unblocked. - * - * <p/><table id="crc"><caption>CRC Card</caption> - * <tr><th> Responsibilities - * <tr><td> Report number of records returned by a taking operation. - * <tr><td> Provide call-back to release producers of taken records. - * </table> - */ -public interface SynchRef -{ - /** - * Reports the number of records taken by the take or drain operation. - * - * @return The number of records taken by the take or drain operation. - */ - public int getNumRecords(); - - /** - * Any producers that have had their data elements taken from the queue but have not been unblocked are - * unblocked when this method is called. The exception to this is producers that have had their data put back - * onto the queue by a consumer. Producers that have had exceptions for their data items registered by consumers - * will be unblocked but will not return from their put call normally, but with an exception instead. - */ - public void unblockProducers(); -} |