summaryrefslogtreecommitdiff
path: root/tools/src/java/qpid-qmf2/src/main/java/org/apache/qpid/qmf2/agent/QmfAgentData.java
blob: 974c5746e2a2914621f8a948d3b2d0827c22d407 (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
/*
 *
 * 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.qmf2.agent;

// Misc Imports
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

// QMF2 Imports
import org.apache.qpid.qmf2.common.ObjectId;
import org.apache.qpid.qmf2.common.QmfException;
import org.apache.qpid.qmf2.common.QmfManaged;
import org.apache.qpid.qmf2.common.SchemaObjectClass;

/**
 * The Agent manages the data it represents by the QmfAgentData class - a derivative of the QmfData class.
 * <p>
 * The Agent is responsible for managing the values of the properties within the object, as well as servicing
 * the object's method calls. Unlike the Console, the Agent has full control of the state of the object.
 * <p>
 * In most cases, for efficiency, it is expected that Agents would <i>actually</i> manage objects that are subclasses of 
 * QmfAgentData and maintain subclass specific properties as primitives, only actually explicitly setting the
 * underlying Map properties via setValue() etc. when the object needs to be "serialised". This would most
 * obviously be done by extending the mapEncode() method (noting that it's important to call QmfAgentData's mapEncode()
 * first via super.mapEncode(); as this will set the state of the underlying QmfData).
 * <p>
 * This class provides a number of methods aren't in the QMF2 API per se, but they are used to manage the association
 * between a managed object and any subscriptions that might be interested in it.
 * <p>
 * The diagram below shows the relationship between the Subscription and QmfAgentData.
 * <p>
 * <img alt="" src="doc-files/Subscriptions.png">
 * <p>
 * In particular the QmfAgentData maintains references to active subscriptions to allow agents to asynchronously
 * push data to subscribing Consoles immediately that data becomes available.
 * <p>
 * The update() method indicates that the object's state has changed and the publish() method <b>immediately</b> sends
 * the new state to any subscription.
 * <p>
 * The original intention was to "auto update" by calling these from the setValue() method. Upon reflection this
 * seems a bad idea, as in many cases there may be several properties that an Agent may wish to change which would
 * lead to unnecessary calls to currentTimeMillis(), but also as theSubscription update is run via a TimerTask it is
 * possible that an update indication could get sent part way through setting an object's overall state.
 * Similarly calling the publish() method directly from setValue() would force an update indication on partial changes
 * of state, which is generally not the desired behaviour.
 * @author Fraser Adams
 */
public class QmfAgentData extends QmfManaged implements Comparable<QmfAgentData>
{
    private long _updateTimestamp;
    private long _createTimestamp;
    private long _deleteTimestamp;
    private String _compareKey = null;

    /**
     * This Map is used to look up Subscriptions that are interested in this data by SubscriptionId
     */
    private Map<String, Subscription> _subscriptions = new ConcurrentHashMap<String, Subscription>();

    /**
     * Construct a QmfAgentData object of the type described by the given SchemaObjectClass.
     *
     * @param schema the schema describing the type of this QmfAgentData object.
     */
    public QmfAgentData(final SchemaObjectClass schema)
    {
        long currentTime = System.currentTimeMillis()*1000000l;
        _updateTimestamp = currentTime;
        _createTimestamp = currentTime;
        _deleteTimestamp = 0;
        setSchemaClassId(schema.getClassId());
    }

    /**
     * Return the creation timestamp.
     * @return the creation timestamp. Timestamps are recorded in nanoseconds since the epoch
     */
    public final long getCreateTime()
    {
        return _createTimestamp;
    }

    /**
     * Return the update timestamp.
     * @return the update timestamp. Timestamps are recorded in nanoseconds since the epoch
     */
    public final long getUpdateTime()
    {
        return _updateTimestamp;
    }

    /**
     * Return the deletion timestamp.
     * @return the deletion timestamp, or zero if not deleted. Timestamps are recorded in nanoseconds since the epoch
     */
    public final long getDeleteTime()
    {
        return _deleteTimestamp;
    }

    /**
     * Return true if deletion timestamp not zero.
     * @return true if deletion timestamp not zero.
     */
    public final boolean isDeleted()
    {
        return getDeleteTime() != 0;
    }

    /**
     * Mark the object as deleted by setting the deletion timestamp to the current time.
     * <p>
     * This method alse publishes the deleted object to any listening Subscription then removes references to the
     * Subscription.
     * <p>
     * When this method returns the object should be ready for reaping.
     */
    public final void destroy()
    {
        _deleteTimestamp = System.currentTimeMillis()*1000000l;
        _updateTimestamp = System.currentTimeMillis()*1000000l;
        publish();
        _subscriptions.clear();
    }

    /**
     * Add the delta to the property.
     *
     * @param name the name of the property being modified.
     * @param delta the value being added to the property.
     */
    public final synchronized void incValue(final String name, final long delta)
    {
        long value = getLongValue(name);
        value += delta;
        setValue(name, value);
    }

    /**
     * Add the delta to the property.
     *
     * @param name the name of the property being modified.
     * @param delta the value being added to the property.
     */
    public final synchronized void incValue(final String name, final double delta)
    {
        double value = getDoubleValue(name);
        value += delta;
        setValue(name, value);
    }

    /**
     * Subtract the delta from the property.
     *
     * @param name the name of the property being modified.
     * @param delta the value being subtracted from the property.
     */
    public final synchronized void decValue(final String name, final long delta)
    {
        long value = getLongValue(name);
        value -= delta;
        setValue(name, value);
    }

    /**
     * Subtract the delta from the property.
     *
     * @param name the name of the property being modified.
     * @param delta the value being subtracted from the property.
     */
    public final synchronized void decValue(final String name, final double delta)
    {
        double value = getDoubleValue(name);
        value -= delta;
        setValue(name, value);
    }

    // The following methods aren't in the QMF2 API per se, but they are used to manage the association between
    // a managed object and any subscriptions that might be interested in it.

    /**
     * Return the Subscription with the specified ID.
     * @return the Subscription with the specified ID.
     */
    public final Subscription getSubscription(final String subscriptionId)
    {
        return _subscriptions.get(subscriptionId);
    }

    /**
     * Add a new Subscription reference.
     * @param subscriptionId the ID of the Subscription being added.
     * @param subscription the Subscription being added.
     */
    public final void addSubscription(final String subscriptionId, final Subscription subscription)
    {
        _subscriptions.put(subscriptionId, subscription);
    }

    /**
     * Remove a Subscription reference.
     * @param subscriptionId the ID of the Subscription being removed.
     */
    public final void removeSubscription(final String subscriptionId)
    {
        _subscriptions.remove(subscriptionId);
    }


    /**
     * Set the _updateTimestamp to indicate (particularly to subscriptions) that the managed object has changed.
     * <p>
     * The update() method indicates that the object's state has changed and the publish() method <b>immediately</b> sends
     * the new state to any subscription.
     * <p>
     * The original intention was to "auto update" by calling these from the setValue() method. Upon reflection this
     * seems a bad idea, as in many cases there may be several properties that an Agent may wish to change which would
     * lead to unnecessary calls to currentTimeMillis(), but also as the Subscription update is run via a TimerTask it
     * is possible that an update indication could get sent part way through setting an object's overall state.
     * Similarly calling the publish() method directly from setValue() would force an update indication on partial
     * changes of state, which is generally not the desired behaviour.
     */
    public final void update()
    {
        _updateTimestamp = System.currentTimeMillis()*1000000l;
    }

    /**
     * Iterate through any Subscriptions associated with this Object and force them to republish the Object's new state.
     * <p>
     * The update() method indicates that the object's state has changed and the publish() method <b>immediately</b> sends
     * the new state to any subscription.
     * <p>
     * The original intention was to "auto update" by calling these from the setValue() method. Upon reflection this
     * seems a bad idea, as in many cases there may be several properties that an Agent may wish to change which would
     * lead to unnecessary calls to currentTimeMillis(), but also as the Subscription update is run via a TimerTask it
     * is possible that an update indication could get sent part way through setting an object's overall state.
     * Similarly calling the publish() method directly from setValue() would force an update indication on partial
     * changes of state, which is generally not the desired behaviour.
     */
    public final void publish()
    {
        update();
        if (getObjectId() == null)
        { // If ObjectId is null the Object isn't yet Managed to we can't publish
            return;
        }

        List<Map> results = new ArrayList<Map>();
        results.add(mapEncode());
        for (Map.Entry<String, Subscription> entry : _subscriptions.entrySet())
        {
            Subscription subscription = entry.getValue();
            subscription.publish(results);
        }
    }

    /**
     * Return the underlying map.
     * <p>
     * In most cases, for efficiency, it is expected that Agents would <i>actually</i> manage objects that are
     * subclasses of QmfAgentData and maintain subclass specific properties as primitives, only actually explicitly
     * setting the underlying Map properties via setValue() etc. when the object needs to be "serialised". This would
     * most obviously be done by extending the mapEncode() method (noting that it's important to call QmfAgentData's
     * mapEncode() first via super.mapEncode(); as this will set the state of the underlying QmfData).
     *
     * @return the underlying map. 
     */
    @Override
    public Map<String, Object> mapEncode()
    {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("_values", super.mapEncode());
        if (_subtypes != null)
        {
            map.put("_subtypes", _subtypes);
        }
        map.put("_schema_id", getSchemaClassId().mapEncode());
        map.put("_object_id", getObjectId().mapEncode());
        map.put("_update_ts", _updateTimestamp);
        map.put("_create_ts", _createTimestamp);
        map.put("_delete_ts", _deleteTimestamp);
        return map;
    }

    /**
     * Helper/debug method to list the QMF Object properties and their type.
     */
    @Override
    public void listValues()
    {
        super.listValues();
        System.out.println("QmfAgentData:");
        System.out.println("create timestamp: " + new Date(getCreateTime()/1000000l));
        System.out.println("update timestamp: " + new Date(getUpdateTime()/1000000l));
        System.out.println("delete timestamp: " + new Date(getDeleteTime()/1000000l));
    }

    // The following methods allow instances of QmfAgentData to be compared with each other and sorted.
    // N.B. This behaviour is not part of the specified QmfAgentData, but it's quite useful for some Agents.

    /**
     * Set the key String to be used for comparing two QmfAgentData instances. This is primarily used by the Agent
     * to allow it to order Query results (e.g. for getObjects()).
     * @param compareKey the String that we wish to use as a compare key.
     */
    public void setCompareKey(String compareKey)
    {
        _compareKey = compareKey;
    }

    /**
     * If a compare key has been set then the QmfAgentData is sortable.
     * @return true if a compare key has been set and the QmfAgentData is sortable otherwise return false.
     */
    public boolean isSortable()
    {
        return _compareKey != null;
    }

    /**
     * Compare the compare key of this QmfAgentData with the specified other QmfAgentData.
     * Compares the compare keys (which are Strings) lexicographically. The comparison is based on the Unicode
     * value of each character in the strings.
     * @param rhs the String to be compared.
     * @return the value 0 if the argument string is equal to this string; a value less than 0 if this string is 
     * lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically 
     * greater than the string argument.
     */
    public int compareTo(QmfAgentData rhs)
    { 
        if (_compareKey == null)
        {
            return 0;
        }
        else
        {
            return this._compareKey.compareTo(rhs._compareKey);
        }
    }
}