summaryrefslogtreecommitdiff
path: root/common/src/org/apache/qpid/framing/FieldTable.java
blob: be456c8754353ecee63dbd7ade2a67f95162971b (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
/*
 *
 * 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.framing;

import org.apache.log4j.Logger;
import org.apache.mina.common.ByteBuffer;

import java.util.*;

/**
 * From the protocol document:
 * field-table      = short-integer *field-value-pair
 * field-value-pair = field-name field-value
 * field-name       = short-string
 * field-value      = 'S' long-string
 * / 'I' long-integer
 * / 'D' decimal-value
 * / 'T' long-integer
 * decimal-value    = decimals long-integer
 * decimals         = OCTET
 */
public class FieldTable extends LinkedHashMap
{
    private static final Logger _logger = Logger.getLogger(FieldTable.class);
    private long _encodedSize = 0;

    public FieldTable()
    {
        super();
    }

    /**
     * Construct a new field table.
     *
     * @param buffer the buffer from which to read data. The length byte must be read already
     * @param length the length of the field table. Must be > 0.
     * @throws AMQFrameDecodingException if there is an error decoding the table
     */
    public FieldTable(ByteBuffer buffer, long length) throws AMQFrameDecodingException
    {
        super();
        final boolean debug = _logger.isDebugEnabled();
        assert length > 0;
        _encodedSize = length;
        int sizeRead = 0;
        while (sizeRead < _encodedSize)
        {
            int sizeRemaining = buffer.remaining();
            final String key = EncodingUtils.readShortString(buffer);
            // TODO: use proper charset decoder
            byte iType = buffer.get();
            final char type = (char) iType;
            Object value;
            switch (type)
            {
                case 'S':
                    value = EncodingUtils.readLongString(buffer);
                    break;
                case 'I':
                    value = new Long(buffer.getUnsignedInt());
                    break;
                default:
                    String msg = "Field '" + key + "' - unsupported field table type: " + type;
                    //some extra debug information...
                    msg += " (" + iType + "), length=" + length + ", sizeRead=" + sizeRead + ", sizeRemaining=" + sizeRemaining;
                    throw new AMQFrameDecodingException(msg);
            }
            sizeRead += (sizeRemaining - buffer.remaining());

            if (debug)
            {
                _logger.debug("FieldTable::FieldTable(buffer," + length + "): Read type '" + type + "', key '" + key + "', value '" + value + "' (now read " + sizeRead + " of " + length + " encoded bytes)...");
            }

            // we deliberately want to call put in the parent class since we do
            // not need to do the size calculations
            super.put(key, value);
        }

        if (debug)
        {
            _logger.debug("FieldTable::FieldTable(buffer," + length + "): Done.");
        }
    }

    public void writeToBuffer(ByteBuffer buffer)
    {
        final boolean debug = _logger.isDebugEnabled();

        if (debug)
        {
            _logger.debug("FieldTable::writeToBuffer: Writing encoded size of " + _encodedSize + "...");
        }

        // write out the total length, which we have kept up to date as data is added
        EncodingUtils.writeUnsignedInteger(buffer, _encodedSize);
        final Iterator it = this.entrySet().iterator();
        while (it.hasNext())
        {
            Map.Entry me = (Map.Entry) it.next();
            String key = (String) me.getKey();

            EncodingUtils.writeShortStringBytes(buffer, key);
            Object value = me.getValue();

            if (debug)
            {
                _logger.debug("FieldTable::writeToBuffer: Writing key '" + key + "' of type " + value.getClass() + ", value '" + value + "'...");
            }

            if (value instanceof byte[])
            {
                buffer.put((byte) 'S');
                EncodingUtils.writeLongstr(buffer, (byte[]) value);
            }
            else if (value instanceof String)
            {
                // TODO: look at using proper charset encoder
                buffer.put((byte) 'S');
                EncodingUtils.writeLongStringBytes(buffer, (String) value);
            }
            else if (value instanceof Long)
            {
                // TODO: look at using proper charset encoder
                buffer.put((byte) 'I');
                EncodingUtils.writeUnsignedInteger(buffer, ((Long) value).longValue());
            }
            else
            {
                // Should never get here
                throw new IllegalArgumentException("Key '" + key + "': Unsupported type in field table, type: " + ((value == null) ? "null-object" : value.getClass()));
            }
        }

        if (debug)
        {
            _logger.debug("FieldTable::writeToBuffer: Done.");
        }
    }

    public byte[] getDataAsBytes()
    {
        final ByteBuffer buffer = ByteBuffer.allocate((int) _encodedSize); // XXX: Is cast a problem?
        final Iterator it = this.entrySet().iterator();
        while (it.hasNext())
        {
            Map.Entry me = (Map.Entry) it.next();
            String key = (String) me.getKey();
            EncodingUtils.writeShortStringBytes(buffer, key);
            Object value = me.getValue();
            if (value instanceof byte[])
            {
                buffer.put((byte) 'S');
                EncodingUtils.writeLongstr(buffer, (byte[]) value);
            }
            else if (value instanceof String)
            {
                // TODO: look at using proper charset encoder
                buffer.put((byte) 'S');
                EncodingUtils.writeLongStringBytes(buffer, (String) value);
            }
            else if (value instanceof char[])
            {
                // TODO: look at using proper charset encoder
                buffer.put((byte) 'S');
                EncodingUtils.writeLongStringBytes(buffer, (char[]) value);
            }
            else if (value instanceof Long || value instanceof Integer)
            {
                // TODO: look at using proper charset encoder
                buffer.put((byte) 'I');
                EncodingUtils.writeUnsignedInteger(buffer, ((Long) value).longValue());
            }
            else
            {
                // Should never get here
                assert false;
            }
        }
        final byte[] result = new byte[(int) _encodedSize];
        buffer.flip();
        buffer.get(result);
        buffer.release();
        return result;
    }

    public Object put(Object key, Object value)
    {
        final boolean debug = _logger.isDebugEnabled();

        if (key == null)
        {
            throw new IllegalArgumentException("All keys must be Strings - was passed: null");
        }
        else if (!(key instanceof String))
        {
            throw new IllegalArgumentException("All keys must be Strings - was passed: " + key.getClass());
        }

        Object existing;

        if ((existing = super.remove(key)) != null)
        {
            if (debug)
            {
                _logger.debug("Found duplicate of key '" + key + "', previous value '" + existing + "' (" + existing.getClass() + "), to be replaced by '" + value + "', (" + value.getClass() + ") - stack trace of source of duplicate follows...", new Throwable().fillInStackTrace());
            }

            // If we are in effect deleting the value (see comment on null values being deleted
            // below) then we also need to remove the name from the encoding length.
            if (value == null)
            {
                _encodedSize -= EncodingUtils.encodedShortStringLength((String) key);
            }

            // FIXME: Should be able to short-cut this process if the old and new values are
            // the same object and/or type and size...
            _encodedSize -= getEncodingSize(existing);
        }
        else
        {
            if (value != null)
            {
                _encodedSize += EncodingUtils.encodedShortStringLength((String) key);
            }
        }

        // For now: Setting a null value is the equivalent of deleting it.
        // This is ambiguous in the JMS spec and needs thrashing out and potentially
        // testing against other implementations.
        if (value != null)
        {
            _encodedSize += getEncodingSize(value);
        }

        return super.put(key, value);
    }

    public Object remove(Object key)
    {
        if (super.containsKey(key))
        {
            final Object value = super.remove(key);
            _encodedSize -= EncodingUtils.encodedShortStringLength((String) key);

            // This check is, for now, unnecessary (we don't store null values).
            if (value != null)
            {
                _encodedSize -= getEncodingSize(value);
            }

            return value;
        }
        else
        {
            return null;
        }
    }

    /**
     * @return unsigned integer
     */
    public long getEncodedSize()
    {
        return _encodedSize;
    }

    /**
     * @return integer
     */
    private static int getEncodingSize(Object value)
    {
        int encodingSize;

        // the extra byte if for the type indicator that is written out
        if (value instanceof String)
        {
            encodingSize = 1 + EncodingUtils.encodedLongStringLength((String) value);
        }
        else if (value instanceof char[])
        {
            encodingSize = 1 + EncodingUtils.encodedLongStringLength((char[]) value);
        }
        else if (value instanceof Integer)
        {
            encodingSize = 1 + 4;
        }
        else if (value instanceof Long)
        {
            encodingSize = 1 + 4;
        }
        else
        {
            throw new IllegalArgumentException("Unsupported type in field table: " + value.getClass());
        }

        return encodingSize;
    }   

    public Enumeration keys()
    {
        return new FieldTableKeyEnumeration(this);
    }
}