You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@qpid.apache.org by rh...@apache.org on 2006/09/20 00:07:25 UTC

svn commit: r447994 [13/46] - in /incubator/qpid/trunk/qpid: ./ cpp/ cpp/bin/ cpp/broker/ cpp/broker/inc/ cpp/broker/src/ cpp/broker/test/ cpp/client/ cpp/client/inc/ cpp/client/src/ cpp/client/test/ cpp/common/ cpp/common/concurrent/ cpp/common/concur...

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,603 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.protocol;
+
+import org.apache.log4j.Logger;
+import org.apache.mina.common.IoSession;
+import org.apache.mina.common.IdleStatus;
+import org.apache.mina.transport.vmpipe.VmPipeAddress;
+import org.apache.qpid.AMQChannelException;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.codec.AMQCodecFactory;
+import org.apache.qpid.codec.AMQDecoder;
+import org.apache.qpid.framing.*;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.RequiredDeliveryException;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.management.DefaultManagedObject;
+import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.state.AMQStateManager;
+
+import javax.security.sasl.SaslServer;
+import javax.management.ObjectName;
+import javax.management.MalformedObjectNameException;
+import javax.management.openmbean.*;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArraySet;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+
+public class AMQMinaProtocolSession implements AMQProtocolSession, ProtocolVersionList
+{
+    private static final Logger _logger = Logger.getLogger(AMQProtocolSession.class);
+
+    private final IoSession _minaProtocolSession;
+
+    private String _contextKey;
+
+    private final Map<Integer, AMQChannel> _channelMap = new HashMap<Integer, AMQChannel>();
+
+    private final CopyOnWriteArraySet<AMQMethodListener> _frameListeners = new CopyOnWriteArraySet<AMQMethodListener>();
+
+    private final AMQStateManager _stateManager;
+
+    private final QueueRegistry _queueRegistry;
+
+    private final ExchangeRegistry _exchangeRegistry;
+
+    private AMQCodecFactory _codecFactory;
+
+    private AMQProtocolSessionMBean _managedObject;
+
+    private SaslServer _saslServer;
+
+    private Object _lastReceived;
+
+    private Object _lastSent;
+
+    private boolean _closed;
+
+    private long _maxNoOfChannels;
+    
+    /* AMQP Version for this session */
+    
+    private byte _major;
+    private byte _minor;
+
+    /**
+     * This class implements the management interface (is an MBean). In order to make more attributes, operations
+     * and notifications available over JMX simply augment the ManagedConnection interface and add the appropriate
+     * implementation here.
+     */
+    private final class AMQProtocolSessionMBean extends DefaultManagedObject implements ManagedConnection
+    {
+        /**
+         * Represents the channel attributes sent with channel data.
+         */
+        private String[] _channelAtttibuteNames = { "ChannelId",
+                                                    "ChannelName",
+                                                    "Transactional",
+                                                    "DefaultQueue"};
+        private String[] _channelAttributeDescriptions = { "Channel Identifier",
+                                                           "Channel Name",
+                                                           "is Channel Transactional?",
+                                                           "Default Queue Name" };
+        private OpenType[] _channelAttributeTypes = { SimpleType.INTEGER,
+                                                      SimpleType.OBJECTNAME,
+                                                      SimpleType.BOOLEAN,
+                                                      SimpleType.STRING };
+        /**
+         * Channels in the list will be indexed according to channelId.
+         */
+        private String[] _indexNames = { "ChannelId" };
+
+        /**
+         * represents the data type for channel data.
+         */
+        private CompositeType _channelType = null;
+        /**
+         * Datatype for list of channelsType.
+         */
+        private TabularType  _channelsType = null;
+
+        private TabularDataSupport _channelsList = null;
+
+        public AMQProtocolSessionMBean()
+        {
+            super(ManagedConnection.class, ManagedConnection.TYPE);
+            init();
+        }
+
+        /**
+         * initialises the CompositeTypes and TabularType attributes.
+         */
+        private void init()
+        {
+            try
+            {
+                _channelType = new CompositeType("channel",
+                                              "a Channel",
+                                              _channelAtttibuteNames,
+                                              _channelAttributeDescriptions,
+                                              _channelAttributeTypes);
+
+                _channelsType = new TabularType("channelsType",
+                                       "List of available channelsType",
+                                       _channelType,
+                                       _indexNames);
+            }
+            catch(OpenDataException ex)
+            {
+                // It should never occur.
+                _logger.error("OpenDataTypes could not be created.", ex);
+                throw new RuntimeException(ex);
+            }
+        }
+
+        public Date getLastIoTime()
+        {
+            return new Date(_minaProtocolSession.getLastIoTime());
+        }
+
+        public String getRemoteAddress()
+        {
+            return _minaProtocolSession.getRemoteAddress().toString();
+        }
+
+        public long getWrittenBytes()
+        {
+            return _minaProtocolSession.getWrittenBytes();
+        }
+
+        public long getReadBytes()
+        {
+            return _minaProtocolSession.getReadBytes();
+        }
+
+        public long getMaximumNumberOfAllowedChannels()
+        {
+            return _maxNoOfChannels;
+        }
+
+        public void setMaximumNumberOfAllowedChannels(long value)
+        {
+            _maxNoOfChannels = value;
+        }
+
+        public String getObjectInstanceName()
+        {
+            String remote = getRemoteAddress();
+            return "anonymous".equals(remote) ? remote + hashCode() : remote;
+        }
+
+        /**
+         * Creates the list of channels in tabular form from the _channelMap.
+         * @return  list of channels in tabular form.
+         * @throws OpenDataException
+         */
+        private TabularData getChannels()
+            throws OpenDataException
+        {
+            _channelsList = new TabularDataSupport(_channelsType);
+
+            for (Map.Entry<Integer, AMQChannel> entry : _channelMap.entrySet())
+            {
+                AMQChannel channel = entry.getValue();
+                ObjectName channelObjectName = null;
+
+                try
+                {
+                    channelObjectName = channel.getObjectName();
+                }
+                catch (MalformedObjectNameException ex)
+                {
+                    _logger.error("Unable to create object name: ", ex);
+                }
+
+                Object[] itemValues = {channel.getChannelId(),
+                                       channelObjectName,
+                                       channel.isTransactional(),
+                                       (channel.getDefaultQueue() != null) ? channel.getDefaultQueue().getName() : null};
+
+                CompositeData channelData = new CompositeDataSupport(_channelType,
+                                                            _channelAtttibuteNames,
+                                                            itemValues);
+
+                _channelsList.put(channelData);
+            }
+
+            return _channelsList;
+        }
+
+        public TabularData viewChannels()
+            throws OpenDataException
+        {
+            return getChannels();
+        }
+
+        public void closeChannel(int id)
+            throws Exception
+        {
+            try
+            {
+                AMQMinaProtocolSession.this.closeChannel(id);
+            }
+            catch (AMQException ex)
+            {
+                throw new Exception(ex.toString());
+            }
+        }
+
+        public void closeConnection()
+            throws Exception
+        {
+            try
+            {
+                AMQMinaProtocolSession.this.closeSession();
+            }
+            catch (AMQException ex)
+            {
+                throw new Exception(ex.toString());
+            }
+        }
+
+    }
+
+    public AMQMinaProtocolSession(IoSession session, QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry,
+                                  AMQCodecFactory codecFactory)
+            throws AMQException
+    {
+        this(session, queueRegistry, exchangeRegistry, codecFactory, new AMQStateManager());
+    }
+
+    public AMQMinaProtocolSession(IoSession session, QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry,
+                                  AMQCodecFactory codecFactory, AMQStateManager stateManager)
+            throws AMQException
+    {
+        _stateManager = stateManager;
+        _minaProtocolSession = session;
+        session.setAttachment(this);
+        _frameListeners.add(_stateManager);
+        _queueRegistry = queueRegistry;
+        _exchangeRegistry = exchangeRegistry;
+        _codecFactory = codecFactory;
+        _managedObject = new AMQProtocolSessionMBean();
+        _managedObject.register();
+    }
+
+    public static AMQProtocolSession getAMQProtocolSession(IoSession minaProtocolSession)
+    {
+        return (AMQProtocolSession) minaProtocolSession.getAttachment();
+    }
+
+    public void dataBlockReceived(AMQDataBlock message)
+            throws Exception
+    {
+        _lastReceived = message;
+        if (message instanceof ProtocolInitiation)
+        {
+            ProtocolInitiation pi = (ProtocolInitiation) message;
+            // this ensures the codec never checks for a PI message again
+            ((AMQDecoder)_codecFactory.getDecoder()).setExpectProtocolInitiation(false);
+            try {
+                pi.checkVersion(this); // Fails if not correct
+                // This sets the protocol version (and hence framing classes) for this session.
+                _major = pi.protocolMajor;
+                _minor = pi.protocolMinor;
+                String mechanisms = ApplicationRegistry.getInstance().getAuthenticationManager().getMechanisms();
+                String locales = "en_US";
+                AMQFrame response = ConnectionStartBody.createAMQFrame((short)0, pi.protocolMajor, pi.protocolMinor, null,
+                                                                       mechanisms.getBytes(), locales.getBytes());
+                _minaProtocolSession.write(response);
+            } catch (AMQException e) {
+                _logger.error("Received incorrect protocol initiation", e);
+                /* Find last protocol version in protocol version list. Make sure last protocol version
+                listed in the build file (build-module.xml) is the latest version which will be used
+                here. */
+                int i = pv.length - 1;
+                _minaProtocolSession.write(new ProtocolInitiation(pv[i][PROTOCOL_MAJOR], pv[i][PROTOCOL_MINOR]));
+                // TODO: Close connection (but how to wait until message is sent?)
+            }
+        }
+        else
+        {
+            AMQFrame frame = (AMQFrame) message;
+
+            if (frame.bodyFrame instanceof AMQMethodBody)
+            {
+                methodFrameReceived(frame);
+            }
+            else
+            {
+                try
+                {
+                    contentFrameReceived(frame);
+                }
+                catch (RequiredDeliveryException e)
+                {
+                    //need to return the message:
+                    _logger.info("Returning message to " + this + " channel " + frame.channel
+                                 + ": " + e.getMessage());
+                    writeFrame(e.getReturnMessage(frame.channel));
+                }
+            }
+        }
+    }
+
+    private void methodFrameReceived(AMQFrame frame)
+    {
+        if (_logger.isDebugEnabled())
+        {
+            _logger.debug("Method frame received: " + frame);
+        }
+        final AMQMethodEvent<AMQMethodBody> evt = new AMQMethodEvent<AMQMethodBody>(frame.channel,
+                                                                                    (AMQMethodBody)frame.bodyFrame);
+        try
+        {
+            boolean wasAnyoneInterested = false;
+            for (AMQMethodListener listener : _frameListeners)
+            {
+                wasAnyoneInterested = listener.methodReceived(evt, this, _queueRegistry, _exchangeRegistry) ||
+                                      wasAnyoneInterested;
+            }
+            if (!wasAnyoneInterested)
+            {
+                throw new AMQException("AMQMethodEvent " + evt + " was not processed by any listener.");
+            }
+        }
+        catch (AMQChannelException e)
+        {
+            _logger.error("Closing channel due to: " + e.getMessage());
+            writeFrame(e.getCloseFrame(frame.channel));
+        }
+        catch (AMQException e)
+        {
+            for (AMQMethodListener listener : _frameListeners)
+            {
+                listener.error(e);
+            }
+            _minaProtocolSession.close();
+        }
+    }
+
+    private void contentFrameReceived(AMQFrame frame) throws AMQException
+    {
+        if (frame.bodyFrame instanceof ContentHeaderBody)
+        {
+            contentHeaderReceived(frame);
+        }
+        else if (frame.bodyFrame instanceof ContentBody)
+        {
+            contentBodyReceived(frame);
+        }
+        else if (frame.bodyFrame instanceof HeartbeatBody)
+        {
+            _logger.debug("Received heartbeat from client");
+        }
+        else
+        {
+            _logger.warn("Unrecognised frame " + frame.getClass().getName());
+        }
+    }
+
+    private void contentHeaderReceived(AMQFrame frame) throws AMQException
+    {
+        if (_logger.isDebugEnabled())
+        {
+            _logger.debug("Content header frame received: " + frame);
+        }
+        getChannel(frame.channel).publishContentHeader((ContentHeaderBody)frame.bodyFrame);
+    }
+
+    private void contentBodyReceived(AMQFrame frame) throws AMQException
+    {
+        if (_logger.isDebugEnabled())
+        {
+            _logger.debug("Content body frame received: " + frame);
+        }
+        getChannel(frame.channel).publishContentBody((ContentBody)frame.bodyFrame);
+    }
+
+    /**
+     * Convenience method that writes a frame to the protocol session. Equivalent
+     * to calling getProtocolSession().write().
+     *
+     * @param frame the frame to write
+     */
+    public void writeFrame(AMQDataBlock frame)
+    {
+        _lastSent = frame;
+        _minaProtocolSession.write(frame);
+    }
+
+    public String getContextKey()
+    {
+        return _contextKey;
+    }
+
+    public void setContextKey(String contextKey)
+    {
+        _contextKey = contextKey;
+    }
+
+    public AMQChannel getChannel(int channelId) throws AMQException
+    {
+        return _channelMap.get(channelId);
+    }
+
+    public void addChannel(AMQChannel channel)
+    {
+        _channelMap.put(channel.getChannelId(), channel);
+    }
+
+    /**
+     * Close a specific channel. This will remove any resources used by the channel, including:
+     * <ul><li>any queue subscriptions (this may in turn remove queues if they are auto delete</li>
+     * </ul>
+     * @param channelId id of the channel to close
+     * @throws AMQException if an error occurs closing the channel
+     * @throws IllegalArgumentException if the channel id is not valid
+     */
+    public void closeChannel(int channelId) throws AMQException
+    {
+        final AMQChannel channel = _channelMap.get(channelId);
+        if (channel == null)
+        {
+            throw new IllegalArgumentException("Unknown channel id");
+        }
+        else
+        {
+            try
+            {
+                channel.close(this);
+            }
+            finally
+            {
+                _channelMap.remove(channelId);
+            }
+        }
+    }
+
+    /**
+     * In our current implementation this is used by the clustering code.
+     * @param channelId
+     */
+    public void removeChannel(int channelId)
+    {
+        _channelMap.remove(channelId);
+    }
+
+    /**
+     * Initialise heartbeats on the session.
+     * @param delay delay in seconds (not ms)
+     */
+    public void initHeartbeats(int delay)
+    {
+        if(delay > 0)
+        {
+            _minaProtocolSession.setIdleTime(IdleStatus.WRITER_IDLE, delay);
+            _minaProtocolSession.setIdleTime(IdleStatus.READER_IDLE, HeartbeatConfig.getInstance().getTimeout(delay));
+        }
+    }
+
+    /**
+     * Closes all channels that were opened by this protocol session. This frees up all resources
+     * used by the channel.
+     * @throws AMQException if an error occurs while closing any channel
+     */
+    private void closeAllChannels() throws AMQException
+    {
+        for (AMQChannel channel : _channelMap.values())
+        {
+            channel.close(this);
+        }
+    }
+
+    /**
+     * This must be called when the session is _closed in order to free up any resources
+     * managed by the session.
+     */
+    public void closeSession() throws AMQException
+    {
+        if(!_closed)
+        {
+            _closed = true;
+            closeAllChannels();
+            if (_managedObject != null)
+            {
+                _managedObject.unregister();
+            }
+        }
+    }
+
+    public String toString()
+    {
+        return "AMQProtocolSession(" + _minaProtocolSession.getRemoteAddress() + ")";
+    }
+
+    public String dump()
+    {
+        return this + " last_sent=" + _lastSent + " last_received=" + _lastReceived;
+    }
+
+    /**
+     * @return an object that can be used to identity
+     */
+    public Object getKey()
+    {
+        return _minaProtocolSession.getRemoteAddress();
+    }
+
+    /**
+     * Get the fully qualified domain name of the local address to which this session is bound. Since some servers
+     * may be bound to multiple addresses this could vary depending on the acceptor this session was created from.
+     *
+     * @return a String FQDN
+     */
+    public String getLocalFQDN()
+    {
+        SocketAddress address = _minaProtocolSession.getLocalAddress();
+        // we use the vmpipe address in some tests hence the need for this rather ugly test. The host
+        // information is used by SASL primary.
+        if (address instanceof InetSocketAddress)
+        {
+            return ((InetSocketAddress)address).getHostName();
+        }
+        else if (address instanceof VmPipeAddress)
+        {
+            return "vmpipe:" + ((VmPipeAddress)address).getPort();
+        }
+        else
+        {
+            throw new IllegalArgumentException("Unsupported socket address class: " + address);
+        }
+    }
+
+    public SaslServer getSaslServer()
+    {
+        return _saslServer;
+    }
+
+    public void setSaslServer(SaslServer saslServer)
+    {
+        _saslServer = saslServer;
+    }
+    
+    /**
+     * Convenience methods for managing AMQP version.
+     * NOTE: Both major and minor will be set to 0 prior to protocol initiation.
+     */
+    
+    public byte getAmqpMajor()
+    {
+        return _major;
+    }
+    
+    public byte getAmqpMinor()
+    {
+        return _minor;
+    }
+    
+    public boolean amqpVersionEquals(byte major, byte minor)
+    {
+        return _major == major && _minor == minor;
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQMinaProtocolSession.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,217 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.protocol;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.codec.AMQCodecFactory;
+import org.apache.qpid.framing.*;
+import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.transport.ConnectorConfiguration;
+import org.apache.qpid.ssl.BogusSSLContextFactory;
+import org.apache.log4j.Logger;
+import org.apache.mina.common.ByteBuffer;
+import org.apache.mina.common.IdleStatus;
+import org.apache.mina.common.IoHandlerAdapter;
+import org.apache.mina.common.IoSession;
+import org.apache.mina.filter.SSLFilter;
+import org.apache.mina.filter.codec.ProtocolCodecFilter;
+import org.apache.mina.util.SessionUtil;
+
+import java.io.IOException;
+
+
+/**
+ * The protocol handler handles "protocol events" for all connections. The state
+ * associated with an individual connection is accessed through the protocol session.
+ *
+ * We delegate all frame (message) processing to the AMQProtocolSession which wraps
+ * the state for the connection.
+ *
+ */
+public class AMQPFastProtocolHandler  extends IoHandlerAdapter implements ProtocolVersionList
+{
+    private static final Logger _logger = Logger.getLogger(AMQPFastProtocolHandler.class);
+
+    /**
+     * The registry of all queues. This is passed to frame listeners when frame
+     * events occur.
+     */
+    private final QueueRegistry _queueRegistry;
+
+    /**
+     * The registry of all exchanges. This is passed to frame listeners when frame
+     * events occur.
+     */
+    private final ExchangeRegistry _exchangeRegistry;
+
+    private boolean _useSSL;
+
+    public AMQPFastProtocolHandler(QueueRegistry queueRegistry,
+                                   ExchangeRegistry exchangeRegistry)
+    {
+        _queueRegistry = queueRegistry;
+        _exchangeRegistry = exchangeRegistry;
+
+        _logger.debug("AMQPFastProtocolHandler created");
+    }
+
+    protected AMQPFastProtocolHandler(AMQPFastProtocolHandler handler)
+    {
+        this(handler._queueRegistry, handler._exchangeRegistry);
+    }
+
+    public void sessionCreated(IoSession protocolSession) throws Exception
+    {
+        SessionUtil.initialize(protocolSession);
+        final AMQCodecFactory codecFactory = new AMQCodecFactory(true);
+
+        createSession(protocolSession, _queueRegistry, _exchangeRegistry, codecFactory);
+        _logger.info("Protocol session created");
+
+        final ProtocolCodecFilter pcf = new ProtocolCodecFilter(codecFactory);
+
+        ConnectorConfiguration connectorConfig = ApplicationRegistry.getInstance().
+                getConfiguredObject(ConnectorConfiguration.class);
+        if (connectorConfig.enableExecutorPool)
+        {
+            if (_useSSL)
+            {
+                protocolSession.getFilterChain().addAfter("AsynchronousReadFilter", "sslFilter",
+                                                          new SSLFilter(BogusSSLContextFactory.getInstance(true)));
+            }
+            protocolSession.getFilterChain().addBefore("AsynchronousWriteFilter", "protocolFilter", pcf);
+        }
+        else
+        {
+            protocolSession.getFilterChain().addLast("protocolFilter", pcf);
+        }
+    }
+
+    /**
+     * Separated into its own, protected, method to allow easier reuse
+     */
+    protected void createSession(IoSession session, QueueRegistry queues, ExchangeRegistry exchanges, AMQCodecFactory codec) throws AMQException
+    {
+        new AMQMinaProtocolSession(session, queues, exchanges, codec);
+    }
+
+    public void sessionOpened(IoSession protocolSession) throws Exception
+    {
+        _logger.info("Session opened");
+    }
+
+    public void sessionClosed(IoSession protocolSession) throws Exception
+    {
+        _logger.info("Protocol Session closed");
+        final AMQProtocolSession amqProtocolSession = AMQMinaProtocolSession.getAMQProtocolSession(protocolSession);
+        amqProtocolSession.closeSession();
+    }
+
+    public void sessionIdle(IoSession session, IdleStatus status) throws Exception
+    {
+        _logger.debug("Protocol Session [" + this + "] idle: " + status);
+        if(IdleStatus.WRITER_IDLE.equals(status))
+        {
+            //write heartbeat frame:
+            session.write(HeartbeatBody.FRAME);
+        }
+        else if(IdleStatus.READER_IDLE.equals(status))
+        {
+            //failover:
+            throw new IOException("Timed out while waiting for heartbeat from peer.");
+        }
+
+    }
+
+    public void exceptionCaught(IoSession protocolSession, Throwable throwable) throws Exception
+    {
+        AMQProtocolSession session = AMQMinaProtocolSession.getAMQProtocolSession(protocolSession);
+        if (throwable instanceof AMQProtocolHeaderException)
+        {
+            /* Find last protocol version in protocol version list. Make sure last protocol version
+            listed in the build file (build-module.xml) is the latest version which will be returned
+            here. */
+            int i = pv.length - 1;
+            protocolSession.write(new ProtocolInitiation(pv[i][PROTOCOL_MAJOR], pv[i][PROTOCOL_MINOR]));
+            protocolSession.close();
+            _logger.error("Error in protocol initiation " + session + ": " + throwable.getMessage(), throwable);
+        }
+        else if(throwable instanceof IOException)
+        {
+            _logger.error("IOException caught in" + session + ", session closed implictly: " + throwable, throwable);            
+        }
+        else
+        {
+            protocolSession.write(ConnectionCloseBody.createAMQFrame(0, 200, throwable.getMessage(), 0, 0));
+            _logger.error("Exception caught in" + session + ", closing session explictly: " + throwable, throwable);
+            protocolSession.close();
+        }
+    }
+
+    /**
+     * Invoked when a message is received on a particular protocol session. Note that a
+     * protocol session is directly tied to a particular physical connection.
+     * @param protocolSession the protocol session that received the message
+     * @param message the message itself (i.e. a decoded frame)
+     * @throws Exception if the message cannot be processed
+     */
+    public void messageReceived(IoSession protocolSession, Object message) throws Exception
+    {
+        final AMQProtocolSession amqProtocolSession = AMQMinaProtocolSession.getAMQProtocolSession(protocolSession);
+
+        if (message instanceof AMQDataBlock)
+        {
+            amqProtocolSession.dataBlockReceived((AMQDataBlock) message);
+        }
+        else if (message instanceof ByteBuffer)
+        {
+            throw new IllegalStateException("Handed undecoded ByteBuffer buf = " + message);
+        }
+        else
+        {
+            throw new IllegalStateException("Handed unhandled message. message.class = " + message.getClass() + " message = " + message);
+        }
+    }
+
+    /**
+     * Called after a message has been sent out on a particular protocol session
+     * @param protocolSession the protocol session (i.e. connection) on which this
+     * message was sent
+     * @param object the message (frame) that was encoded and sent
+     * @throws Exception if we want to indicate an error
+     */
+    public void messageSent(IoSession protocolSession, Object object) throws Exception
+    {
+        if (_logger.isDebugEnabled())
+        {
+            _logger.debug("Message sent: " + object);
+        }
+    }
+
+    public boolean isUseSSL()
+    {
+        return _useSSL;
+    }
+
+    public void setUseSSL(boolean useSSL)
+    {
+        _useSSL = useSSL;
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPFastProtocolHandler.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPProtocolProvider.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPProtocolProvider.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPProtocolProvider.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPProtocolProvider.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,50 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.protocol;
+
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.registry.IApplicationRegistry;
+
+/**
+ * The protocol provide's role is to encapsulate the initialisation of the protocol handler.
+ *
+ * The protocol handler (see AMQPFastProtocolHandler class) handles protocol events
+ * such as connection closing or a frame being received. It can either do this directly
+ * or pass off to the protocol session in the cases where state information is required to
+ * deal with the event.
+ *
+ */
+public class AMQPProtocolProvider
+{
+    /**
+     * Handler for protocol events
+     */
+    private AMQPFastProtocolHandler _handler;
+
+    public AMQPProtocolProvider()
+    {
+        IApplicationRegistry registry = ApplicationRegistry.getInstance();
+        _handler = new AMQPFastProtocolHandler(registry.getQueueRegistry(),
+                                               registry.getExchangeRegistry());
+    }
+
+    public AMQPFastProtocolHandler getHandler()
+    {
+        return _handler;
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQPProtocolProvider.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQProtocolSession.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQProtocolSession.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQProtocolSession.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQProtocolSession.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,122 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.protocol;
+
+import org.apache.qpid.framing.AMQDataBlock;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.AMQException;
+
+import javax.security.sasl.SaslServer;
+
+
+public interface AMQProtocolSession
+{
+    /**
+     * Called when a protocol data block is received
+     * @param message the data block that has been received
+     * @throws Exception if processing the datablock fails
+     */
+    void dataBlockReceived(AMQDataBlock message) throws Exception;
+
+    /**
+     * Write a datablock, encoding where necessary (e.g. into a sequence of bytes)
+     * @param frame the frame to be encoded and written
+     */
+    void writeFrame(AMQDataBlock frame);
+
+    /**
+     * Get the context key associated with this session. Context key is described
+     * in the AMQ protocol specification (RFC 6).
+     * @return the context key
+     */
+    String getContextKey();
+
+    /**
+     * Set the context key associated with this session. Context key is described
+     * in the AMQ protocol specification (RFC 6).
+     * @param contextKey the context key
+     */
+    void setContextKey(String contextKey);
+
+    /**
+     * Get the channel for this session associated with the specified id. A channel
+     * id is unique per connection (i.e. per session).
+     * @param channelId the channel id which must be valid
+     * @return null if no channel exists, the channel otherwise
+     */
+    AMQChannel getChannel(int channelId) throws AMQException;
+
+    /**
+     * Associate a channel with this session.
+     * @param channel the channel to associate with this session. It is an error to
+     * associate the same channel with more than one session but this is not validated.
+     */
+    void addChannel(AMQChannel channel);
+
+    /**
+     * Close a specific channel. This will remove any resources used by the channel, including:
+     * <ul><li>any queue subscriptions (this may in turn remove queues if they are auto delete</li>
+     * </ul>
+     * @param channelId id of the channel to close
+     * @throws org.apache.qpid.AMQException if an error occurs closing the channel
+     * @throws IllegalArgumentException if the channel id is not valid
+     */
+    void closeChannel(int channelId) throws AMQException;
+
+    /**
+     * Remove a channel from the session but do not close it.
+     * @param channelId
+     */
+    void removeChannel(int channelId);
+
+    /**
+     * Initialise heartbeats on the session.
+     * @param delay delay in seconds (not ms)
+     */
+    void initHeartbeats(int delay);
+
+    /**
+     * This must be called when the session is _closed in order to free up any resources
+     * managed by the session.
+     */
+    void closeSession() throws AMQException;
+
+    /**
+     * @return a key that uniquely identifies this session
+     */
+    Object getKey();
+
+    /**
+     * Get the fully qualified domain name of the local address to which this session is bound. Since some servers
+     * may be bound to multiple addresses this could vary depending on the acceptor this session was created from.
+     *
+     * @return a String FQDN
+     */
+    String getLocalFQDN();
+
+    /**
+     * @return the sasl server that can perform authentication for this session.
+     */
+    SaslServer getSaslServer();
+
+    /**
+     * Set the sasl server that is to perform authentication for this session.
+     * @param saslServer
+     */
+    void setSaslServer(SaslServer saslServer);
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/AMQProtocolSession.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ExchangeInitialiser.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ExchangeInitialiser.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ExchangeInitialiser.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ExchangeInitialiser.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,38 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.protocol;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.exchange.ExchangeDefaults;
+import org.apache.qpid.server.exchange.ExchangeFactory;
+import org.apache.qpid.server.exchange.ExchangeRegistry;
+
+public class ExchangeInitialiser
+{
+    public void initialise(ExchangeFactory factory, ExchangeRegistry registry) throws AMQException{        
+        define(registry, factory, ExchangeDefaults.DIRECT_EXCHANGE_NAME, ExchangeDefaults.DIRECT_EXCHANGE_CLASS);
+        define(registry, factory, ExchangeDefaults.TOPIC_EXCHANGE_NAME, ExchangeDefaults.TOPIC_EXCHANGE_CLASS);
+        define(registry, factory, ExchangeDefaults.HEADERS_EXCHANGE_NAME, ExchangeDefaults.HEADERS_EXCHANGE_CLASS);
+    }
+
+    private void define(ExchangeRegistry r, ExchangeFactory f,
+                        String name, String type) throws AMQException
+    {
+        r.registerExchange(f.createExchange(name, type, true, false, 0));
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ExchangeInitialiser.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/HeartbeatConfig.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/HeartbeatConfig.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/HeartbeatConfig.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/HeartbeatConfig.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,64 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.protocol;
+
+import org.apache.qpid.configuration.Configured;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+
+public class HeartbeatConfig
+{
+    @Configured(path = "heartbeat.delay", defaultValue = "5")    
+    public int delay = 5;//in secs
+    @Configured(path = "heartbeat.timeoutFactor", defaultValue = "2.0")
+    public double timeoutFactor = 2;
+
+    public double getTimeoutFactor()
+    {
+        return timeoutFactor;
+    }
+
+    public void setTimeoutFactor(double timeoutFactor)
+    {
+        this.timeoutFactor = timeoutFactor;
+    }
+
+    public int getDelay()
+    {
+        return delay;
+    }
+
+    public void setDelay(int delay)
+    {
+        this.delay = delay;
+    }
+
+    int getTimeout(int writeDelay)
+    {
+        return (int) (timeoutFactor * writeDelay);
+    }
+
+    public static HeartbeatConfig getInstance()
+    {
+        return ApplicationRegistry.getInstance().getConfiguredObject(HeartbeatConfig.class);
+    }
+
+    public String toString()
+    {
+        return "HeartBeatConfig{delay = " + delay + " timeoutFactor = " + timeoutFactor + "}";
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/HeartbeatConfig.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedConnection.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedConnection.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedConnection.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedConnection.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,92 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package org.apache.qpid.server.protocol;
+
+import org.apache.qpid.AMQException;
+
+import javax.management.openmbean.TabularData;
+import javax.management.openmbean.OpenDataException;
+import java.util.Date;
+
+/**
+ * The management interface exposed to allow management of Connections.
+ * @author   Bhupendra Bhardwaj
+ * @version  0.1
+ */
+public interface ManagedConnection
+{
+    static final String TYPE = "Connection";
+
+    /**
+     * Tells the last time, the IO operation was done.
+     * @return last IO time.
+     */
+    Date getLastIoTime();
+
+    /**
+     * Tells the remote address of this connection.
+     * @return  remote address
+     */
+    String getRemoteAddress();
+
+    /**
+     * Tells the total number of bytes written till now.
+     * @return number of bytes written.
+     */
+    long getWrittenBytes();
+
+    /**
+     * Tells the total number of bytes read till now.
+     * @return number of bytes read.
+     */
+    long getReadBytes();
+
+    /**
+     * Tells the maximum number of channels that can be opened using
+     * this connection.  This is useful in setting notifications or
+     * taking required action is there are more channels being created.
+     * @return maximum number of channels allowed to be created.
+     */
+    long getMaximumNumberOfAllowedChannels();
+
+    /**
+     * Sets the maximum number of channels allowed to be created using
+     * this connection.
+     * @param value
+     */
+    void setMaximumNumberOfAllowedChannels(long value);
+
+    //********** Operations *****************//
+
+    /**
+     * Returns channel details of all the channels opened for this connection.
+     * @return  channel details.
+     */
+    TabularData viewChannels() throws OpenDataException;
+
+    /**
+     * Closes all the channels and unregisters this connection from managed objects.
+     */
+    void closeConnection() throws Exception;
+
+    /**
+     * Unsubscribes the consumers and unregisters the channel from managed objects.
+     */
+    void closeChannel(int channelId) throws Exception;
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedConnection.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedSession.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedSession.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedSession.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedSession.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,33 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.protocol;
+
+import java.util.Date;
+
+public interface ManagedSession
+{
+    static final String TYPE = "Connection";
+
+    Date getLastIoTime();
+
+    String getRemoteAddress();
+
+    long getWrittenBytes();
+
+    long getReadBytes();
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/protocol/ManagedSession.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQMessage.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQMessage.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQMessage.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQMessage.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,343 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.mina.common.ByteBuffer;
+import org.apache.qpid.framing.*;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.AMQException;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.LinkedList;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Combines the information that make up a deliverable message into a more manageable form.
+ */
+public class AMQMessage
+{
+    private final Set<Object> _tokens = new HashSet<Object>();
+
+    private AMQProtocolSession _publisher;
+
+    private final BasicPublishBody  _publishBody;
+
+    private ContentHeaderBody _contentHeaderBody;
+
+    private List<ContentBody> _contentBodies;
+
+    private boolean _redelivered;
+
+    private final long _messageId;
+
+    private final AtomicInteger _referenceCount = new AtomicInteger(1);
+
+    /**
+     * Keeps a track of how many bytes we have received in body frames
+     */
+    private long _bodyLengthReceived = 0;
+
+    /**
+     * The message store in which this message is contained.
+     */
+    private transient final MessageStore _store;
+
+    public AMQMessage(MessageStore messageStore, BasicPublishBody publishBody)
+    {
+        _messageId = messageStore.getNewMessageId();
+        _publishBody = publishBody;
+        _store = messageStore;
+        _contentBodies = new LinkedList<ContentBody>();
+    }
+
+    public AMQMessage(MessageStore store, long messageId, BasicPublishBody publishBody,
+                      ContentHeaderBody contentHeaderBody, List<ContentBody> contentBodies)
+            throws AMQException
+    {
+        _publishBody = publishBody;
+        _contentHeaderBody = contentHeaderBody;
+        _contentBodies = contentBodies;
+        _messageId = messageId;
+        _store = store;
+        storeMessage();
+    }
+
+    public AMQMessage(MessageStore store, BasicPublishBody publishBody,
+                      ContentHeaderBody contentHeaderBody, List<ContentBody> contentBodies)
+            throws AMQException
+    {
+        this(store, store.getNewMessageId(), publishBody, contentHeaderBody, contentBodies);        
+    }
+
+    protected AMQMessage(AMQMessage msg) throws AMQException
+    {
+        this(msg._store, msg._messageId, msg._publishBody, msg._contentHeaderBody, msg._contentBodies);
+    }
+
+    private void storeMessage() throws AMQException
+    {
+        if (isPersistent())
+        {
+            _store.put(this);
+        }
+    }
+
+    public CompositeAMQDataBlock getDataBlock(ByteBuffer encodedDeliverBody, int channel)
+    {
+        AMQFrame[] allFrames = new AMQFrame[1 + _contentBodies.size()];
+
+        allFrames[0] = ContentHeaderBody.createAMQFrame(channel, _contentHeaderBody);
+        for (int i = 1; i < allFrames.length; i++)
+        {
+            allFrames[i] = ContentBody.createAMQFrame(channel, _contentBodies.get(i - 1));
+        }
+        return new CompositeAMQDataBlock(encodedDeliverBody, allFrames);
+    }
+
+    public CompositeAMQDataBlock getDataBlock(int channel, String consumerTag, long deliveryTag)
+    {
+        AMQFrame[] allFrames = new AMQFrame[2 + _contentBodies.size()];
+
+        allFrames[0] = BasicDeliverBody.createAMQFrame(channel, consumerTag, deliveryTag, _redelivered,
+                                                       getExchangeName(), getRoutingKey());
+        allFrames[1] = ContentHeaderBody.createAMQFrame(channel, _contentHeaderBody);
+        for (int i = 2; i < allFrames.length; i++)
+        {
+            allFrames[i] = ContentBody.createAMQFrame(channel, _contentBodies.get(i - 2));
+        }
+        return new CompositeAMQDataBlock(allFrames);
+    }
+
+    public List<AMQBody> getPayload()
+    {
+        List<AMQBody> payload = new ArrayList<AMQBody>(2 + _contentBodies.size());
+        payload.add(_publishBody);
+        payload.add(_contentHeaderBody);
+        payload.addAll(_contentBodies);
+        return payload;
+    }
+
+    public BasicPublishBody getPublishBody()
+    {
+        return _publishBody;
+    }
+
+    public ContentHeaderBody getContentHeaderBody()
+    {
+        return _contentHeaderBody;
+    }
+
+    public void setContentHeaderBody(ContentHeaderBody contentHeaderBody) throws AMQException
+    {
+        _contentHeaderBody = contentHeaderBody;
+        if (isAllContentReceived())
+        {
+            storeMessage();
+        }
+    }
+
+    public List<ContentBody> getContentBodies()
+    {
+        return _contentBodies;
+    }
+
+    public void setContentBodies(List<ContentBody> contentBodies)
+    {
+        _contentBodies = contentBodies;
+    }
+
+    public void addContentBodyFrame(ContentBody contentBody) throws AMQException
+    {
+        _contentBodies.add(contentBody);
+        _bodyLengthReceived += contentBody.getSize();
+        if (isAllContentReceived())
+        {
+            storeMessage();
+        }
+    }
+
+    public boolean isAllContentReceived()
+    {
+        return _bodyLengthReceived == _contentHeaderBody.bodySize;
+    }
+
+    public boolean isRedelivered()
+    {
+        return _redelivered;
+    }
+
+    String getExchangeName()
+    {
+        return _publishBody.exchange;
+    }
+
+    String getRoutingKey()
+    {
+        return _publishBody.routingKey;
+    }
+
+    boolean isImmediate()
+    {
+        return _publishBody.immediate;
+    }
+
+    NoConsumersException getNoConsumersException(String queue)
+    {
+        return new NoConsumersException(queue, _publishBody, _contentHeaderBody, _contentBodies);
+    }
+
+    void setRedelivered(boolean redelivered)
+    {
+        _redelivered = redelivered;
+    }
+
+    public long getMessageId()
+    {
+        return _messageId;
+    }
+
+    /**
+     * Threadsafe. Increment the reference count on the message.
+     */
+    public void incrementReference()
+    {
+        _referenceCount.incrementAndGet();
+    }
+
+    /**
+     * Threadsafe. This will decrement the reference count and when it reaches zero will remove the message from the
+     * message store.
+     */
+    public void decrementReference() throws AMQException
+    {
+        // note that the operation of decrementing the reference count and then removing the message does not
+        // have to be atomic since the ref count starts at 1 and the exchange itself decrements that after
+        // the message has been passed to all queues. i.e. we are
+        // not relying on the all the increments having taken place before the delivery manager decrements.
+        if (_referenceCount.decrementAndGet() == 0)
+        {
+            _store.removeMessage(_messageId);
+        }
+    }
+
+    public void setPublisher(AMQProtocolSession publisher)
+    {
+        _publisher = publisher;
+    }
+
+    public AMQProtocolSession getPublisher()
+    {
+        return _publisher;
+    }
+
+    public boolean checkToken(Object token)
+    {
+        if(_tokens.contains(token))
+        {
+            return true;
+        }
+        else
+        {
+            _tokens.add(token);
+            return false;
+        }
+    }
+
+    public void enqueue(AMQQueue queue) throws AMQException
+    {
+        //if the message is not persistent or the queue is not durable
+        //we will not need to recover the association and so do not
+        //need to record it
+        if(isPersistent() && queue.isDurable())
+        {
+            _store.enqueueMessage(queue.getName(), _messageId);
+        }
+    }
+
+    public void dequeue(AMQQueue queue) throws AMQException
+    {
+        //only record associations where both queue and message will survive
+        //a restart, so only need to remove association if this is the case
+        if(isPersistent() && queue.isDurable())
+        {
+            _store.dequeueMessage(queue.getName(), _messageId);
+        }
+    }
+
+    /**
+     * Used to requeue a message (on delivery where an acknowledgement is
+     * expected). This will move it to the end of the queue.
+     */
+    public void requeue(AMQQueue queue) throws AMQException
+    {
+        if(isPersistent() && queue.isDurable())
+        {
+            if(!_store.inTran())
+            {
+                //if not already in tran, want to be so this is atomic
+                _store.beginTran();
+                try
+                {
+                    requeueImpl(queue);
+                    _store.commitTran();
+                }
+                catch(AMQException e)
+                {
+                    _store.abortTran();
+                }
+            }
+            else
+            {
+                //May already be in tran (e.g. if this is called during delivery
+                //resulting from a commit).
+                requeueImpl(queue);
+            }
+        }
+    }
+
+    private void requeueImpl(AMQQueue queue) throws AMQException
+    {
+        try
+        {
+            _store.dequeueMessage(queue.getName(), _messageId);
+            _store.enqueueMessage(queue.getName(), _messageId);
+        }
+        catch(AMQException e)
+        {
+            throw e;
+        }
+        catch(Throwable t)
+        {
+            throw new AMQException("Failure on requeue of message", t);
+        }
+    }
+
+    public boolean isPersistent() throws AMQException
+    {
+        if(_contentHeaderBody == null)
+        {
+            throw new AMQException("Cannot determine delivery mode of message. Content header not found.");
+        }
+        return _contentHeaderBody.properties instanceof BasicContentHeaderProperties
+                &&((BasicContentHeaderProperties) _contentHeaderBody.properties).getDeliveryMode() == 2;
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQMessage.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQQueue.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQQueue.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQQueue.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQQueue.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,654 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.log4j.Logger;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.ContentBody;
+import org.apache.qpid.server.exchange.Exchange;
+import org.apache.qpid.server.management.Managable;
+import org.apache.qpid.server.management.ManagedObject;
+import org.apache.qpid.server.management.AMQManagedObject;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
+
+import javax.management.openmbean.*;
+import javax.management.MBeanNotificationInfo;
+import javax.management.AttributeChangeNotification;
+import javax.management.Notification;
+import javax.management.JMException;
+import javax.management.MBeanException;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.Executor;
+
+/**
+ * This is an AMQ Queue, and should not be confused with a JMS queue or any other abstraction like
+ * that. It is described fully in RFC 006.
+ */
+public class AMQQueue implements Managable
+{
+    private static final Logger _logger = Logger.getLogger(AMQQueue.class);
+
+    private final String _name;
+
+    /**
+     * null means shared
+     */
+    private final String _owner;
+
+    private final boolean _durable;
+
+    /**
+     * If true, this queue is deleted when the last subscriber is removed
+     */
+    private final boolean _autoDelete;
+
+    /**
+     * Holds subscribers to the queue.
+     */
+    private final SubscriptionSet _subscribers;
+
+    private final SubscriptionFactory _subscriptionFactory;
+
+    /**
+     * Manages message delivery.
+     */
+    private final DeliveryManager _deliveryMgr;
+
+    /**
+     * The queue registry with which this queue is registered.
+     */
+    private final QueueRegistry _queueRegistry;
+
+    /**
+     * Used to track bindings to exchanges so that on deletion they can easily
+     * be cancelled.
+     */
+    private final ExchangeBindings _bindings = new ExchangeBindings(this);
+
+    /**
+     * Executor on which asynchronous delivery will be carriedout where required
+     */
+    private final Executor _asyncDelivery;
+
+    private final AMQQueueMBean _managedObject;
+
+    /**
+     * max allowed size of a single message.
+     */
+    private long _maxAllowedMessageSize = 0;
+
+    /**
+     * max allowed number of messages on a queue.
+     */
+    private long _maxAllowedMessageCount = 0;
+
+    /**
+     * max allowed size in bytes for all the messages combined together in a queue.
+     */
+    private long _queueDepth = 0;
+
+    /**
+     * total messages received by the queue since startup.
+     */
+    private long _totalMessagesReceived = 0;
+
+    /**
+     * MBean interface for the implementation AMQQueueMBean.
+     * This is required for making the implementation a compliant MBean.
+     */
+    public interface AMQQueueMBeanMBean extends ManagedQueue
+    {
+
+    }
+    /**
+     * MBean class for AMQQueue. It implements all the management features exposed
+     * for an AMQQueue.
+     */
+    private final class AMQQueueMBean extends AMQManagedObject implements AMQQueueMBeanMBean
+    {
+        // AMQ message attribute names exposed.
+        private String[] _msgAttributeNames = { "MessageId",
+                                                "Redelivered",
+                                                "Content's size",
+                                                "Contents" };
+        // AMQ Message attribute descriptions.
+        private String[] _msgAttributeDescriptions = { "Message Id",
+                                              "Redelivered",
+                                              "Message content's size in bytes",
+                                              "Message content bodies" };
+        // AMQ message attribute types.
+        private OpenType[]    _msgAttributeTypes = new OpenType[4];
+        // Messages will be indexed according to the messageId.
+        private String[]      _msgAttributeIndex = { "MessageId"};
+        // Composite type for representing AMQ Message data.
+        private CompositeType _messageDataType = null;
+        // Datatype for representing AMQ messages list.
+        private TabularType   _messagelistDataType = null;
+
+        private String[]      _contentNames = {"SerialNumber", "ContentBody"};
+        private String[]      _contentDesc  = {"SerialNumber", "Message Content"};
+        private String[]      _contentIndex = {"SerialNumber"};
+        private OpenType[]    _contentType  = new OpenType[2];
+        private CompositeType _contentBodyType = null;
+        private TabularType   _contentBodyListType = null;
+
+        public AMQQueueMBean()
+        {
+            super(ManagedQueue.class, ManagedQueue.TYPE);
+            init();
+        }
+
+        private void init()
+        {
+            try
+            {
+                _contentType[0]  = SimpleType.INTEGER;
+                _contentType[1]  = new ArrayType(1, SimpleType.BYTE);
+                _contentBodyType = new CompositeType("Content",
+                                                    "Message body content",
+                                                    _contentNames,
+                                                    _contentDesc,
+                                                    _contentType);
+                _contentBodyListType = new TabularType("MessageContents",
+                                                      "MessageContent",
+                                                      _contentBodyType,
+                                                      _contentIndex);
+
+                _msgAttributeTypes[0] = SimpleType.LONG;
+                _msgAttributeTypes[1] = SimpleType.BOOLEAN;
+                _msgAttributeTypes[2] = SimpleType.LONG;
+                _msgAttributeTypes[3] = _contentBodyListType;
+
+                _messageDataType = new CompositeType("Message",
+                                                    "AMQ Message",
+                                                    _msgAttributeNames,
+                                                    _msgAttributeDescriptions,
+                                                    _msgAttributeTypes);
+                _messagelistDataType = new TabularType("Messages",
+                                                      "List of messages",
+                                                      _messageDataType,
+                                                      _msgAttributeIndex);
+            }
+            catch (OpenDataException ex)
+            {
+                _logger.error("OpenDataTypes could not be created.", ex);
+                throw new RuntimeException(ex);
+            }
+        }
+
+        public String getObjectInstanceName()
+        {
+            return _name;
+        }
+
+        public String getName()
+        {
+            return _name;
+        }
+
+        public boolean isDurable()
+        {
+            return _durable;
+        }
+
+        public String getOwner()
+        {
+            return _owner;
+        }
+
+        public boolean isAutoDelete()
+        {
+            return _autoDelete;
+        }
+
+        public int getMessageCount()
+        {
+            return _deliveryMgr.getQueueMessageCount();
+        }
+
+        public long getMaximumMessageSize()
+        {
+            return _maxAllowedMessageSize;
+        }
+
+        public void setMaximumMessageSize(long value)
+        {
+            _maxAllowedMessageSize = value;
+        }
+
+        public int getConsumerCount()
+        {
+            return _subscribers.size();
+        }
+
+        public int getActiveConsumerCount()
+        {
+            return _subscribers.getWeight();
+        }
+
+        public long getReceivedMessageCount()
+        {
+            return _totalMessagesReceived;
+        }
+
+        public long getMaximumMessageCount()
+        {
+            return _maxAllowedMessageCount;
+        }
+
+        public void setMaximumMessageCount( long value)
+        {
+            _maxAllowedMessageCount = value;
+        }
+
+        public long getQueueDepth()
+        {
+            return _queueDepth;
+        }
+
+        public void setQueueDepth(long value)
+        {
+           _queueDepth = value;
+        }
+
+        // Operations
+
+        private void checkForNotification()
+        {
+            if (getMessageCount() >= getMaximumMessageCount())
+            {
+                Notification n = new Notification(
+                        "Warning",
+                        this,
+                        ++_notificationSequenceNumber,
+                        System.currentTimeMillis(),
+                        "Queue has reached its size limit and is now full.");
+
+                _broadcaster.sendNotification(n);
+            }
+        }
+
+        public void deleteMessageFromTop() throws JMException
+        {
+            try
+            {
+                _deliveryMgr.removeAMessageFromTop();
+            }
+            catch(AMQException ex)
+            {
+                throw new MBeanException(ex, ex.toString());
+            }
+        }
+
+        public void clearQueue() throws JMException
+        {
+            try
+            {
+                _deliveryMgr.clearAllMessages();
+            }
+            catch (AMQException ex)
+            {
+                throw new MBeanException(ex, ex.toString());
+            }
+        }
+
+        /**
+         * Returns the messages stored in this queue in tabular form.
+         * @param beginIndex
+         * @param endIndex
+         * @return AMQ messages in tabular form.
+         * @throws JMException
+         */
+        public TabularData viewMessages(int beginIndex, int endIndex) throws JMException
+        {
+            if ((beginIndex > endIndex) || (beginIndex < 1))
+            {
+                throw new JMException("FromIndex = " + beginIndex + ", ToIndex = " + endIndex +
+                          "\nFromIndex should be greater than 0 and less than ToIndex");
+            }
+
+            List<AMQMessage> list = _deliveryMgr.getMessages();
+
+            if (beginIndex > list.size())
+            {
+                throw new JMException("FromIndex = " + beginIndex + ". There are only " + list.size() + " messages in the queue");
+            }
+
+            endIndex = endIndex < list.size() ? endIndex : list.size();
+            TabularDataSupport _messageList = new TabularDataSupport(_messagelistDataType);
+
+            for (int i = beginIndex; i <= endIndex; i++)
+            {
+                AMQMessage msg = list.get(i - 1);
+                long msgId = msg.getMessageId();
+
+                List<ContentBody> cBodies = msg.getContentBodies();
+
+                TabularDataSupport _contentList = new TabularDataSupport(_contentBodyListType);
+                int  contentSerialNo = 1;
+                long size = 0;
+
+                for (ContentBody body : cBodies)
+                {
+                    if (body.getSize() != 0)
+                    {
+                        Byte[] byteArray = getByteArray(body.payload.slice().array());
+                        size = size + byteArray.length;
+
+                        Object[] contentValues = {contentSerialNo, byteArray};
+                        CompositeData contentData = new CompositeDataSupport(_contentBodyType,
+                                                                             _contentNames,
+                                                                             contentValues);
+
+                        _contentList.put(contentData);
+                    }
+                }
+
+                Object[] itemValues = {msgId, true, size, _contentList};
+                CompositeData messageData = new CompositeDataSupport(_messageDataType,
+                                                                     _msgAttributeNames,
+                                                                     itemValues);
+                _messageList.put(messageData);
+            }
+
+            return _messageList;
+        }
+
+        /**
+         * A utility to convert byte[] to Byte[]. Required to create composite
+         * type for message contents.
+         * @param byteArray  message content as byte[]
+         * @return  Byte[]
+         */
+        private Byte[] getByteArray(byte[] byteArray)
+        {
+            int size = byteArray.length;
+            List<Byte> list = new ArrayList<Byte>();
+
+            for (int i = 0; i < size; i++)
+            {
+                list.add(byteArray[i]);
+            }
+
+            return list.toArray(new Byte[0]);
+        }
+
+        /**
+         * Creates all the notifications this MBean can send.
+         * @return Notifications broadcasted by this MBean.
+         */
+        public MBeanNotificationInfo[] getNotificationInfo()
+        {
+            String[] notificationTypes = new String[]
+                                {AttributeChangeNotification.ATTRIBUTE_CHANGE};
+            String name = AttributeChangeNotification.class.getName();
+            String description = "An attribute of this MBean has changed";
+            MBeanNotificationInfo info1 = new MBeanNotificationInfo(notificationTypes,
+                                                                    name,
+                                                                    description);
+
+            return new MBeanNotificationInfo[] {info1};
+        }
+
+    } // End of AMQMBean class
+
+    public AMQQueue(String name, boolean durable, String owner,
+                    boolean autoDelete, QueueRegistry queueRegistry)
+            throws AMQException
+    {
+        this(name, durable, owner, autoDelete, queueRegistry,
+             AsyncDeliveryConfig.getAsyncDeliveryExecutor(), new SubscriptionImpl.Factory());
+    }
+
+    public AMQQueue(String name, boolean durable, String owner,
+                    boolean autoDelete, QueueRegistry queueRegistry, SubscriptionFactory subscriptionFactory)
+            throws AMQException
+    {
+        this(name, durable, owner, autoDelete, queueRegistry,
+             AsyncDeliveryConfig.getAsyncDeliveryExecutor(), subscriptionFactory);
+    }
+
+    public AMQQueue(String name, boolean durable, String owner,
+                    boolean autoDelete, QueueRegistry queueRegistry, Executor asyncDelivery,
+                    SubscriptionFactory subscriptionFactory)
+            throws AMQException
+    {
+
+        this(name, durable, owner, autoDelete, queueRegistry, asyncDelivery, new SubscriptionSet(), subscriptionFactory);
+    }
+
+    public AMQQueue(String name, boolean durable, String owner,
+                    boolean autoDelete, QueueRegistry queueRegistry, Executor asyncDelivery)
+            throws AMQException
+    {
+
+        this(name, durable, owner, autoDelete, queueRegistry, asyncDelivery, new SubscriptionSet(),
+             new SubscriptionImpl.Factory());
+    }
+
+    protected AMQQueue(String name, boolean durable, String owner,
+                       boolean autoDelete, QueueRegistry queueRegistry,
+                       SubscriptionSet subscribers, SubscriptionFactory subscriptionFactory)
+            throws AMQException
+    {
+        this(name, durable, owner, autoDelete, queueRegistry,
+             AsyncDeliveryConfig.getAsyncDeliveryExecutor(), subscribers, subscriptionFactory);
+    }
+
+    protected AMQQueue(String name, boolean durable, String owner,
+                       boolean autoDelete, QueueRegistry queueRegistry,
+                       SubscriptionSet subscribers)
+            throws AMQException
+    {
+        this(name, durable, owner, autoDelete, queueRegistry,
+             AsyncDeliveryConfig.getAsyncDeliveryExecutor(), subscribers, new SubscriptionImpl.Factory());
+    }
+
+    protected AMQQueue(String name, boolean durable, String owner,
+                       boolean autoDelete, QueueRegistry queueRegistry,
+                       Executor asyncDelivery, SubscriptionSet subscribers, SubscriptionFactory subscriptionFactory)
+            throws AMQException
+    {
+        if (name == null)
+        {
+            throw new IllegalArgumentException("Queue name must not be null");
+        }
+        if (queueRegistry == null)
+        {
+            throw new IllegalArgumentException("Queue registry must not be null");
+        }
+        _name = name;
+        _durable = durable;
+        _owner = owner;
+        _autoDelete = autoDelete;
+        _queueRegistry = queueRegistry;
+        _asyncDelivery = asyncDelivery;
+        _managedObject = new AMQQueueMBean();
+        _managedObject.register();
+
+        _subscribers = subscribers;
+        _subscriptionFactory = subscriptionFactory;
+        _deliveryMgr = new DeliveryManager(_subscribers, this);
+    }
+
+    public String getName()
+    {
+        return _name;
+    }
+
+    public boolean isShared()
+    {
+        return _owner == null;
+    }
+
+    public boolean isDurable()
+    {
+        return _durable;
+    }
+
+    public String getOwner()
+    {
+        return _owner;
+    }
+
+    public boolean isAutoDelete()
+    {
+        return _autoDelete;
+    }
+
+    public int getMessageCount()
+    {
+        return _deliveryMgr.getQueueMessageCount();
+    }
+
+    public ManagedObject getManagedObject()
+    {
+        return _managedObject;
+    }
+
+    public void bind(String routingKey, Exchange exchange)
+    {
+        _bindings.addBinding(routingKey, exchange);
+    }
+
+    public void registerProtocolSession(AMQProtocolSession ps, int channel, String consumerTag, boolean acks)
+            throws AMQException
+    {
+        debug("Registering protocol session {0} with channel {1} and consumer tag {2} with {3}", ps, channel, consumerTag, this);
+
+        Subscription subscription = _subscriptionFactory.createSubscription(channel, ps, consumerTag, acks);
+        _subscribers.addSubscriber(subscription);
+    }
+
+    public void unregisterProtocolSession(AMQProtocolSession ps, int channel, String consumerTag) throws AMQException
+    {
+        debug("Unregistering protocol session {0} with channel {1} and consumer tag {2} from {3}", ps, channel, consumerTag,
+              this);
+
+        Subscription removedSubscription;
+        if ((removedSubscription = _subscribers.removeSubscriber(_subscriptionFactory.createSubscription(channel,
+                                                                                                         ps,
+                                                                                                         consumerTag)))
+                == null)
+        {
+            throw new AMQException("Protocol session with channel " + channel + " and consumer tag " + consumerTag +
+                    " and protocol session key " + ps.getKey() + " not registered with queue " + this);
+        }
+
+        // if we are eligible for auto deletion, unregister from the queue registry
+        if (_autoDelete && _subscribers.isEmpty())
+        {
+            autodelete();
+            // we need to manually fire the event to the removed subscription (which was the last one left for this
+            // queue. This is because the delete method uses the subscription set which has just been cleared
+            removedSubscription.queueDeleted(this);
+        }
+    }
+
+    public int delete(boolean checkUnused, boolean checkEmpty) throws AMQException
+    {
+        if(checkUnused && !_subscribers.isEmpty())
+        {
+            _logger.info("Will not delete " + this + " as it is in use.");
+            return 0;
+        }
+        else if(checkEmpty && _deliveryMgr.getQueueMessageCount() > 0)
+        {
+            _logger.info("Will not delete " + this + " as it is not empty.");
+            return 0;
+        }
+        else
+        {
+            delete();
+            return _deliveryMgr.getQueueMessageCount();
+        }
+    }
+
+    public void delete() throws AMQException
+    {
+        _subscribers.queueDeleted(this);
+        _bindings.deregister();
+        _queueRegistry.unregisterQueue(_name);
+        _managedObject.unregister();
+    }
+
+    protected void autodelete() throws AMQException
+    {
+        debug("autodeleting {0}", this);
+        delete();
+    }
+
+    public void deliver(AMQMessage msg) throws AMQException
+    {
+        msg.enqueue(this);
+        _deliveryMgr.deliver(getName(), msg);
+        updateReceivedMessageCount();
+    }
+
+    public void deliverAsync()
+    {
+        _deliveryMgr.processAsync(_asyncDelivery);
+    }
+
+    protected SubscriptionManager getSubscribers()
+    {
+        return _subscribers;
+    }
+
+    protected void updateReceivedMessageCount()
+    {
+        _totalMessagesReceived++;
+        _managedObject.checkForNotification();
+    }
+
+    public boolean equals(Object o)
+    {
+        if (this == o)
+        {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass())
+        {
+            return false;
+        }
+
+        final AMQQueue amqQueue = (AMQQueue) o;
+
+        return (_name.equals(amqQueue._name));
+    }
+
+    public int hashCode()
+    {
+        return _name.hashCode();
+    }
+
+    public String toString()
+    {
+        return "Queue(" + _name + ")@" + System.identityHashCode(this);
+    }
+
+    private void debug(String msg, Object... args)
+    {
+        if(_logger.isDebugEnabled())
+        {
+            _logger.debug(MessageFormat.format(msg, args));
+        }
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AMQQueue.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AsyncDeliveryConfig.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AsyncDeliveryConfig.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AsyncDeliveryConfig.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AsyncDeliveryConfig.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,53 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.configuration.Configured;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+
+public class AsyncDeliveryConfig
+{
+    private Executor _executor;
+
+    @Configured(path = "delivery.poolsize", defaultValue = "0")
+    public int poolSize;
+
+    public Executor getExecutor()
+    {
+        if (_executor == null)
+        {
+            if (poolSize > 0)
+            {
+                _executor = Executors.newFixedThreadPool(poolSize);
+            }
+            else
+            {
+                _executor = Executors.newCachedThreadPool();
+            }
+        }
+        return _executor;
+    }
+
+    public static Executor getAsyncDeliveryExecutor()
+    {
+        return ApplicationRegistry.getInstance().getConfiguredObject(AsyncDeliveryConfig.class).getExecutor();
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/AsyncDeliveryConfig.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/DefaultQueueRegistry.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/DefaultQueueRegistry.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/DefaultQueueRegistry.java (added)
+++ incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/DefaultQueueRegistry.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,47 @@
+/*
+ *
+ * Copyright (c) 2006 The Apache Software Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+package org.apache.qpid.server.queue;
+
+import org.apache.qpid.AMQException;
+
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class DefaultQueueRegistry implements QueueRegistry
+{
+    private ConcurrentMap<String, AMQQueue> _queueMap = new ConcurrentHashMap<String, AMQQueue>();
+
+    public DefaultQueueRegistry()
+    {
+    }
+
+    public void registerQueue(AMQQueue queue) throws AMQException
+    {
+        _queueMap.put(queue.getName(), queue);
+    }
+
+    public void unregisterQueue(String name) throws AMQException
+    {
+        _queueMap.remove(name);
+    }
+
+    public AMQQueue getQueue(String name)
+    {
+        return _queueMap.get(name);
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/broker/src/org/apache/qpid/server/queue/DefaultQueueRegistry.java
------------------------------------------------------------------------------
    svn:eol-style = native