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 [32/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/cluster/src/org/apache/qpid/server/cluster/ClientHandlerRegistry.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClientHandlerRegistry.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClientHandlerRegistry.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClientHandlerRegistry.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,132 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.client.handler.ConnectionCloseMethodHandler;
+import org.apache.qpid.client.handler.ConnectionOpenOkMethodHandler;
+import org.apache.qpid.client.handler.ConnectionSecureMethodHandler;
+import org.apache.qpid.client.handler.ConnectionStartMethodHandler;
+import org.apache.qpid.client.handler.ConnectionTuneMethodHandler;
+import org.apache.qpid.client.state.AMQState;
+import org.apache.qpid.client.state.AMQStateManager;
+import org.apache.qpid.client.state.IllegalStateTransitionException;
+import org.apache.qpid.client.state.StateAwareMethodListener;
+import org.apache.qpid.framing.AMQFrame;
+import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.ConnectionCloseBody;
+import org.apache.qpid.framing.ConnectionOpenOkBody;
+import org.apache.qpid.framing.ConnectionSecureBody;
+import org.apache.qpid.framing.ConnectionStartBody;
+import org.apache.qpid.framing.ConnectionTuneBody;
+
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * An extension of client.AMQStateManager that allows different handlers to be registered.
+ *
+ */
+public class ClientHandlerRegistry extends AMQStateManager
+{
+    private final Map<AMQState, ClientRegistry> _handlers = new HashMap<AMQState, ClientRegistry>();
+    private final MemberHandle _identity;
+
+    protected ClientHandlerRegistry(MemberHandle local)
+    {
+        super(AMQState.CONNECTION_NOT_STARTED, false);
+
+        _identity = local;
+
+        addHandler(ConnectionStartBody.class, ConnectionStartMethodHandler.getInstance(),
+                   AMQState.CONNECTION_NOT_STARTED);
+
+        addHandler(ConnectionTuneBody.class, new ConnectionTuneHandler(),
+                   AMQState.CONNECTION_NOT_TUNED);
+        addHandler(ConnectionSecureBody.class, ConnectionSecureMethodHandler.getInstance(),
+                   AMQState.CONNECTION_NOT_TUNED);
+        addHandler(ConnectionOpenOkBody.class, ConnectionOpenOkMethodHandler.getInstance(),
+                   AMQState.CONNECTION_NOT_OPENED);
+
+        addHandlers(ConnectionCloseBody.class, ConnectionCloseMethodHandler.getInstance(),
+                    AMQState.CONNECTION_NOT_STARTED,
+                    AMQState.CONNECTION_NOT_TUNED,
+                    AMQState.CONNECTION_NOT_OPENED);
+
+    }
+
+    private ClientRegistry state(AMQState state)
+    {
+        ClientRegistry registry = _handlers.get(state);
+        if (registry == null)
+        {
+            registry = new ClientRegistry();
+            _handlers.put(state, registry);
+        }
+        return registry;
+    }
+
+    protected StateAwareMethodListener findStateTransitionHandler(AMQState state, AMQMethodBody frame) throws IllegalStateTransitionException
+    {
+        ClientRegistry registry = _handlers.get(state);
+        return registry == null ? null : registry.getHandler(frame);
+    }
+
+
+    <A extends Class<AMQMethodBody>> void addHandlers(Class type, StateAwareMethodListener handler, AMQState... states)
+    {
+        for (AMQState state : states)
+        {
+            addHandler(type, handler, state);
+        }
+    }
+
+    <A extends Class<AMQMethodBody>> void addHandler(Class type, StateAwareMethodListener handler, AMQState state)
+    {
+        ClientRegistry registry = _handlers.get(state);
+        if (registry == null)
+        {
+            registry = new ClientRegistry();
+            _handlers.put(state, registry);
+        }
+        registry.add(type, handler);
+    }
+
+    static class ClientRegistry
+    {
+        private final Map<Class<? extends AMQMethodBody>, StateAwareMethodListener> registry
+                = new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener>();
+
+        <A extends Class<AMQMethodBody>> void add(A type, StateAwareMethodListener handler)
+        {
+            registry.put(type, handler);
+        }
+
+        StateAwareMethodListener getHandler(AMQMethodBody frame)
+        {
+            return registry.get(frame.getClass());
+        }
+    }
+
+    class ConnectionTuneHandler extends ConnectionTuneMethodHandler
+    {
+        protected AMQFrame createConnectionOpenFrame(int channel, String path, String capabilities, boolean insist)
+        {
+            return super.createConnectionOpenFrame(channel, path, ClusterCapability.add(capabilities, _identity), insist);
+        }
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClientHandlerRegistry.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterBuilder.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterBuilder.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterBuilder.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterBuilder.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,60 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.server.cluster.handler.ClusterMethodHandlerFactory;
+import org.apache.qpid.server.cluster.replay.RecordingMethodHandlerFactory;
+import org.apache.qpid.server.cluster.replay.ReplayStore;
+
+import java.net.InetSocketAddress;
+
+class ClusterBuilder
+{
+    private final LoadTable loadTable = new LoadTable();
+    private final ReplayStore replayStore = new ReplayStore();
+    private final MemberHandle handle;
+    private final GroupManager groupMgr;
+
+    ClusterBuilder(InetSocketAddress address)
+    {
+        handle = new SimpleMemberHandle(address.getHostName(), address.getPort()).resolve();
+        groupMgr = new DefaultGroupManager(handle, getBrokerFactory(), replayStore, loadTable);
+    }
+
+    GroupManager getGroupManager()
+    {
+        return groupMgr;
+    }
+
+    ServerHandlerRegistry getHandlerRegistry()
+    {
+        return new ServerHandlerRegistry(getHandlerFactory());
+    }
+
+    private MethodHandlerFactory getHandlerFactory()
+    {
+        MethodHandlerFactory factory = new ClusterMethodHandlerFactory(groupMgr, loadTable);
+        //need to wrap relevant handlers with recording handler for easy replay:
+        return new RecordingMethodHandlerFactory(factory, replayStore);
+    }
+
+    private BrokerFactory getBrokerFactory()
+    {
+        return new MinaBrokerProxyFactory(handle);
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterBuilder.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterCapability.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterCapability.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterCapability.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterCapability.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,55 @@
+/*
+ *
+ * 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.cluster;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public class ClusterCapability
+{
+    public static final String PATTERN = ".*\\bcluster_peer=(\\S*:\\d*)\b*.*";
+    public static final String PEER = "cluster_peer";
+
+    public static String add(String original, MemberHandle identity)
+    {
+        return original == null ? peer(identity) : original + " " + peer(identity);
+    }
+
+    private static String peer(MemberHandle identity)
+    {
+        return PEER + "=" + identity.getDetails();
+    }
+
+    public static boolean contains(String in)
+    {
+        return in != null && in.contains(in);
+    }
+
+    public static MemberHandle getPeer(String in)
+    {
+        Matcher matcher = Pattern.compile(PATTERN).matcher(in);
+        if (matcher.matches())
+        {
+            return new SimpleMemberHandle(matcher.group(1));
+        }
+        else
+        {
+            throw new RuntimeException("Could not find peer in '" + in + "'");
+        }
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusterCapability.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,190 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.log4j.Logger;
+import org.apache.mina.common.IoSession;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.codec.AMQCodecFactory;
+import org.apache.qpid.framing.AMQBody;
+import org.apache.qpid.framing.AMQFrame;
+import org.apache.qpid.framing.ConnectionOpenBody;
+import org.apache.qpid.framing.ConnectionSecureOkBody;
+import org.apache.qpid.framing.ConnectionStartOkBody;
+import org.apache.qpid.framing.ConnectionTuneOkBody;
+import org.apache.qpid.framing.ClusterMembershipBody;
+import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.protocol.AMQPFastProtocolHandler;
+import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.registry.IApplicationRegistry;
+import org.apache.qpid.server.cluster.util.LogMessage;
+
+import java.net.InetSocketAddress;
+
+public class ClusteredProtocolHandler extends AMQPFastProtocolHandler implements InductionBuffer.MessageHandler
+{
+    private static final Logger _logger = Logger.getLogger(ClusteredProtocolHandler.class);
+    private final InductionBuffer _peerBuffer = new InductionBuffer(this);
+    private final InductionBuffer _clientBuffer = new InductionBuffer(this);
+    private final GroupManager _groupMgr;
+    private final ServerHandlerRegistry _handlers;
+
+    public ClusteredProtocolHandler(InetSocketAddress address)
+    {
+        this(ApplicationRegistry.getInstance(), address);
+    }
+
+    public ClusteredProtocolHandler(IApplicationRegistry registry, InetSocketAddress address)
+    {
+        this(registry.getQueueRegistry(), registry.getExchangeRegistry(), address);
+    }
+
+    public ClusteredProtocolHandler(QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry, InetSocketAddress address)
+    {
+        super(queueRegistry, exchangeRegistry);
+        ClusterBuilder builder = new ClusterBuilder(address);
+        _groupMgr = builder.getGroupManager();
+        _handlers = builder.getHandlerRegistry();
+    }
+
+    public ClusteredProtocolHandler(ClusteredProtocolHandler handler)
+    {
+        super(handler);
+        _groupMgr = handler._groupMgr;
+        _handlers = handler._handlers;
+    }
+
+    protected void createSession(IoSession session, QueueRegistry queues, ExchangeRegistry exchanges, AMQCodecFactory codec) throws AMQException
+    {
+        new ClusteredProtocolSession(session, queues, exchanges, codec, new ServerHandlerRegistry(_handlers));
+    }
+
+    void connect(String join) throws Exception
+    {
+        if (join == null)
+        {
+            _groupMgr.establish();
+        }
+        else
+        {
+            _groupMgr.join(new SimpleMemberHandle(join));
+        }
+    }
+
+    private boolean inState(JoinState state)
+    {
+        return _groupMgr.getState().equals(state);
+    }
+
+    public void messageReceived(IoSession session, Object msg) throws Exception
+    {
+        JoinState state = _groupMgr.getState();
+        switch (state)
+        {
+            case JOINED:
+                _logger.debug(new LogMessage("Received {0}", msg));
+                super.messageReceived(session, msg);
+                break;
+            case JOINING:
+            case INITIATION:
+            case INDUCTION:
+                buffer(session, msg);
+                break;
+            default:
+                throw new AMQException("Received message while in state: " + state);
+        }
+        JoinState latest = _groupMgr.getState();
+        if (!latest.equals(state))
+        {
+            switch (latest)
+            {
+                case INDUCTION:
+                    _logger.info("Reached induction, delivering buffered message from peers");
+                    _peerBuffer.deliver();
+                    break;
+                case JOINED:
+                    _logger.info("Reached joined, delivering buffered message from clients");
+                    _clientBuffer.deliver();
+                    break;
+            }
+        }
+    }
+
+    private void buffer(IoSession session, Object msg) throws Exception
+    {
+        if (isBufferable(msg))
+        {
+            MemberHandle peer = ClusteredProtocolSession.getSessionPeer(session);
+            if (peer == null)
+            {
+                _logger.debug(new LogMessage("Buffering {0} for client", msg));
+                _clientBuffer.receive(session, msg);
+            }
+            else if (inState(JoinState.JOINING) && isMembershipAnnouncement(msg))
+            {
+                _logger.debug(new LogMessage("Initial membership [{0}] received from {1}", msg, peer));
+                super.messageReceived(session, msg);
+            }
+            else if (inState(JoinState.INITIATION) && _groupMgr.isLeader(peer))
+            {
+                _logger.debug(new LogMessage("Replaying {0} from leader ", msg));
+                super.messageReceived(session, msg);
+            }
+            else if (inState(JoinState.INDUCTION))
+            {
+                _logger.debug(new LogMessage("Replaying {0} from peer {1}", msg, peer));
+                super.messageReceived(session, msg);
+            }
+            else
+            {
+                _logger.debug(new LogMessage("Buffering {0} for peer {1}", msg, peer));
+                _peerBuffer.receive(session, msg);
+            }
+        }
+        else
+        {
+            _logger.debug(new LogMessage("Received {0}", msg));
+            super.messageReceived(session, msg);
+        }
+    }
+
+    public void deliver(IoSession session, Object msg) throws Exception
+    {
+        _logger.debug(new LogMessage("Delivering {0}", msg));
+        super.messageReceived(session, msg);
+    }
+
+    private boolean isMembershipAnnouncement(Object msg)
+    {
+        return msg instanceof AMQFrame && (((AMQFrame) msg).bodyFrame instanceof ClusterMembershipBody);
+    }
+
+    private boolean isBufferable(Object msg)
+    {
+        return msg instanceof AMQFrame && isBuffereable(((AMQFrame) msg).bodyFrame);
+    }
+
+    private boolean isBuffereable(AMQBody body)
+    {
+        return !(body instanceof ConnectionStartOkBody ||
+                body instanceof ConnectionTuneOkBody ||
+                body instanceof ConnectionSecureOkBody ||
+                body instanceof ConnectionOpenBody);
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolHandler.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolSession.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolSession.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolSession.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolSession.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,132 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.mina.common.IoSession;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.codec.AMQCodecFactory;
+import org.apache.qpid.server.AMQChannel;
+import org.apache.qpid.server.exchange.ExchangeRegistry;
+import org.apache.qpid.server.protocol.AMQMinaProtocolSession;
+import org.apache.qpid.server.protocol.AMQProtocolSession;
+import org.apache.qpid.server.queue.AMQMessage;
+import org.apache.qpid.server.queue.QueueRegistry;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.registry.IApplicationRegistry;
+import org.apache.qpid.server.state.AMQStateManager;
+
+public class ClusteredProtocolSession extends AMQMinaProtocolSession
+{
+    private MemberHandle _peer;
+
+    public ClusteredProtocolSession(IoSession session, QueueRegistry queueRegistry, ExchangeRegistry exchangeRegistry, AMQCodecFactory codecFactory, AMQStateManager stateManager)
+            throws AMQException
+    {
+        super(session, queueRegistry, exchangeRegistry, codecFactory, stateManager);
+    }
+
+    public boolean isPeerSession()
+    {
+        return _peer != null;
+    }
+
+    public void setSessionPeer(MemberHandle peer)
+    {
+        _peer = peer;
+    }
+
+    public MemberHandle getSessionPeer()
+    {
+        return _peer;
+    }
+
+    public AMQChannel getChannel(int channelId)
+        throws AMQException
+    {
+        AMQChannel channel = super.getChannel(channelId);
+        if (isPeerSession() && channel == null)
+        {
+            channel = new OneUseChannel(channelId);
+            addChannel(channel);
+        }
+        return channel;
+    }
+
+    public static boolean isPeerSession(IoSession session)
+    {
+        return isPeerSession(getAMQProtocolSession(session));
+    }
+
+    public static boolean isPeerSession(AMQProtocolSession session)
+    {
+        return session instanceof ClusteredProtocolSession && ((ClusteredProtocolSession) session).isPeerSession();
+    }
+
+    public static void setSessionPeer(AMQProtocolSession session, MemberHandle peer)
+    {
+        ((ClusteredProtocolSession) session).setSessionPeer(peer);
+    }
+
+    public static MemberHandle getSessionPeer(AMQProtocolSession session)
+    {
+        return ((ClusteredProtocolSession) session).getSessionPeer();
+    }
+
+    public static MemberHandle getSessionPeer(IoSession session)
+    {
+        return getSessionPeer(getAMQProtocolSession(session));
+    }
+
+    /**
+     * Cleans itself up after delivery of a message (publish frame, header and optional body frame(s))
+     */
+    private class OneUseChannel extends AMQChannel
+    {
+        public OneUseChannel(int channelId)
+            throws AMQException
+        {
+            this(channelId, ApplicationRegistry.getInstance());
+        }
+
+        public OneUseChannel(int channelId, IApplicationRegistry registry)
+            throws AMQException
+        {
+            super(channelId,
+                  registry.getMessageStore(),
+                  registry.getExchangeRegistry());
+        }
+
+        protected void routeCurrentMessage() throws AMQException
+        {
+            super.routeCurrentMessage();
+            removeChannel(getChannelId());
+        }
+    }
+
+    public static boolean isPayloadFromPeer(AMQMessage payload)
+    {
+        return isPeerSession(payload.getPublisher());
+    }
+
+    public static boolean canRelay(AMQMessage payload, MemberHandle target)
+    {
+        //can only relay client messages that have not already been relayed to the given target
+        return !isPayloadFromPeer(payload) && !payload.checkToken(target);
+    }
+
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ClusteredProtocolSession.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ConnectionStatusMonitor.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ConnectionStatusMonitor.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ConnectionStatusMonitor.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ConnectionStatusMonitor.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,77 @@
+/*
+ *
+ * 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.cluster;
+
+import java.io.IOException;
+
+class ConnectionStatusMonitor
+{
+    private boolean _complete;
+    private boolean _redirected;
+    private String _host;
+    private int _port;
+    private RuntimeException _error;
+
+    synchronized void opened()
+    {
+        _complete = true;
+        notifyAll();
+    }
+
+    synchronized void redirect(String host, int port)
+    {
+        _complete = true;
+        _redirected = true;
+        this._host = host;
+        this._port = port;
+    }
+
+    synchronized void failed(RuntimeException e)
+    {
+        _error = e;
+        _complete = true;
+    }
+
+    synchronized boolean waitUntilOpen() throws InterruptedException
+    {
+        while (!_complete)
+        {
+            wait();
+        }
+        if (_error != null)
+        {
+            throw _error;
+        }
+        return !_redirected;
+    }
+
+    synchronized boolean isOpened()
+    {
+        return _complete;
+    }
+
+    String getHost()
+    {
+        return _host;
+    }
+
+    int getPort()
+    {
+        return _port;
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ConnectionStatusMonitor.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/DefaultGroupManager.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/DefaultGroupManager.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/DefaultGroupManager.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/DefaultGroupManager.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,366 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.log4j.Logger;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.ClusterJoinBody;
+import org.apache.qpid.framing.ClusterLeaveBody;
+import org.apache.qpid.framing.ClusterMembershipBody;
+import org.apache.qpid.framing.ClusterPingBody;
+import org.apache.qpid.framing.ClusterSuspectBody;
+import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.server.cluster.policy.StandardPolicies;
+import org.apache.qpid.server.cluster.replay.ReplayManager;
+import org.apache.qpid.server.cluster.util.LogMessage;
+import org.apache.qpid.server.cluster.util.InvokeMultiple;
+
+import java.util.List;
+
+public class DefaultGroupManager implements GroupManager, MemberFailureListener, BrokerFactory, StandardPolicies
+{
+    private static final Logger _logger = Logger.getLogger(DefaultGroupManager.class);
+    private final LoadTable _loadTable;
+    private final BrokerFactory _factory;
+    private final ReplayManager _replayMgr;
+    private final BrokerGroup _group;
+
+    DefaultGroupManager(MemberHandle handle, BrokerFactory factory, ReplayManager replayMgr)
+    {
+        this(handle, factory, replayMgr, new LoadTable());
+    }
+
+    DefaultGroupManager(MemberHandle handle, BrokerFactory factory, ReplayManager replayMgr, LoadTable loadTable)
+    {
+        handle = SimpleMemberHandle.resolve(handle);
+        _logger.info(handle);
+        _loadTable = loadTable;
+        _factory = factory;
+        _replayMgr = replayMgr;
+        _group = new BrokerGroup(handle, _replayMgr, this);
+    }
+
+    public JoinState getState()
+    {
+        return _group.getState();
+    }
+
+    public void addMemberhipChangeListener(MembershipChangeListener l)
+    {
+        _group.addMemberhipChangeListener(l);
+    }
+
+    public void removeMemberhipChangeListener(MembershipChangeListener l)
+    {
+        _group.removeMemberhipChangeListener(l);
+    }
+
+    public void broadcast(Sendable message) throws AMQException
+    {
+        for (Broker b : _group.getPeers())
+        {
+            b.send(message, null);
+        }
+    }
+
+    public void broadcast(Sendable message, BroadcastPolicy policy, GroupResponseHandler callback) throws AMQException
+    {
+        GroupRequest request = new GroupRequest(message, policy, callback);
+        for (Broker b : _group.getPeers())
+        {
+            b.invoke(request);
+        }
+        request.finishedSend();
+    }
+
+    public void send(MemberHandle broker, Sendable message) throws AMQException
+    {
+        Broker destination = findBroker(broker);
+        if(destination == null)
+        {
+            _logger.warn(new LogMessage("Invalid destination sending {0}. {1} not known", message, broker));            
+        }
+        else
+        {
+            destination.send(message, null);
+            _logger.debug(new LogMessage("Sent {0} to {1}", message, broker));
+        }
+    }
+
+    private void send(Broker broker, Sendable message, ResponseHandler handler) throws AMQException
+    {
+        broker.send(message, handler);
+    }
+
+    private void ping(Broker b) throws AMQException
+    {
+        ClusterPingBody ping = new ClusterPingBody();
+        ping.broker = _group.getLocal().getDetails();
+        ping.responseRequired = true;
+        ping.load = _loadTable.getLocalLoad();
+        BlockingHandler handler = new BlockingHandler();
+        send(getLeader(), new SimpleSendable(ping), handler);
+        handler.waitForCompletion();
+        if (handler.failed())
+        {
+            if (isLeader())
+            {
+                handleFailure(b);
+            }
+            else
+            {
+                suspect(b);
+            }
+        }
+        else
+        {
+            _loadTable.setLoad(b, ((ClusterPingBody) handler.getResponse()).load);
+        }
+    }
+
+    public void handlePing(MemberHandle member, long load)
+    {
+        _loadTable.setLoad(findBroker(member), load);
+    }
+
+    public Member redirect()
+    {
+        return _loadTable.redirect();
+    }
+
+    public void establish()
+    {
+        _group.establish();
+        _logger.info("Established cluster");
+    }
+
+    public void join(MemberHandle member) throws AMQException
+    {
+        member = SimpleMemberHandle.resolve(member);
+
+        Broker leader = connectToLeader(member);
+        _logger.info(new LogMessage("Connected to {0}. joining", leader));
+        ClusterJoinBody join = new ClusterJoinBody();
+        join.broker = _group.getLocal().getDetails();
+        send(leader, new SimpleSendable(join));
+    }
+
+    private Broker connectToLeader(MemberHandle member) throws AMQException
+    {
+        try
+        {
+            return _group.connectToLeader(member);
+        }
+        catch (Exception e)
+        {
+            throw new AMQException("Could not connect to leader: " + e, e);
+        }
+    }
+
+    public void leave() throws AMQException
+    {
+        ClusterLeaveBody leave = new ClusterLeaveBody();
+        leave.broker = _group.getLocal().getDetails();
+        send(getLeader(), new SimpleSendable(leave));
+    }
+
+    private void suspect(MemberHandle broker) throws AMQException
+    {
+        if (_group.isLeader(broker))
+        {
+            //need new leader, if this broker is next in line it can assume leadership
+            if (_group.assumeLeadership())
+            {
+                announceMembership();
+            }
+            else
+            {
+                _logger.warn(new LogMessage("Leader failed. Expecting {0} to succeed.", _group.getMembers().get(1)));
+            }
+        }
+        else
+        {
+            ClusterSuspectBody suspect = new ClusterSuspectBody();
+            suspect.broker = broker.getDetails();
+            send(getLeader(), new SimpleSendable(suspect));
+        }
+    }
+
+
+    public void handleJoin(MemberHandle member) throws AMQException
+    {
+        _logger.info(new LogMessage("Handling join request for {0}", member));
+        if(isLeader())
+        {
+            //connect to the host and port specified:
+            Broker prospect = connectToProspect(member);
+            announceMembership();
+            List<AMQMethodBody> msgs = _replayMgr.replay(true);
+            _logger.info(new LogMessage("Replaying {0} from leader to {1}", msgs, prospect));
+            prospect.replay(msgs);
+        }
+        else
+        {
+            //pass request on to leader:
+            ClusterJoinBody request = new ClusterJoinBody();
+            request.broker = member.getDetails();
+            Broker leader = getLeader();
+            send(leader, new SimpleSendable(request));
+            _logger.info(new LogMessage("Passed join request for {0} to {1}", member, leader));
+        }
+    }
+
+    private Broker connectToProspect(MemberHandle member) throws AMQException
+    {
+        try
+        {
+            return _group.connectToProspect(member);
+        }
+        catch (Exception e)
+        {
+            e.printStackTrace();
+            throw new AMQException("Could not connect to prospect: " + e, e);
+        }
+    }
+
+    public void handleLeave(MemberHandle member) throws AMQException
+    {
+        handleFailure(findBroker(member));
+        announceMembership();
+    }
+
+    public void handleSuspect(MemberHandle member) throws AMQException
+    {
+        Broker b = findBroker(member);
+        if(b != null)
+        {
+            //ping it to check it has failed, ping will handle failure if it has
+            ping(b);
+            announceMembership();
+        }
+    }
+
+    public void handleSynch(MemberHandle member)
+    {
+        _group.synched(member);
+    }
+
+    private ClusterMembershipBody createAnnouncement(String membership)
+    {
+        ClusterMembershipBody announce = new ClusterMembershipBody();
+        //TODO: revise this way of converting String to bytes...
+        announce.members = membership.getBytes();
+        return announce;
+    }
+
+    private void announceMembership() throws AMQException
+    {
+        String membership = SimpleMemberHandle.membersToString(_group.getMembers());
+        ClusterMembershipBody announce = createAnnouncement(membership);
+        broadcast(new SimpleSendable(announce));
+        _logger.info(new LogMessage("Membership announcement sent: {0}", membership));
+    }
+
+    private void handleFailure(Broker peer)
+    {
+        peer.remove();
+        _group.remove(peer);
+    }
+
+    public void handleMembershipAnnouncement(String membership) throws AMQException
+    {
+        _group.setMembers(SimpleMemberHandle.stringToMembers(membership));
+        _logger.info(new LogMessage("Membership announcement received: {0}", membership));
+    }
+
+    public boolean isLeader()
+    {
+        return _group.isLeader();
+    }
+
+    public boolean isLeader(MemberHandle handle)
+    {
+        return _group.isLeader(handle);
+    }
+
+    public Broker getLeader()
+    {
+        return _group.getLeader();
+    }
+
+    private Broker findBroker(MemberHandle handle)
+    {
+        return _group.findBroker(handle, false);
+    }
+
+    public Member getMember(MemberHandle handle)
+    {
+        return findBroker(handle);
+    }
+
+    public boolean isMember(MemberHandle member)
+    {
+        for (MemberHandle handle : _group.getMembers())
+        {
+            if (handle.matches(member))
+            {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public MemberHandle getLocal()
+    {
+        return _group.getLocal();
+    }
+
+    public void failed(MemberHandle member)
+    {
+        if (isLeader())
+        {
+            handleFailure(findBroker(member));
+            try
+            {
+                announceMembership();
+            }
+            catch (AMQException e)
+            {
+                _logger.error("Error announcing failure: " + e, e);
+            }
+        }
+        else
+        {
+            try
+            {
+                suspect(member);
+            }
+            catch (AMQException e)
+            {
+                _logger.error("Error sending suspect: " + e, e);
+            }
+        }
+    }
+
+    public Broker create(MemberHandle handle)
+    {
+        Broker broker = _factory.create(handle);
+        broker.addFailureListener(this);
+        return broker;
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/DefaultGroupManager.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupManager.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupManager.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupManager.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupManager.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,69 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.AMQException;
+
+public interface GroupManager
+{
+    /**
+     * Establish a new cluster with the local member as the leader.
+     */
+    public void establish();
+
+    /**
+     * Join the cluster to which member belongs 
+     */
+    public void join(MemberHandle member) throws AMQException;
+
+    public void broadcast(Sendable message) throws AMQException;
+
+    public void broadcast(Sendable message, BroadcastPolicy policy, GroupResponseHandler callback) throws AMQException;
+
+    public void send(MemberHandle broker, Sendable message) throws AMQException;
+
+    public void leave() throws AMQException;
+
+    public void handleJoin(MemberHandle member) throws AMQException;
+
+    public void handleLeave(MemberHandle member) throws AMQException;
+
+    public void handleSuspect(MemberHandle member) throws AMQException;
+
+    public void handlePing(MemberHandle member, long load);
+
+    public void handleMembershipAnnouncement(String membership) throws AMQException;
+
+    public void handleSynch(MemberHandle member);
+
+    public boolean isLeader();
+
+    public boolean isLeader(MemberHandle handle);
+
+    public boolean isMember(MemberHandle member);
+
+    public MemberHandle redirect();
+
+    public MemberHandle getLocal();
+
+    public JoinState getState();
+
+    public void addMemberhipChangeListener(MembershipChangeListener l);
+
+    public void removeMemberhipChangeListener(MembershipChangeListener l);
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupManager.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupRequest.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupRequest.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupRequest.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupRequest.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,104 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQMethodBody;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Represents a method sent to a group of Member instances. Manages the responses,
+ * completion and callback.
+ *
+ */
+class GroupRequest
+{
+    private final Map<Member, AMQMethodBody> _responses = new HashMap<Member, AMQMethodBody>();
+    private final List<Member> _brokers = new ArrayList<Member>();
+    private boolean _sent;
+
+    private final Sendable _request;
+    private final BroadcastPolicy _policy;
+    private final GroupResponseHandler _callback;
+
+    GroupRequest(Sendable request, BroadcastPolicy policy, GroupResponseHandler callback)
+    {
+        _request = request;
+        _policy = policy;
+        _callback = callback;
+    }
+
+    void send(int channel, Member session) throws AMQException
+    {
+        _brokers.add(session);
+        _request.send(channel, session);
+    }
+
+    boolean finishedSend()
+    {
+        _sent = true;
+        return checkCompletion();
+    }
+
+    public boolean responseReceived(Member broker, AMQMethodBody response)
+    {
+        _responses.put(broker, response);
+        return checkCompletion();
+    }
+
+    public boolean removed(Member broker)
+    {
+        _brokers.remove(broker);
+        return checkCompletion();
+    }
+
+    private synchronized boolean checkCompletion()
+    {
+        return isComplete() && callback();
+    }
+
+    boolean isComplete()
+    {
+        return _sent && _policy != null && _policy.isComplete(_responses.size(), _brokers.size());
+    }
+
+    boolean callback()
+    {
+        _callback.response(getResults(), _brokers);
+        return true;
+    }
+
+    List<AMQMethodBody> getResults()
+    {
+        List<AMQMethodBody> results = new ArrayList<AMQMethodBody>(_brokers.size());
+        for (Member b : _brokers)
+        {
+            results.add(_responses.get(b));
+        }
+        return results;
+    }
+
+    public String toString()
+    {
+        return "GroupRequest{request=" + _request +", brokers=" + _brokers + ", responses=" + _responses + "}";
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupRequest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupResponseHandler.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupResponseHandler.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupResponseHandler.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupResponseHandler.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,28 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.framing.AMQMethodBody;
+
+import java.util.List;
+
+public interface GroupResponseHandler
+{
+    //Note: this implies that the response to a group request will always be a method body...
+    public void response(List<AMQMethodBody> responses, List<Member> members);
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/GroupResponseHandler.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/InductionBuffer.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/InductionBuffer.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/InductionBuffer.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/InductionBuffer.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,87 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.mina.common.IoSession;
+
+import java.util.LinkedList;
+import java.util.Queue;
+
+/**
+ * Buffers any received messages until join completes.
+ *
+ */
+class InductionBuffer
+{
+    private final Queue<Message> _buffer = new LinkedList<Message>();
+    private final MessageHandler _handler;
+    private boolean _buffering = true;
+
+    InductionBuffer(MessageHandler handler)
+    {
+        _handler = handler;
+    }
+
+    private void process() throws Exception
+    {
+        for (Message o = _buffer.poll(); o != null; o = _buffer.poll())
+        {
+            o.deliver(_handler);
+        }
+        _buffering = false;
+    }
+
+    synchronized void deliver() throws Exception
+    {
+        process();
+    }
+
+    synchronized void receive(IoSession session, Object msg) throws Exception
+    {
+        if (_buffering)
+        {
+            _buffer.offer(new Message(session, msg));
+        }
+        else
+        {
+            _handler.deliver(session, msg);
+        }
+    }
+
+    private static class Message
+    {
+        private final IoSession _session;
+        private final Object _msg;
+
+        Message(IoSession session, Object msg)
+        {
+            _session = session;
+            _msg = msg;
+        }
+
+        void deliver(MessageHandler handler) throws Exception
+        {
+            handler.deliver(_session, _msg);
+        }
+    }
+
+    static interface MessageHandler
+    {
+        public void deliver(IoSession session, Object msg) throws Exception;
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/InductionBuffer.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/JoinState.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/JoinState.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/JoinState.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/JoinState.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,23 @@
+/*
+ *
+ * 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.cluster;
+
+public enum JoinState
+{
+    UNINITIALISED, JOINING, INITIATION, INDUCTION, JOINED
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/JoinState.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/LoadTable.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/LoadTable.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/LoadTable.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/LoadTable.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,104 @@
+/*
+ *
+ * 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.cluster;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.PriorityQueue;
+
+/**
+ * Maintains loading information about the local member and its cluster peers.
+ *
+ */
+public class LoadTable
+{
+    private final Map<MemberHandle, Loading> _peers = new HashMap<MemberHandle, Loading>();
+    private final PriorityQueue<Loading> _loads = new PriorityQueue<Loading>();
+    private final Loading _local = new Loading(null);
+
+    public LoadTable()
+    {
+        _loads.add(_local);
+    }
+
+    public void setLoad(Member member, long load)
+    {
+        synchronized (_peers)
+        {
+            Loading loading = _peers.get(member);
+            if (loading == null)
+            {
+                loading = new Loading(member);
+                synchronized (_loads)
+                {
+                    _loads.add(loading);
+                }
+                _peers.put(member, loading);
+            }
+            loading.load = load;
+        }
+    }
+
+    public void incrementLocalLoad()
+    {
+        synchronized (_local)
+        {
+            _local.load++;
+        }
+    }
+
+    public void decrementLocalLoad()
+    {
+        synchronized (_local)
+        {
+            _local.load--;
+        }
+    }
+
+    public long getLocalLoad()
+    {
+        synchronized (_local)
+        {
+            return _local.load;
+        }
+    }
+
+    public Member redirect()
+    {
+        synchronized (_loads)
+        {
+            return _loads.peek().member;
+        }
+    }
+
+    private static class Loading implements Comparable
+    {
+        private final Member member;
+        private long load;
+
+        Loading(Member member)
+        {
+            this.member = member;
+        }
+
+        public int compareTo(Object o)
+        {
+            return (int) (load - ((Loading) o).load);
+        }
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/LoadTable.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Main.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Main.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Main.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Main.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,117 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.CommandLineParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionBuilder;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.PosixParser;
+import org.apache.log4j.Logger;
+import org.apache.mina.common.IoAcceptor;
+import org.apache.mina.transport.socket.nio.SocketAcceptor;
+import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
+import org.apache.mina.transport.socket.nio.SocketSessionConfig;
+import org.apache.qpid.pool.ReadWriteThreadModel;
+import org.apache.qpid.server.registry.ApplicationRegistry;
+import org.apache.qpid.server.registry.ConfigurationFileApplicationRegistry;
+import org.apache.qpid.server.transport.ConnectorConfiguration;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+
+/**
+ * TODO: This is a cut-and-paste from the original broker Main class. Would be preferrable
+ * to make that class more reuseable to avoid all this duplication.
+ *
+ */
+public class Main extends org.apache.qpid.server.Main
+{
+    private static final Logger _logger = Logger.getLogger(Main.class);
+
+    protected Main(String[] args)
+    {
+        super(args);
+    }
+
+    protected void setOptions(Options otions)
+    {
+        super.setOptions(options);
+
+        //extensions:
+        Option join = OptionBuilder.withArgName("join").hasArg().withDescription("Join the specified cluster member. Overrides any value in the config file").
+                withLongOpt("join").create("j");
+        options.addOption(join);
+    }
+
+    protected void bind(int port, ConnectorConfiguration connectorConfig)
+    {
+        try
+        {
+            IoAcceptor acceptor = new SocketAcceptor();
+            SocketAcceptorConfig sconfig = (SocketAcceptorConfig) acceptor.getDefaultConfig();
+            SocketSessionConfig sc = (SocketSessionConfig) sconfig.getSessionConfig();
+
+            sc.setReceiveBufferSize(connectorConfig.socketReceiveBufferSize);
+            sc.setSendBufferSize(connectorConfig.socketWriteBuferSize);
+            sc.setTcpNoDelay(true);
+
+            // if we do not use the executor pool threading model we get the default leader follower
+            // implementation provided by MINA
+            if (connectorConfig.enableExecutorPool)
+            {
+                sconfig.setThreadModel(new ReadWriteThreadModel());
+            }
+
+            String host = InetAddress.getLocalHost().getHostName();
+            ClusteredProtocolHandler handler = new ClusteredProtocolHandler(new InetSocketAddress(host, port));
+            if (connectorConfig.enableNonSSL)
+            {
+                acceptor.bind(new InetSocketAddress(port), handler, sconfig);
+                _logger.info("Qpid.AMQP listening on non-SSL port " + port);
+                handler.connect(commandLine.getOptionValue("j"));
+            }
+
+            if (connectorConfig.enableSSL)
+            {
+                ClusteredProtocolHandler sslHandler = new ClusteredProtocolHandler(handler);
+                sslHandler.setUseSSL(true);
+                acceptor.bind(new InetSocketAddress(connectorConfig.sslPort), handler, sconfig);
+                _logger.info("Qpid.AMQP listening on SSL port " + connectorConfig.sslPort);
+            }
+        }
+        catch (IOException e)
+        {
+            _logger.error("Unable to bind service to registry: " + e, e);
+        }
+        catch (Exception e)
+        {
+            _logger.error("Unable to connect to cluster: " + e, e);
+        }
+    }
+
+    public static void main(String[] args)
+    {
+        new Main(args);
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Main.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Member.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Member.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Member.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Member.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,28 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQDataBlock;
+
+public interface Member extends MemberHandle
+{
+    public void send(AMQDataBlock data) throws AMQException;
+
+    public void addFailureListener(MemberFailureListener listener);
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Member.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberFailureListener.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberFailureListener.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberFailureListener.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberFailureListener.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,23 @@
+/*
+ *
+ * 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.cluster;
+
+interface MemberFailureListener
+{
+    public void failed(MemberHandle member);
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberFailureListener.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberHandle.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberHandle.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberHandle.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberHandle.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,31 @@
+/*
+ *
+ * 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.cluster;
+
+public interface MemberHandle
+{
+    public String getHost();
+
+    public int getPort();
+
+    public boolean matches(MemberHandle m);
+
+    public boolean matches(String host, int port);
+
+    public String getDetails();
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MemberHandle.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MembershipChangeListener.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MembershipChangeListener.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MembershipChangeListener.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MembershipChangeListener.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,25 @@
+/*
+ *
+ * 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.cluster;
+
+import java.util.List;
+
+public interface MembershipChangeListener
+{
+    public void changed(List<MemberHandle> members);
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MembershipChangeListener.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandler.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandler.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandler.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandler.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,26 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.AMQException;
+import org.apache.qpid.framing.AMQMethodBody;
+
+interface MethodHandler
+{
+    public void handle(int channel, AMQMethodBody method) throws AMQException;
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandler.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerFactory.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerFactory.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerFactory.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerFactory.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,25 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.server.state.AMQState;
+
+public interface MethodHandlerFactory
+{
+    public MethodHandlerRegistry register(AMQState state, MethodHandlerRegistry registry);
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerFactory.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerRegistry.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerRegistry.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerRegistry.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerRegistry.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,41 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.server.state.StateAwareMethodListener;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class MethodHandlerRegistry
+{
+    private final Map<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>> registry =
+            new HashMap<Class<? extends AMQMethodBody>, StateAwareMethodListener<? extends AMQMethodBody>>();
+
+    public <A extends AMQMethodBody, B extends Class<A>> MethodHandlerRegistry addHandler(B type, StateAwareMethodListener<A> handler)
+    {
+        registry.put(type, handler);
+        return this;
+    }
+
+    public <B extends AMQMethodBody> StateAwareMethodListener<B> getHandler(B frame)
+    {
+        return (StateAwareMethodListener<B>) registry.get(frame.getClass());
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MethodHandlerRegistry.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxy.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxy.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxy.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxy.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,269 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.log4j.Logger;
+import org.apache.mina.common.ConnectFuture;
+import org.apache.mina.common.IoHandlerAdapter;
+import org.apache.mina.common.IoSession;
+import org.apache.mina.common.RuntimeIOException;
+import org.apache.mina.filter.codec.ProtocolCodecFilter;
+import org.apache.mina.transport.socket.nio.SocketConnector;
+import org.apache.mina.transport.socket.nio.SocketConnectorConfig;
+import org.apache.mina.transport.socket.nio.SocketSessionConfig;
+import org.apache.qpid.AMQException;
+import org.apache.qpid.server.cluster.util.LogMessage;
+import org.apache.qpid.client.state.AMQState;
+import org.apache.qpid.codec.AMQCodecFactory;
+import org.apache.qpid.framing.AMQBody;
+import org.apache.qpid.framing.AMQDataBlock;
+import org.apache.qpid.framing.AMQFrame;
+import org.apache.qpid.framing.AMQMethodBody;
+import org.apache.qpid.framing.ConnectionRedirectBody;
+import org.apache.qpid.framing.ProtocolInitiation;
+import org.apache.qpid.framing.ProtocolVersionList;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+
+/**
+ * A 'client stub' for a remote cluster peer, using MINA for IO Layer
+ *
+ */
+public class MinaBrokerProxy extends Broker implements MethodHandler
+{
+    private static final Logger _logger = Logger.getLogger(MinaBrokerProxy.class);
+    private final ConnectionStatusMonitor _connectionMonitor = new ConnectionStatusMonitor();
+    private final ClientHandlerRegistry _legacyHandler;
+    private final MinaBinding _binding = new MinaBinding();
+    private final MemberHandle _local;
+    private IoSession _session;
+    private MethodHandler _handler;
+    private Iterable<AMQMethodBody> _replay;
+
+    MinaBrokerProxy(String host, int port, MemberHandle local)
+    {
+        super(host, port);
+        _local = local;
+        _legacyHandler = new ClientHandlerRegistry(local);
+    }
+
+    private void init(IoSession session)
+    {
+        _session = session;
+        _handler = new ClientAdapter(session, _legacyHandler);
+    }
+
+    private ConnectFuture connectImpl()
+    {
+        _logger.info("Connecting to cluster peer: " + getDetails());
+        SocketConnector ioConnector = new SocketConnector();
+        SocketConnectorConfig cfg = (SocketConnectorConfig) ioConnector.getDefaultConfig();
+
+        SocketSessionConfig scfg = (SocketSessionConfig) cfg.getSessionConfig();
+        scfg.setTcpNoDelay(true);
+        scfg.setSendBufferSize(32768);
+        scfg.setReceiveBufferSize(32768);
+        InetSocketAddress address = new InetSocketAddress(getHost(), getPort());
+        return ioConnector.connect(address, _binding);
+    }
+
+    //extablish connection without handling redirect
+    boolean connect() throws IOException, InterruptedException
+    {
+        ConnectFuture future = connectImpl();
+        // wait for connection to complete
+        future.join();
+        // we call getSession which throws an IOException if there has been an error connecting
+        try
+        {
+            future.getSession();
+        }
+        catch (RuntimeIOException e)
+        {
+            _connectionMonitor.failed(e);
+            _logger.error(new LogMessage("Could not connect to {0}: {1}", this, e), e);
+            throw e;
+        }
+        return _connectionMonitor.waitUntilOpen();
+    }
+
+    void connectAsynch(Iterable<AMQMethodBody> msgs)
+    {
+        _replay = msgs;
+        connectImpl();
+    }
+
+    void replay(Iterable<AMQMethodBody> msgs)
+    {
+        _replay = msgs;
+        if(_connectionMonitor.isOpened())
+        {
+            replay();
+        }
+    }
+
+    //establish connection, handling redirect if required...
+    Broker connectToCluster() throws IOException, InterruptedException
+    {
+        connect();
+        //wait until the connection is open or get a redirection
+        if (_connectionMonitor.waitUntilOpen())
+        {
+            return this;
+        }
+        else
+        {
+            Broker broker = new MinaBrokerProxy(_connectionMonitor.getHost(), _connectionMonitor.getPort(), _local);
+            broker.connect();
+            return broker;
+        }
+    }
+
+    public void send(AMQDataBlock data) throws AMQException
+    {
+        if (_session == null)
+        {
+            try
+            {
+                _connectionMonitor.waitUntilOpen();
+            }
+            catch (Exception e)
+            {
+                throw new AMQException("Failed to send " + data + ": " + e, e);
+            }
+        }
+        _session.write(data);
+    }
+
+    private void replay()
+    {
+        if(_replay != null)
+        {
+            for(AMQMethodBody b : _replay)
+            {
+                _session.write(new AMQFrame(0, b));
+            }
+        }
+    }
+
+    public void handle(int channel, AMQMethodBody method) throws AMQException
+    {
+        _logger.info(new LogMessage("Handling method: {0} for channel {1}", method, channel));
+        if (!handleResponse(channel, method))
+        {
+            _logger.warn(new LogMessage("Unhandled method: {0} for channel {1}", method, channel));
+        }
+    }
+
+    private void handleMethod(int channel, AMQMethodBody method) throws AMQException
+    {
+        if (method instanceof ConnectionRedirectBody)
+        {
+            //signal redirection to waiting thread
+            ConnectionRedirectBody redirect = (ConnectionRedirectBody) method;
+            String[] parts = redirect.host.split(":");
+            _connectionMonitor.redirect(parts[0], Integer.parseInt(parts[1]));
+        }
+        else
+        {
+            _handler.handle(channel, method);
+            if (AMQState.CONNECTION_OPEN.equals(_legacyHandler.getCurrentState()) && _handler != this)
+            {
+                _handler = this;
+                _logger.info(new LogMessage("Connection opened, handler switched"));
+                //replay any messages:
+                replay();
+                //signal waiting thread:
+                _connectionMonitor.opened();
+            }
+        }
+    }
+
+    private void handleFrame(AMQFrame frame) throws AMQException
+    {
+        AMQBody body = frame.bodyFrame;
+        if (body instanceof AMQMethodBody)
+        {
+            handleMethod(frame.channel, (AMQMethodBody) body);
+        }
+        else
+        {
+            throw new AMQException("Client only expects method body, got: " + body);
+        }
+    }
+
+    public String toString()
+    {
+        return "MinaBrokerProxy[" + (_session == null ? super.toString() : _session.getRemoteAddress()) + "]";
+    }
+
+    private class MinaBinding extends IoHandlerAdapter implements ProtocolVersionList
+    {
+        public void sessionCreated(IoSession session) throws Exception
+        {
+            init(session);
+            _logger.info(new LogMessage("{0}: created", MinaBrokerProxy.this));
+            ProtocolCodecFilter pcf = new ProtocolCodecFilter(new AMQCodecFactory(false));
+            session.getFilterChain().addLast("protocolFilter", pcf);
+            
+            /* 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;
+            session.write(new ProtocolInitiation(pv[i][PROTOCOL_MAJOR], pv[i][PROTOCOL_MINOR]));
+        }
+
+        public void sessionOpened(IoSession session) throws Exception
+        {
+            _logger.info(new LogMessage("{0}: opened", MinaBrokerProxy.this));
+        }
+
+        public void sessionClosed(IoSession session) throws Exception
+        {
+            _logger.info(new LogMessage("{0}: closed", MinaBrokerProxy.this));
+        }
+
+        public void exceptionCaught(IoSession session, Throwable throwable) throws Exception
+        {
+            _logger.error(new LogMessage("{0}: received {1}", MinaBrokerProxy.this, throwable), throwable);
+            if (! (throwable instanceof IOException))
+            {
+                _session.close();
+            }
+            failed();
+        }
+
+        public void messageReceived(IoSession session, Object object) throws Exception
+        {
+            if (object instanceof AMQFrame)
+            {
+                handleFrame((AMQFrame) object);
+            }
+            else
+            {
+                throw new AMQException("Received message of unrecognised type: " + object);
+            }
+        }
+
+        public void messageSent(IoSession session, Object object) throws Exception
+        {
+            _logger.debug(new LogMessage("{0}: sent {1}", MinaBrokerProxy.this, object));
+        }
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxy.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxyFactory.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxyFactory.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxyFactory.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxyFactory.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.cluster;
+
+public class MinaBrokerProxyFactory implements BrokerFactory
+{
+    private final MemberHandle _local;
+
+    MinaBrokerProxyFactory(MemberHandle local)
+    {
+        _local = local;
+    }
+
+    public Broker create(MemberHandle handle)
+    {
+        return new MinaBrokerProxy(handle.getHost(), handle.getPort(), _local);
+    }
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/MinaBrokerProxyFactory.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ResponseHandler.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ResponseHandler.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ResponseHandler.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ResponseHandler.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,27 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.framing.AMQMethodBody;
+
+public interface ResponseHandler
+{
+    public void responded(AMQMethodBody response);
+
+    public void removed();
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/ResponseHandler.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Sendable.java
URL: http://svn.apache.org/viewvc/incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Sendable.java?view=auto&rev=447994
==============================================================================
--- incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Sendable.java (added)
+++ incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Sendable.java Tue Sep 19 15:06:50 2006
@@ -0,0 +1,25 @@
+/*
+ *
+ * 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.cluster;
+
+import org.apache.qpid.AMQException;
+
+public interface Sendable
+{
+    public void send(int channel, Member member) throws AMQException;
+}

Propchange: incubator/qpid/trunk/qpid/java/cluster/src/org/apache/qpid/server/cluster/Sendable.java
------------------------------------------------------------------------------
    svn:eol-style = native