summaryrefslogtreecommitdiff
path: root/dotnet/Qpid.Client/Client/State/AMQStateManager.cs
blob: 881e01e697abe757c07ad707874e29c5641cdd3c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
using System;
using System.Collections;
using log4net;
using Apache.Qpid.Client.Handler;
using Apache.Qpid.Client.Protocol;
using Apache.Qpid.Client.Protocol.Listener;
using Apache.Qpid.Framing;

namespace Apache.Qpid.Client.State
{
    public class AMQStateManager : IAMQMethodListener
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(AMQStateManager));

        const bool InfoLoggingHack = true;
            
        /// <summary>
        /// The current state
        /// </summary>
        private AMQState _currentState;

        /// <summary>
        /// Maps from an AMQState instance to a Map from Class to StateTransitionHandler.
        /// The class must be a subclass of AMQFrame.
        /// </summary>
        private readonly IDictionary _state2HandlersMap;
        private ArrayList _stateListeners;
        private object _syncLock;
        
        public AMQStateManager()
        {
            _syncLock = new object();
            _state2HandlersMap = new Hashtable();
            _stateListeners = ArrayList.Synchronized(new ArrayList(5));
            _currentState = AMQState.CONNECTION_NOT_STARTED;
            RegisterListeners();
        }

        private void RegisterListeners()
        {
            IStateAwareMethodListener connectionStart = new ConnectionStartMethodHandler();
            IStateAwareMethodListener connectionClose = new ConnectionCloseMethodHandler();
            IStateAwareMethodListener connectionCloseOk = new ConnectionCloseOkHandler();
            IStateAwareMethodListener connectionTune = new ConnectionTuneMethodHandler();
            IStateAwareMethodListener connectionSecure = new ConnectionSecureMethodHandler();
            IStateAwareMethodListener connectionOpenOk = new ConnectionOpenOkMethodHandler();
            IStateAwareMethodListener channelClose = new ChannelCloseMethodHandler();
            IStateAwareMethodListener basicDeliver = new BasicDeliverMethodHandler();
            IStateAwareMethodListener basicReturn = new BasicReturnMethodHandler();
            IStateAwareMethodListener queueDeleteOk = new QueueDeleteOkMethodHandler();
            IStateAwareMethodListener queuePurgeOk = new QueuePurgeOkMethodHandler();
            
            // We need to register a map for the null (i.e. all state) handlers otherwise you get
            // a stack overflow in the handler searching code when you present it with a frame for which
            // no handlers are registered.
            _state2HandlersMap[AMQState.ALL] = new Hashtable();

            {
                Hashtable notStarted = new Hashtable();
                notStarted[typeof(ConnectionStartBody)] = connectionStart;
                notStarted[typeof(ConnectionCloseBody)] = connectionClose;
                _state2HandlersMap[AMQState.CONNECTION_NOT_STARTED] = notStarted;
            }
            {
                Hashtable notTuned = new Hashtable();
                notTuned[typeof(ConnectionTuneBody)] = connectionTune;
                notTuned[typeof(ConnectionSecureBody)] = connectionSecure;
                notTuned[typeof(ConnectionCloseBody)] = connectionClose;
                _state2HandlersMap[AMQState.CONNECTION_NOT_TUNED] = notTuned;
            }
            {
                Hashtable notOpened = new Hashtable();
                notOpened[typeof(ConnectionOpenOkBody)] = connectionOpenOk;
                notOpened[typeof(ConnectionCloseBody)] = connectionClose;
                _state2HandlersMap[AMQState.CONNECTION_NOT_OPENED] = notOpened;
            }
            {
                Hashtable open = new Hashtable();
                open[typeof(ChannelCloseBody)] = channelClose;
                open[typeof(ConnectionCloseBody)] = connectionClose;
                open[typeof(BasicDeliverBody)] = basicDeliver;
                open[typeof(BasicReturnBody)] = basicReturn;
                open[typeof(QueueDeleteOkBody)] = queueDeleteOk;
                open[typeof(QueuePurgeOkBody)] = queuePurgeOk;
                _state2HandlersMap[AMQState.CONNECTION_OPEN] = open;
            }
            {
                Hashtable closing = new Hashtable();
                closing[typeof(ConnectionCloseOkBody)] = connectionCloseOk;
                _state2HandlersMap[AMQState.CONNECTION_CLOSING] = closing;
            }
        }

        public AMQState CurrentState
        {
            get
            {
                return _currentState;
            }
        }

        /// <summary>
        /// Changes the state.
        /// </summary>
        /// <param name="newState">The new state.</param>
        /// <exception cref="AMQException">if there is an error changing state</exception>
        public void ChangeState(AMQState newState)
        {
            if (InfoLoggingHack)
            {
                _logger.Debug("State changing to " + newState + " from old state " + _currentState);
            }
            _logger.Debug("State changing to " + newState + " from old state " + _currentState);
            AMQState oldState = _currentState;
            _currentState = newState;

            lock ( _syncLock )
            {
               foreach ( IStateListener l in _stateListeners )
               {
                  l.StateChanged(oldState, newState);
               }
            }
        }

        public void Error(Exception e)
        {
            _logger.Debug("State manager receive error notification: " + e);
            lock ( _syncLock )
            {
               foreach ( IStateListener l in _stateListeners )
               {
                  l.Error(e);
               }
            }
        }

        public bool MethodReceived(AMQMethodEvent evt)
        {
            _logger.Debug(String.Format("Finding method handler. currentState={0} type={1}", _currentState, evt.Method.GetType()));            
            IStateAwareMethodListener handler = FindStateTransitionHandler(_currentState, evt.Method);
            if (handler != null)
            {
                handler.MethodReceived(this, evt);
                return true;
            }
            return false;
        }

        /// <summary>
        /// Finds the state transition handler.
        /// </summary>
        /// <param name="currentState">State of the current.</param>
        /// <param name="frame">The frame.</param>
        /// <returns></returns>
        /// <exception cref="IllegalStateTransitionException">if the state transition if not allowed</exception>
        private IStateAwareMethodListener FindStateTransitionHandler(AMQState currentState,
                                                                     AMQMethodBody frame)                
        {
            Type clazz = frame.GetType();
            if (_logger.IsDebugEnabled)
            {
                _logger.Debug("Looking for state transition handler for frame " + clazz);
            }
            IDictionary classToHandlerMap = (IDictionary) _state2HandlersMap[currentState];

            if (classToHandlerMap == null)
            {
                // if no specialised per state handler is registered look for a
                // handler registered for "all" states
                return FindStateTransitionHandler(AMQState.ALL, frame);
            }
            IStateAwareMethodListener handler = (IStateAwareMethodListener) classToHandlerMap[clazz];
            if (handler == null)
            {
                if (currentState == AMQState.ALL)
                {
                    _logger.Debug("No state transition handler defined for receiving frame " + frame);
                    return null;
                }
                else
                {
                    // if no specialised per state handler is registered look for a
                    // handler registered for "all" states
                    return FindStateTransitionHandler(AMQState.ALL, frame);
                }
            }
            else
            {
                return handler;
            }
        }

        public void AddStateListener(IStateListener listener)
        {
            _logger.Debug("Adding state listener");
            lock ( _syncLock )
            {
               _stateListeners.Add(listener);
            }
        }

        public void RemoveStateListener(IStateListener listener)
        {
           lock ( _syncLock )
           {
              _stateListeners.Remove(listener);
           }
        }

        public void AttainState(AMQState s)
        {
            if (_currentState != s)
            {
                StateWaiter sw = null;
                try
                {
                    _logger.Debug("Adding state wait to reach state " + s);
                    sw = new StateWaiter(s);
                    AddStateListener(sw);
                    sw.WaituntilStateHasChanged();
                    // at this point the state will have changed.
                }
                finally
                { 
                    RemoveStateListener(sw);
                }
            }
        }        
    }
}