summaryrefslogtreecommitdiff
path: root/qpid/java/management/agent/src/main/java/org/apache/qpid/agent/binding/ClassBinding.java
blob: 0a749580233ee54472f8acb53aef968871fbde4c (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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
/*
 *
 * 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.agent.binding;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.qpid.agent.annotations.QMFEvent;
import org.apache.qpid.agent.annotations.QMFObject;
import org.apache.qpid.agent.annotations.QMFProperty;
import org.apache.qpid.agent.annotations.QMFSeeAlso;
import org.apache.qpid.agent.annotations.QMFType;
import org.apache.qpid.agent.annotations.QMFHide;
import org.apache.qpid.transport.codec.Decoder;
import org.apache.qpid.transport.codec.Encoder;

/**
 * Binding information from a custom java class to a QMF schema
 */
public class ClassBinding implements TypeBinding
{
    private static Log log = LogFactory.getLog(ClassBinding.class);

    private static enum MethodType
    {
        READ_ONLY, READ_WRITE, METHOD, IGNORE
    }

    protected boolean exposeBehaviour = true;
    protected String pkg;
    protected BindingContext bctx;
    protected String name;
    protected ArrayList<PropertyBinding> properties = new ArrayList<PropertyBinding>();
    protected ArrayList<MethodBinding> methods = new ArrayList<MethodBinding>();
    protected Map<String, MethodBinding> methodsByName = new HashMap<String, MethodBinding>();
    protected Class javaClass;
    protected short kind = 1;
    protected byte hash[] = null;
    protected ClassBinding superType = null;

    public ClassBinding(String pkg, String name, Class cls,
            boolean exposeBehaviour, BindingContext bctx)
    {
        this.pkg = pkg;
        this.name = name;
        this.bctx = bctx;
        this.javaClass = cls;
        this.exposeBehaviour = exposeBehaviour;
    }

    protected MethodType classify(Class<?> cls, Method m)
    {
        String name = m.getName();
        MethodType returnValue = MethodType.METHOD;
        String propPrefixes[] =
        { "get", "is" };
        for (String prefix : propPrefixes)
        {
            if (name.startsWith(prefix) && m.getParameterTypes().length == 0)
            {
                try
                {
                    Class<?> type = m.getReturnType();
                    Method setter = cls.getMethod("set"
                            + name.substring(prefix.length()), type);
                    returnValue = MethodType.READ_WRITE;
                } catch (NoSuchMethodException e)
                {
                    returnValue = MethodType.READ_ONLY;
                }
                break;
            }
        }
        return returnValue;
    }

    protected String property(Method m)
    {
        String name = m.getName();
        String propPrefixes[] =
        { "get", "is" };
        for (String prefix : propPrefixes)
        {
            if (name.startsWith(prefix) && m.getParameterTypes().length == 0)
            {
                String sfx = name.substring(prefix.length());
                return Character.toLowerCase(sfx.charAt(0)) + sfx.substring(1);
            }
        }
        // If we got here, it is n invalid property
        throw new IllegalArgumentException("" + m);
    }

    protected ArrayList<Method> getMethods(Class cls)
    {
        ArrayList returnValue = new ArrayList();
        ArrayList nameList = new ArrayList();
        if ((cls != null) && (!cls.equals(Object.class)))
        {
            for (Method m : cls.getDeclaredMethods())
            {
                if (m.getAnnotation(QMFHide.class) == null)
                // && (!Modifier.isAbstract(m.getModifiers())))
                {
                    returnValue.add(m);
                    nameList.add(m.getName());
                }
            }
            // Look at the superclass, if it is also a
            // QMF object then stop.
            Class superType = cls.getSuperclass();
            if (!this.hasQMFSupertype(cls))
            {
                for (Method m : this.getMethods(cls.getSuperclass()))
                {
                    if (!nameList.contains(m.getName()))
                    {
                        returnValue.add(m);
                        nameList.add(m.getName());
                    }
                }
            }
        }
        return returnValue;
    }

    protected boolean hasQMFSupertype(Class cls)
    {
        boolean returnValue = false;
        Class superType = cls.getSuperclass();
        if (superType != null)
        {
            if ((superType.getAnnotation(QMFObject.class) != null)
                    || (superType.getAnnotation(QMFType.class) != null)
                    || (superType.getAnnotation(QMFSeeAlso.class) != null)
                    || (superType.getAnnotation(QMFEvent.class) != null))
            {
                returnValue = true;
            }
        }
        return returnValue;
    }

    protected boolean isOptional(Method m, TypeBinding type)
    {
        boolean returnValue = false;
        // Look for the annotaiton first
        QMFProperty ann = m.getAnnotation(QMFProperty.class);
        if (ann != null)
        {
            returnValue = ann.optional();
        } else
        {
            returnValue = type.optionalDefault();
        }
        return returnValue;
    }

    public ClassBinding parse()
    {
        log.debug(String.format(
                "Parsing class binding '%s' for package '%s' from class %s",
                name, pkg, javaClass.getName()));
        for (Method m : this.getMethods(javaClass))
        {
            String mname = m.getName();
            Class<?> type = m.getReturnType();
            switch (classify(javaClass, m))
            {
            case READ_ONLY:
                TypeBinding tb = bctx.getTypeBinding(type);
                boolean optional = isOptional(m, tb);
                properties.add(new PropertyBinding(property(m), tb,
                        PropertyBinding.READ_ONLY, optional));
                break;
            case READ_WRITE:
                TypeBinding tbnd = bctx.getTypeBinding(type);
                boolean opt = isOptional(m, tbnd);
                properties.add(new PropertyBinding(property(m), tbnd,
                        PropertyBinding.READ_WRITE, opt));
                break;
            case METHOD:
                // Only expose methods if told to
                if (exposeBehaviour)
                {
                    List<ParameterBinding> params = new ArrayList<ParameterBinding>();
                    int arg = 0;
                    for (Class pcls : m.getParameterTypes())
                    {
                        params.add(new ParameterBinding("arg" + arg++, bctx
                                .getTypeBinding(pcls), true, false));
                    }
                    if (type != void.class)
                    {
                        params.add(new ParameterBinding("result", bctx
                                .getTypeBinding(type), false, true));
                    }
                    methods.add(new MethodBinding(mname, params));
                }
                break;
            case IGNORE:
                break;
            }
        }
        for (MethodBinding m : methods)
        {
            methodsByName.put(m.getName(), m);
        }
        QMFEvent eventAnnotation = (QMFEvent) javaClass
                .getAnnotation(QMFEvent.class);
        if (eventAnnotation != null)
        {
            kind = 2; // Event Type
        }
        // if (this.hasQMFSupertype(javaClass)) {
        if ((javaClass.getSuperclass() != Object.class)
                && (javaClass.getSuperclass() != null))
        {
            superType = bctx.register(javaClass.getSuperclass());
        }
        return this;
    }

    public String getPackage()
    {
        return pkg;
    }

    public String getName()
    {
        return name;
    }

    public List<PropertyBinding> getProperties()
    {
        return properties;
    }

    public List<PropertyBinding> getAllProperties()
    {
        if (this.superType == null)
        {
            return properties;
        } else
        {
            List<PropertyBinding> newList = new ArrayList<PropertyBinding>(
                    properties);
            for (PropertyBinding p : superType.getAllProperties())
            {
                if (!newList.contains(p))
                {
                    newList.add(p);
                }
            }
            return newList;
        }
    }

    public List<MethodBinding> getMethods()
    {
        return methods;
    }

    public MethodBinding getMethod(String name)
    {
        return methodsByName.get(name);
    }

    // Use this format
    // bytes value
    // 0-3 package name
    // 4-7 class name
    // 8-11 property signature hash
    // 12-15 method signature hash
    // FIXME: Hash codes seem to mess things up
    public byte[] getSchemaHash()
    {
        if (null == hash)
        {
            hash = new byte[16];
            StringBuilder blder = new StringBuilder();
            int packageHash = pkg.hashCode();
            int classHash = name.hashCode();
            int propertyHash = 0;
            int methodHash = 0;
            for (PropertyBinding p : properties)
            {
                blder.append(p.getName()).append(":").append(
                        p.getType().getCode()).append(":")
                        .append(p.getAccess()).append(":").append(
                                p.isOptional());
            }
            propertyHash = blder.toString().hashCode();
            blder = new StringBuilder();
            for (MethodBinding m : methods)
            {
                blder.append(m.getName());
                for (ParameterBinding p : m.getParameters())
                {
                    String direction = p.isIn() ? "in" : "out";
                    blder.append(":").append(p.getName()).append(":").append(
                            direction).append(":")
                            .append(p.getType().getCode());
                }
            }
            methodHash = blder.toString().hashCode();
            hash[0] = (byte) (packageHash >> 24);
            hash[1] = (byte) (packageHash >> 16);
            hash[2] = (byte) (packageHash >> 8);
            hash[3] = (byte) (packageHash);
            hash[4] = (byte) (classHash >> 24);
            hash[5] = (byte) (classHash >> 16);
            hash[6] = (byte) (classHash >> 8);
            hash[7] = (byte) (classHash);
            hash[8] = (byte) (propertyHash >> 24);
            hash[9] = (byte) (propertyHash >> 16);
            hash[10] = (byte) (propertyHash >> 8);
            hash[11] = (byte) (propertyHash);
            hash[12] = (byte) (methodHash >> 24);
            hash[13] = (byte) (methodHash >> 16);
            hash[14] = (byte) (methodHash >> 8);
            hash[15] = (byte) (methodHash);
        }
        return hash;
    }

    public void encode(Encoder enc)
    {
        log.debug(String.format("encoding %s %s with superclass %s", this
                .getRefClass(), this.getRefPackage(), superType));
        enc.writeUint8(kind); // kind
        enc.writeStr8(pkg);
        enc.writeStr8(name);
        enc.writeBin128(this.getSchemaHash()); // schema hash
        // Send true (1) if we have a super-type
        //if (superType == null)
        //{
        //    enc.writeUint8((short) 0);
        //} else
        //{
        //    enc.writeUint8((short) 1);
        //}
        enc.writeUint16(properties.size());
        // Events do not have the method size sent
        if (kind == 1)
        {
            enc.writeUint16(0);
            enc.writeUint16(methods.size());
        }
        // Add the super type information if we have it
        //if (superType != null)
        //{
        //    enc.writeStr8(superType.pkg);
        //    enc.writeStr8(superType.name);
        //    enc.writeBin128(superType.getSchemaHash()); // schema hash
        //}
        for (PropertyBinding p : properties)
        {
            log.trace("encoding property " + p.getName());
            p.encode(enc);
        }
        for (MethodBinding m : methods)
        {
            m.encode(enc);
        }
    }

    // Type Binding functions
    public short getCode()
    {
        return (short) 20;
    }

    public Class<?> getJavaClass()
    {
        return javaClass;
    }

    public Object decode(Decoder dec)
    {
        // FIXME This only works with POJOs
        short typeCode = dec.readUint8();
        log.trace("Type code: " + typeCode);
        if (typeCode == 20)
        {
            String packageName = dec.readStr8();
            String className = dec.readStr8();
            log
                    .debug(String
                            .format(
                                    "Decoding an object for package %s class %s with bindings for %s %s",
                                    packageName, className, this.pkg, this.name));
            byte schemaHash[] = dec.readBin128();
            // Check to see that this is me, and not a subclass
            if (packageName.equals(this.pkg) && className.equals(this.name))
            {
                return decodeWithNoHeaders(dec);
            } else
            {
                ClassBinding mcls = bctx
                        .getClassBinding(packageName, className);
                return mcls.decodeWithNoHeaders(dec);
            }
        } else
        {
            TypeBinding tb = QMFTypeBinding.getType(typeCode);
            return tb.decode(dec);
        }
    }

    protected Object decodeWithNoHeaders(Decoder dec)
    {
        Object instance = null;
        try
        {
            log.trace("Creating a new instance of " + this.javaClass.getName());
            instance = this.javaClass.newInstance();
        } catch (Exception e)
        {
            log.error("Could not instantiate object of class"
                    + this.javaClass.getName());
            throw new BindingException(e);
        }
        List<String> excludes = this.processPresenceMasks(dec);
        for (PropertyBinding p : getAllProperties())
        {
            if (!excludes.contains(p.getName()))
            {
                Object value = p.getType().decode(dec);
                BindingUtils.set(p, value, instance);
            }
        }
        return instance;
    }

    protected List<String> processPresenceMasks(Decoder dec)
    {
        List<String> excludes = new ArrayList<String>();
        short bit = 0;
        short mask = 0;
        for (PropertyBinding prop : properties)
        {
            if (prop.isOptional())
            {
                if (bit == 0)
                {
                    mask = dec.readUint8();
                    bit = 1;
                }
                if ((mask & bit) == 0)
                {
                    log.trace("Going in exclude " + prop.getName());
                    excludes.add(prop.getName());
                }
                bit *= 2;
                if (bit == 256)
                {
                    bit = 0;
                }
            }
        }
        return excludes;
    }

    public void encode(Encoder enc, Object value)
    {
        // if the object is null, assume this is the
        // correct class
        if (value == null || (value.getClass().equals(this.javaClass)))
        {
            String pkg = getPackage();
            String cls = getName();
            log.debug(String.format("Encoding class %s:%s", pkg, cls));
            enc.writeUint8(this.getCode());
            enc.writeStr8(pkg);
            enc.writeStr8(cls);
            enc.writeBin128(this.getSchemaHash());
            short bit = 0;
            short mask = 0;
            if (value != null)
            {
                // Encode the property presence masks first.
                // if this is not an event
                if (!isEvent())
                {
                    for (PropertyBinding p : getAllProperties())
                    {
                        if (p.isOptional())
                        {
                            Object pValue = BindingUtils.get(p, value);
                            if (bit == 0)
                                bit = 1;
                            if (pValue != null)
                            {
                                mask |= bit;
                            }
                            if (bit == 128)
                            {
                                enc.writeUint8(mask);
                                bit = 0;
                                mask = 0;
                            } else
                            {
                                bit = (short) (bit << 1);
                            }
                        }
                    }
                    if (bit != 0)
                    {
                        enc.writeUint8(mask);
                    }
                }
                // Now put the actual properties
                for (PropertyBinding p : getAllProperties())
                {
                    Object pValue = BindingUtils.get(p, value);
                    if (!p.isOptional() || !(pValue == null))
                    {
                        log.trace(String.format("Encoding property %s", p
                                .getName()));
                        p.getType().encode(enc, pValue);
                    }
                }
            }
            log.debug(String.format("Done with %s:%s", pkg, cls));
        } else
        {
            TypeBinding tb = bctx.getTypeBinding(value.getClass());
            if (tb == null)
            {
                throw new BindingException(String.format(
                        "No class named %s defined for this context ", value
                                .getClass()));
            } else
            {
                if (tb.isNative())
                {
                    enc.writeUint8(tb.getCode());
                }
                tb.encode(enc, value);
            }
        }
    }

    public boolean isNative()
    {
        return false;
    }

    public boolean optionalDefault()
    {
        return true;
    }

    public String getRefClass()
    {
        return this.name;
    }

    public String getRefPackage()
    {
        return this.pkg;
    }

    public short getKind()
    {
        return kind;
    }

    public boolean isEvent()
    {
        return kind == 2;
    }

    public void setKind(short kind)
    {
        this.kind = kind;
    }
}