summaryrefslogtreecommitdiff
path: root/qpid/java/client-api/src/main/java/org/apache/qpid/messaging/util/SessionManagementDecorator.java
blob: f35589901b0e5ef9a609f14d36bfc72edd5bf2f1 (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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/* 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.messaging.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.qpid.messaging.Address;
import org.apache.qpid.messaging.Connection;
import org.apache.qpid.messaging.ConnectionException;
import org.apache.qpid.messaging.Message;
import org.apache.qpid.messaging.MessagingException;
import org.apache.qpid.messaging.Receiver;
import org.apache.qpid.messaging.Sender;
import org.apache.qpid.messaging.Session;
import org.apache.qpid.messaging.SessionException;
import org.apache.qpid.messaging.internal.ConnectionInternal;
import org.apache.qpid.messaging.internal.ReceiverInternal;
import org.apache.qpid.messaging.internal.SenderInternal;
import org.apache.qpid.messaging.internal.SessionInternal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A Decorator that adds basic housekeeping tasks to a session.
 * This class adds,
 * 1. Management of receivers and senders created by this session.
 * 2. State management.
 * 3. Exception handling.
 *
 * <b>Exception Handling</b>
 * This class will wrap each method call to it's delegate to handle error situations.
 * First it will check if the session is already CLOSED or in an ERROR situation.
 * Then it will look for connection and session errors and handle as follows.
 *
 * <b>Connection Exceptions</b>
 * This class intercepts ConnectionException's and are passed onto the connection.
 * The Session will be marked as ERROR and a session exception will be thrown with an appropriate message.
 * Any further use of the session is prevented until it moves to OPENED.
 *
 * If failover is handled at a layer above, there will be a Session Decorator that
 * would handle the session exception and retry when the connection is available.
 * This handler may block the call until the state moves into either OPENED or CLOSED.
 * Ex @see SessionFailoverDecorator.
 *
 * If failover is handled at a layer below, then a connection exception means it has failed already.
 * Therefore when passed to the connection,the exception will be thrown directly to the application.
 * The connection object will be responsible for calling close on this session for the above case.
 *
 * <i> <b>Close() can be called by,</b>
 *      <ol>
 *       <li>The application (normal close)</li>
 *       <li>By the parent via failover (error)</li>
 *       <li>By the connection object, if no failover(error)</li>
 *       <li>By itself if it receives and exception (error)</li>
 *      </ol>
 * </i>
 *
 * <b>Session Exceptions</b>
 * For the time being, anytime a session exception is received, the session will be marked CLOSED.
 * We need to revisit this.
 */
public class SessionManagementDecorator implements SessionInternal
{
    private static Logger _logger = LoggerFactory.getLogger(SessionManagementDecorator.class);

    public enum SessionState {OPENED, CLOSED, ERROR}

    private ConnectionInternal _conn;
    private Session _delegate;
    SessionState _state = SessionState.OPENED;
    private List<ReceiverInternal> _receivers = new ArrayList<ReceiverInternal>();
    private List<SenderInternal> _senders = new ArrayList<SenderInternal>();
    private final Object _connectionLock;  // global per connection lock

    public SessionManagementDecorator(ConnectionInternal conn, Session delegate)
    {
        _conn = conn;
        _delegate = delegate;
        _connectionLock = conn.getConnectionLock();
    }

    @Override
    public boolean isClosed()
    {
        return _state == SessionState.CLOSED;
    }

    @Override
    public void close() throws MessagingException
    {
        checkClosedAndThrowException("Session is already closed");
        synchronized(_connectionLock)
        {
            _state = SessionState.CLOSED;
            for (Sender sender: _senders)
            {
                sender.close();
            }
            _senders.clear();

            for (Receiver receiver: _receivers)
            {
                receiver.close();
            }
            _receivers.clear();
            _delegate.close();
        }
    }

    @Override
    public void commit() throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            _delegate.commit();
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public void rollback() throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            _delegate.rollback();
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public void acknowledge(boolean sync) throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            _delegate.acknowledge(sync);
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public void acknowledge(Message message, boolean sync)
    throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            _delegate.acknowledge(message, sync);
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public void reject(Message message) throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            _delegate.reject(message);
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public void release(Message message) throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            _delegate.release(message);
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public void sync(boolean block) throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            _delegate.sync(block);
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public int getReceivable() throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            return _delegate.getReceivable();
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public int getUnsettledAcks() throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            return _delegate.getUnsettledAcks();
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public Receiver nextReceiver(long timeout) throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            return _delegate.nextReceiver(timeout);
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public Sender createSender(Address address) throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            SenderInternal sender = new SenderManagementDecorator(this,_delegate.createSender(address));
            _senders.add(sender);
            return sender;
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public Sender createSender(String address) throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            SenderInternal sender = new SenderManagementDecorator(this,_delegate.createSender(address));
            _senders.add(sender);
            return sender;
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public Receiver createReceiver(Address address) throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            ReceiverInternal receiver = new ReceiverManagementDecorator(this,_delegate.createReceiver(address));
            _receivers.add(receiver);
            return receiver;
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public Receiver createReceiver(String address) throws MessagingException
    {
        checkClosedAndThrowException();
        try
        {
            ReceiverInternal receiver = new ReceiverManagementDecorator(this,_delegate.createReceiver(address));
            _receivers.add(receiver);
            return receiver;
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public Connection getConnection() throws MessagingException
    {
        checkError();
        return _conn;  // always return your peer (not your delegate's peer)
    }

    @Override
    public boolean hasError()
    {
        return _delegate.hasError();
    }

    @Override
    public void checkError() throws MessagingException
    {
        checkClosedAndThrowException(); // check if we already have the info.
        try
        {
            // Asking the delegate.
            _delegate.checkError();
        }
        catch (ConnectionException e)
        {
            throw handleConnectionException(e);
        }
        catch (SessionException e)
        {
            throw handleSessionException(e);
        }
    }

    @Override
    public void exception(MessagingException e)
    {
        if (e instanceof ConnectionException)
        {
            handleConnectionException((ConnectionException)e);
        }
        else if (e instanceof SessionException)
        {
            handleSessionException((SessionException)e);
        }
    }

    @Override
    public void recreate() throws MessagingException
    {
        // TODO Auto-generated method stub

    }

    @Override
    public ConnectionInternal getConnectionInternal()
    {
        return _conn;
    }

    private void checkClosedAndThrowException() throws SessionException
    {
        checkClosedAndThrowException("Session is closed. You cannot invoke methods on a closed sesion");
    }

    private void checkClosedAndThrowException(String closedMessage) throws SessionException
    {
        switch (_state)
        {
        case ERROR:
            throw new SessionException("Session is in a temporary error state. The session may or may not recover from this");
        case CLOSED:
            throw new SessionException(closedMessage);
        }
    }

    /**
     * A ConnectionException will cause the Session to go into a temporary error state,
     * which prevents it from being used further.
     * From there the Session can be moved into OPENED (if failover works) or
     * CLOSED if there is no failover or if failover has failed.
     * @param e
     * @throws MessagingException
     */
    private SessionException handleConnectionException(ConnectionException e)
    {
        synchronized (_connectionLock)
        {
            _state = SessionState.ERROR;
            _conn.exception(e); // This might trigger failover in a layer above.
            if (_state == SessionState.CLOSED)
            {
                // The connection has instructed the session to be closed.
                // Either there was no failover, or failover has failed.
                return new SessionException("Session is closed due to connection error",e);
            }
            else
            {
                // Asking the application or the Parent handler to retry the operation.
                // The Session should be in OPENED state at this time.
                return new SessionException("Session was in a temporary error state due to connection error." +
                        "Plase retry your operation",e);
            }
        }
    }

    /**
     * Session Exceptions will generally invalidate the Session.
     * TODO this needs to be revisited again.
     * A new session will need to be created in that case.
     * @param e
     * @throws MessagingException
     */
    private SessionException handleSessionException(SessionException e)
    {
        synchronized (_connectionLock)
        {
            try
            {
                close();
            }
            catch(MessagingException ex)
            {
                // Should not throw an exception here.
                // Even if it did, does't matter as are closing.
            }
        }
        return new SessionException("Session has been closed",e);
    }
}