summaryrefslogtreecommitdiff
path: root/java/broker-core/src/main/java/org/apache/qpid/server/subscription/AbstractSubscription.java
blob: 213d8b77304a3d8f1af4e92735a37979e89bebf5 (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
/*
 *
 * 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.server.subscription;

import org.apache.qpid.AMQException;
import org.apache.qpid.server.filter.FilterManager;
import org.apache.qpid.server.logging.LogActor;
import org.apache.qpid.server.logging.LogSubject;
import org.apache.qpid.server.logging.actors.CurrentActor;
import org.apache.qpid.server.logging.actors.SubscriptionActor;
import org.apache.qpid.server.logging.messages.SubscriptionMessages;
import org.apache.qpid.server.logging.subjects.SubscriptionLogSubject;
import org.apache.qpid.server.message.ServerMessage;
import org.apache.qpid.server.model.Queue;
import org.apache.qpid.server.protocol.MessageConverterRegistry;
import org.apache.qpid.server.queue.AMQQueue;
import org.apache.qpid.server.queue.QueueEntry;
import org.apache.qpid.server.util.StateChangeListener;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public abstract class AbstractSubscription implements Subscription
{
    private final long _subscriptionID;
    private final AtomicReference<State> _state = new AtomicReference<State>(State.ACTIVE);
    private final Lock _stateChangeLock = new ReentrantLock();
    private final long _createTime = System.currentTimeMillis();
    private final QueueEntry.SubscriptionAcquiredState _owningState = new QueueEntry.SubscriptionAcquiredState(this);
    private final boolean _acquires;
    private final boolean _seesRequeues;
    private final String _consumerName;
    private final boolean _isTransient;


    private final AtomicLong _deliveredCount = new AtomicLong(0);
    private final AtomicLong _deliveredBytes = new AtomicLong(0);

    private Map<String, Object> _properties = new ConcurrentHashMap<String, Object>();


    private final FilterManager _filters;

    private volatile AMQQueue.Context _queueContext;


    private StateChangeListener<Subscription, State> _stateListener = new StateChangeListener<Subscription, State>()
    {
        public void stateChanged(Subscription sub, State oldState, State newState)
        {
            CurrentActor.get().message(SubscriptionMessages.STATE(newState.toString()));
        }
    };

    private SubscriptionLogSubject _logSubject;
    private AMQQueue _queue;
    private String _traceExclude;
    private String _trace;
    private SubscriptionActor _logActor;
    private final Class<? extends ServerMessage> _messageClass;
    private final Object _sessionReference;
    private boolean _noLocal;

    protected AbstractSubscription(FilterManager filters,
                                   final Class<? extends ServerMessage> messageClass,
                                   final Object sessionReference,
                                   final boolean acquires,
                                   final boolean seesRequeues,
                                   final String consumerName, final boolean isTransient)
    {
        _messageClass = messageClass;
        _sessionReference = sessionReference;
        _subscriptionID = SUB_ID_GENERATOR.getAndIncrement();
        _filters = filters;
        _acquires = acquires;
        _seesRequeues = seesRequeues;
        _consumerName = consumerName;
        _isTransient = isTransient;
    }

    public final long getSubscriptionID()
    {
        return _subscriptionID;
    }


    public final StateChangeListener<Subscription, State> getStateListener()
    {
        return _stateListener;
    }

    public final void setStateListener(StateChangeListener<Subscription, State> listener)
    {
        _stateListener = listener;
    }


    public final AMQQueue.Context getQueueContext()
    {
        return _queueContext;
    }

    public final void setQueueContext(AMQQueue.Context queueContext)
    {
        _queueContext = queueContext;
    }


    public State getState()
    {
        return _state.get();
    }

    protected boolean updateState(State from, State to)
    {
        return _state.compareAndSet(from, to);
    }

    public final boolean isActive()
    {
        return getState() == State.ACTIVE;
    }

    public final boolean isClosed()
    {
        return getState() == State.CLOSED;
    }


    public final void setNoLocal(boolean noLocal)
    {
        _noLocal = noLocal;
    }


    public final boolean hasInterest(QueueEntry entry)
    {
       //check that the message hasn't been rejected
        if (entry.isRejectedBy(getSubscriptionID()))
        {

            return false;
        }

        if (entry.getMessage().getClass() == _messageClass)
        {
            if(_noLocal)
            {
                Object connectionRef = entry.getMessage().getConnectionReference();
                if (connectionRef != null && connectionRef == _sessionReference)
                {
                    return false;
                }
            }
        }
        else
        {
            // no interest in messages we can't convert
            if(MessageConverterRegistry.getConverter(entry.getMessage().getClass(), _messageClass)==null)
            {
                return false;
            }
        }
        return (_filters == null) || _filters.allAllow(entry.asFilterable());
    }


    protected String getFilterLogString()
    {
        StringBuilder filterLogString = new StringBuilder();
        String delimiter = ", ";
        boolean hasEntries = false;
        if (_filters != null && _filters.hasFilters())
        {
            filterLogString.append(_filters.toString());
            hasEntries = true;
        }

        if (!acquires())
        {
            if (hasEntries)
            {
                filterLogString.append(delimiter);
            }
            filterLogString.append("Browser");
            hasEntries = true;
        }

        return filterLogString.toString();
    }


    public final boolean trySendLock()
    {
        return _stateChangeLock.tryLock();
    }

    public final void getSendLock()
    {
        _stateChangeLock.lock();
    }

    public final void releaseSendLock()
    {
        _stateChangeLock.unlock();
    }

    public final AMQQueue getQueue()
    {
        return _queue;
    }

    public final void setQueue(AMQQueue queue, boolean exclusive)
    {
        if(getQueue() != null)
        {
            throw new IllegalStateException("Attempt to set queue for subscription " + this + " to " + queue + "when already set to " + getQueue());
        }
        _queue = queue;

        _traceExclude = (String) queue.getAttribute(Queue.FEDERATION_EXCLUDES);
        _trace = (String) queue.getAttribute(Queue.FEDERATION_ID);

        _logSubject = new SubscriptionLogSubject(this);
        _logActor = new SubscriptionActor(CurrentActor.get().getRootMessageLogger(), this);

        if (CurrentActor.get().getRootMessageLogger().isMessageEnabled(_logActor, _logSubject, SubscriptionMessages.CREATE_LOG_HIERARCHY))
        {
            final String filterLogString = getFilterLogString();
            CurrentActor.get().message(_logSubject, SubscriptionMessages.CREATE(filterLogString, queue.isDurable() && exclusive,
                                                                         filterLogString.length() > 0));
        }
    }

    protected final String getTraceExclude()
    {
        return _traceExclude;
    }

    protected final String getTrace()
    {
        return _trace;
    }

    protected final LogSubject getLogSubject()
    {
        return _logSubject;
    }

    public final LogActor getLogActor()
    {
        return _logActor;
    }

    public final long getCreateTime()
    {
        return _createTime;
    }


    public final QueueEntry.SubscriptionAcquiredState getOwningState()
    {
        return _owningState;
    }


    public final void set(String key, Object value)
    {
        _properties.put(key, value);
    }

    public final Object get(String key)
    {
        return _properties.get(key);
    }

    public final boolean acquires()
    {
        return _acquires;
    }

    public final boolean seesRequeues()
    {
        return _seesRequeues;
    }

    public final String getName()
    {
        return _consumerName;
    }

    public final boolean isTransient()
    {
        return _isTransient;
    }


    public final long getBytesOut()
    {
        return _deliveredBytes.longValue();
    }

    public final long getMessagesOut()
    {
        return _deliveredCount.longValue();
    }

    public final void send(final QueueEntry entry, final boolean batch) throws AMQException
    {
        _deliveredCount.incrementAndGet();
        _deliveredBytes.addAndGet(entry.getMessage().getSize());
        doSend(entry, batch);
    }

    protected abstract void doSend(final QueueEntry entry, final boolean batch) throws AMQException;

    @Override
    public final void flush() throws AMQException
    {
        getQueue().flushSubscription(this);
    }
}