summaryrefslogtreecommitdiff
path: root/java/newclient/src/main/java/org/apache/qpid/nclient/amqp/AMQPConnection.java
blob: 9c9e913cd3addc2d7d0bff6308575a47a9e4250b (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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package org.apache.qpid.nclient.amqp;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;
import org.apache.qpid.framing.AMQMethodBody;
import org.apache.qpid.framing.ConnectionCloseBody;
import org.apache.qpid.framing.ConnectionCloseOkBody;
import org.apache.qpid.framing.ConnectionOpenBody;
import org.apache.qpid.framing.ConnectionOpenOkBody;
import org.apache.qpid.framing.ConnectionSecureBody;
import org.apache.qpid.framing.ConnectionSecureOkBody;
import org.apache.qpid.framing.ConnectionStartBody;
import org.apache.qpid.framing.ConnectionStartOkBody;
import org.apache.qpid.framing.ConnectionTuneBody;
import org.apache.qpid.framing.ConnectionTuneOkBody;
import org.apache.qpid.nclient.amqp.state.AMQPState;
import org.apache.qpid.nclient.amqp.state.AMQPStateMachine;
import org.apache.qpid.nclient.config.ClientConfiguration;
import org.apache.qpid.nclient.core.AMQPException;
import org.apache.qpid.nclient.core.Phase;
import org.apache.qpid.nclient.core.QpidConstants;
import org.apache.qpid.nclient.model.AMQPMethodEvent;
import org.apache.qpid.nclient.model.AMQPMethodListener;
import org.apache.qpid.nclient.transport.TransportConnection;
import org.apache.qpid.nclient.util.AMQPValidator;

/**
 * This maps directly to the Connection class defined in the AMQP protocol This class is a finite state machine and is
 * thread safe by design A particular method (state changing) can only be invoked once and only in sequence or else an
 * IllegalStateTransitionException will be thrown Also only one thread can enter those methods at a given time.
 */
public class AMQPConnection extends AMQPStateMachine implements AMQPMethodListener
{
    private static final Logger _logger = Logger.getLogger(AMQPConnection.class);

    private Phase _phase;

    private TransportConnection _connection;

    private long _correlationId;

    private AMQPState _currentState;

    private final AMQPState[] _validCloseStates = new AMQPState[] { AMQPState.CONNECTION_NOT_STARTED,
	    AMQPState.CONNECTION_NOT_SECURE, AMQPState.CONNECTION_NOT_TUNED, AMQPState.CONNECTION_NOT_OPENED,
	    AMQPState.CONNECTION_OPEN, };

    // The wait period until a server sends a respond
    private long _serverTimeOut = 1000;

    private final Lock _lock = new ReentrantLock();

    private final Condition _connectionNotStarted = _lock.newCondition();

    private final Condition _connectionNotSecure = _lock.newCondition();

    private final Condition _connectionNotTuned = _lock.newCondition();

    private final Condition _connectionNotOpened = _lock.newCondition();

    private final Condition _connectionNotClosed = _lock.newCondition();

    private ConnectionStartBody _connectionStartBody;

    private ConnectionSecureBody _connectionSecureBody;

    private ConnectionTuneBody _connectionTuneBody;

    private ConnectionOpenOkBody _connectionOpenOkBody;

    private ConnectionCloseOkBody _connectionCloseOkBody;

    public AMQPConnection(TransportConnection connection)
    {
	_connection = connection;
	_currentState = AMQPState.CONNECTION_UNDEFINED;
	_serverTimeOut = ClientConfiguration.get().getLong(QpidConstants.SERVER_TIMEOUT_IN_MILLISECONDS);
    }

    /**
         * ------------------------------------------- API Methods --------------------------------------------
         */

    /**
         * Opens the TCP connection and let the formalities begin.
         */
    public ConnectionStartBody openTCPConnection() throws AMQPException
    {
	_lock.lock();
	// open the TCP connection
	try
	{
	    _connectionStartBody = null;
	    checkIfValidStateTransition(AMQPState.CONNECTION_UNDEFINED, _currentState, AMQPState.CONNECTION_NOT_STARTED);
	    _phase = _connection.connect();

	    // waiting for ConnectionStartBody or error in connection
	    _connectionNotStarted.await(_serverTimeOut, TimeUnit.MILLISECONDS);
	    AMQPValidator.throwExceptionOnNull(_connectionStartBody,
		    "The broker didn't send the ConnectionStartBody in time");
	    _currentState = AMQPState.CONNECTION_NOT_STARTED;
	    return _connectionStartBody;
	}
	catch (Exception e)
	{
	    throw new AMQPException("XXX");
	}
	finally
	{
	    _lock.unlock();
	}
    }

    public ConnectionSecureBody startOk(ConnectionStartOkBody connectionStartOkBody) throws AMQPException
    {
	_lock.lock();
	try
	{
	    _connectionSecureBody = null;
	    checkIfValidStateTransition(AMQPState.CONNECTION_NOT_STARTED, _currentState,
		    AMQPState.CONNECTION_NOT_SECURE);
	    AMQPMethodEvent msg = new AMQPMethodEvent(QpidConstants.CHANNEL_ZERO, connectionStartOkBody, _correlationId);
	    _phase.messageSent(msg);
	    _connectionNotSecure.await(_serverTimeOut, TimeUnit.MILLISECONDS);
	    AMQPValidator.throwExceptionOnNull(_connectionSecureBody,
		    "The broker didn't send the ConnectionSecureBody in time");
	    _currentState = AMQPState.CONNECTION_NOT_SECURE;
	    return _connectionSecureBody;
	}
	catch (Exception e)
	{
	    throw new AMQPException("XXX");
	}
	finally
	{
	    _lock.unlock();
	}
    }

    /**
         * The server will verify the response contained in the secureOK body and send a ConnectionTuneBody or it could
         * issue a new challenge
         */
    public AMQMethodBody secureOk(ConnectionSecureOkBody connectionSecureOkBody) throws AMQPException
    {
	_lock.lock();
	try
	{
	    _connectionTuneBody = null;
	    _connectionSecureBody = null;
	    checkIfValidStateTransition(AMQPState.CONNECTION_NOT_SECURE, _currentState, AMQPState.CONNECTION_NOT_TUNED);
	    _connectionSecureBody = null; // The server could send a fresh challenge
	    AMQPMethodEvent msg = new AMQPMethodEvent(QpidConstants.CHANNEL_ZERO, connectionSecureOkBody,
		    _correlationId);
	    _phase.messageSent(msg);
	    _connectionNotTuned.await(_serverTimeOut, TimeUnit.MILLISECONDS);
	    if (_connectionTuneBody != null)
	    {
		_currentState = AMQPState.CONNECTION_NOT_TUNED;
		return _connectionTuneBody;
	    }
	    else if (_connectionSecureBody != null)
	    { // oops the server sent another challenge
		_currentState = AMQPState.CONNECTION_NOT_SECURE;
		return _connectionSecureBody;
	    }
	    else
	    {
		throw new AMQPException("The broker didn't send the ConnectionTuneBody or ConnectionSecureBody in time");
	    }
	}
	catch (Exception e)
	{
	    throw new AMQPException("XXX");
	}
	finally
	{
	    _lock.unlock();
	}
    }

    public void tuneOk(ConnectionTuneOkBody connectionTuneOkBody) throws AMQPException
    {
	_lock.lock();
	try
	{
	    checkIfValidStateTransition(AMQPState.CONNECTION_NOT_TUNED, _currentState, AMQPState.CONNECTION_NOT_OPENED);
	    _connectionSecureBody = null;
	    AMQPMethodEvent msg = new AMQPMethodEvent(QpidConstants.CHANNEL_ZERO, connectionTuneOkBody, _correlationId);
	    _phase.messageSent(msg);
	    _currentState = AMQPState.CONNECTION_NOT_OPENED;
	}
	catch (Exception e)
	{
	    throw new AMQPException("XXX");
	}
	finally
	{
	    _lock.unlock();
	}
    }

    public ConnectionOpenOkBody open(ConnectionOpenBody connectionOpenBody) throws AMQPException
    {
	_lock.lock();
	try
	{
	    _connectionOpenOkBody = null;
	    checkIfValidStateTransition(AMQPState.CONNECTION_NOT_OPENED, _currentState, AMQPState.CONNECTION_OPEN);
	    AMQPMethodEvent msg = new AMQPMethodEvent(QpidConstants.CHANNEL_ZERO, connectionOpenBody,
		    QpidConstants.EMPTY_CORRELATION_ID);
	    _phase.messageSent(msg);
	    _connectionNotOpened.await(_serverTimeOut, TimeUnit.MILLISECONDS);
	    AMQPValidator.throwExceptionOnNull(_connectionOpenOkBody,
		    "The broker didn't send the ConnectionOpenOkBody in time");
	    _currentState = AMQPState.CONNECTION_OPEN;
	    return _connectionOpenOkBody;
	}
	catch (Exception e)
	{
	    throw new AMQPException("XXX");
	}
	finally
	{
	    _lock.unlock();
	}
    }

    public ConnectionCloseOkBody close(ConnectionCloseBody connectioncloseBody) throws AMQPException
    {
	_lock.lock();
	try
	{
	    _connectionCloseOkBody = null;
	    checkIfValidStateTransition(_validCloseStates, _currentState, AMQPState.CONNECTION_CLOSED);
	    AMQPMethodEvent msg = new AMQPMethodEvent(QpidConstants.CHANNEL_ZERO, connectioncloseBody,
		    QpidConstants.EMPTY_CORRELATION_ID);
	    _phase.messageSent(msg);
	    _connectionNotClosed.await(_serverTimeOut, TimeUnit.MILLISECONDS);
	    AMQPValidator.throwExceptionOnNull(_connectionCloseOkBody,
		    "The broker didn't send the ConnectionCloseOkBody in time");
	    _currentState = AMQPState.CONNECTION_CLOSED;
	    return _connectionCloseOkBody;
	}
	catch (Exception e)
	{
	    throw new AMQPException("XXX");
	}
	finally
	{
	    _lock.unlock();
	}
    }

    /**
         * ------------------------------------------- AMQMethodListener methods
         * --------------------------------------------
         */
    public <B extends AMQMethodBody> boolean methodReceived(AMQPMethodEvent<B> evt) throws AMQPException
    {
	_correlationId = evt.getCorrelationId();

	if (evt.getMethod() instanceof ConnectionStartBody)
	{
	    _connectionStartBody = (ConnectionStartBody) evt.getMethod();
	    _connectionNotStarted.signal();
	    return true;
	}
	else if (evt.getMethod() instanceof ConnectionSecureBody)
	{
	    _connectionSecureBody = (ConnectionSecureBody) evt.getMethod();
	    _connectionNotSecure.signal();
	    _connectionNotTuned.signal(); // in case the server has sent another chanllenge
	    return true;
	}
	else if (evt.getMethod() instanceof ConnectionTuneBody)
	{
	    _connectionTuneBody = (ConnectionTuneBody) evt.getMethod();
	    _connectionNotTuned.signal();
	    return true;
	}
	else if (evt.getMethod() instanceof ConnectionOpenOkBody)
	{
	    _connectionOpenOkBody = (ConnectionOpenOkBody) evt.getMethod();
	    _connectionNotOpened.signal();
	    return true;
	}
	else if (evt.getMethod() instanceof ConnectionCloseOkBody)
	{
	    _connectionCloseOkBody = (ConnectionCloseOkBody) evt.getMethod();
	    _connectionNotClosed.signal();
	    return true;
	}
	else if (evt.getMethod() instanceof ConnectionCloseBody)
	{
	    handleClose();
	    return true;
	}
	else
	{
	    return false;
	}
    }

    public void handleClose() throws AMQPException
    {
	_lock.lock();
	try
	{
	    checkIfValidStateTransition(AMQPState.CONNECTION_OPEN, _currentState, AMQPState.CONNECTION_CLOSING);
	    _currentState = AMQPState.CONNECTION_CLOSING;
	    // do the required cleanup and send a ConnectionCloseOkBody
	}
	catch (Exception e)
	{
	    throw new AMQPException("XXX");
	}
	finally
	{
	    _lock.unlock();
	}
    }

}