summaryrefslogtreecommitdiff
path: root/lang/java/src/com/sleepycat/persist/impl/ReflectionAccessor.java
blob: 11c1761f1ba4fc73c85821f06913dda735c39be5 (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
/*-
 * See the file LICENSE for redistribution information.
 *
 * Copyright (c) 2002, 2015 Oracle and/or its affiliates.  All rights reserved.
 *
 */

package com.sleepycat.persist.impl;

import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.List;

import com.sleepycat.compat.DbCompat;

/**
 * Implements Accessor using reflection.
 *
 * @author Mark Hayes
 */
class ReflectionAccessor implements Accessor {

    private static final FieldAccess[] EMPTY_KEYS = {};

    private Class type;
    private Accessor superAccessor;
    private Constructor constructor;
    private FieldAccess priKey;
    private FieldAccess[] secKeys;
    private FieldAccess[] nonKeys;

    private ReflectionAccessor(Class type, Accessor superAccessor) {
        this.type = type;
        this.superAccessor = superAccessor;
        try {
            constructor = type.getDeclaredConstructor();
        } catch (NoSuchMethodException e) {
            throw DbCompat.unexpectedState(type.getName());
        }
        if (!Modifier.isPublic(type.getModifiers()) || 
            !Modifier.isPublic(constructor.getModifiers())) {
            setAccessible(constructor, type.getName() + "()");
        }
    }

    /**
     * Creates an accessor for a complex type.
     */
    ReflectionAccessor(Catalog catalog,
                       Class type,
                       Accessor superAccessor,
                       FieldInfo priKeyField,
                       List<FieldInfo> secKeyFields,
                       List<FieldInfo> nonKeyFields) {
        this(type, superAccessor);
        if (priKeyField != null) {
            priKey = getField(catalog, priKeyField,
                              true /*isRequiredKeyField*/);
        } else {
            priKey = null;
        }
        if (secKeyFields.size() > 0) {
            secKeys = getFields(catalog, secKeyFields,
                                false /*isRequiredKeyField*/);
        } else {
            secKeys = EMPTY_KEYS;
        }
        if (nonKeyFields.size() > 0) {
            nonKeys = getFields(catalog, nonKeyFields,
                                false /*isRequiredKeyField*/);
        } else {
            nonKeys = EMPTY_KEYS;
        }
    }

    /**
     * Creates an accessor for a composite key type.
     */
    ReflectionAccessor(Catalog catalog,
                       Class type,
                       List<FieldInfo> fieldInfos) {
        this(type, null);
        priKey = null;
        secKeys = EMPTY_KEYS;
        nonKeys = getFields(catalog, fieldInfos, true /*isRequiredKeyField*/);
    }

    private FieldAccess[] getFields(Catalog catalog,
                                    List<FieldInfo> fieldInfos,
                                    boolean isRequiredKeyField) {
        int index = 0;
        FieldAccess[] fields = new FieldAccess[fieldInfos.size()];
        for (FieldInfo info : fieldInfos) {
            fields[index] = getField(catalog, info, isRequiredKeyField);
            index += 1;
        }
        return fields;
    }

    private FieldAccess getField(Catalog catalog,
                                 FieldInfo fieldInfo,
                                 boolean isRequiredKeyField) {
        Field field;
        try {
            field = type.getDeclaredField(fieldInfo.getName());
        } catch (NoSuchFieldException e) {
            throw DbCompat.unexpectedException(e);
        }
        if (!Modifier.isPublic(type.getModifiers()) || 
            !Modifier.isPublic(field.getModifiers())) {
            setAccessible(field, field.getName());
        }
        Class fieldCls = field.getType();
        if (fieldCls.isPrimitive()) {
            assert SimpleCatalog.isSimpleType(fieldCls);
            return new PrimitiveAccess
                (field, (SimpleFormat) catalog.getFormat(fieldCls.getName()));
        } else if (isRequiredKeyField) {
            Format format = catalog.getFormat(fieldInfo.getClassName());
            assert format != null;
            return new KeyObjectAccess(field, format);
        } else if (fieldCls == String.class) {
            return new StringAccess(field);
        } else {
            return new ObjectAccess(field);
        }
    }

    private void setAccessible(AccessibleObject object, String memberName) {
        try {
            object.setAccessible(true);
        } catch (SecurityException e) {
            throw new IllegalStateException
                ("Unable to access non-public member: " +
                 type.getName() + '.' + memberName +
                 ". Please configure the Java Security Manager setting: " +
                 " ReflectPermission suppressAccessChecks", e);
        }
    }

    public Object newInstance() {
        try {
            return constructor.newInstance();
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        } catch (InstantiationException e) {
            throw DbCompat.unexpectedException(e);
        } catch (InvocationTargetException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public Object newArray(int len) {
        return Array.newInstance(type, len);
    }

    public boolean isPriKeyFieldNullOrZero(Object o) {
        try {
            if (priKey != null) {
                return priKey.isNullOrZero(o);
            } else if (superAccessor != null) {
                return superAccessor.isPriKeyFieldNullOrZero(o);
            } else {
                throw DbCompat.unexpectedState("No primary key field");
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public void writePriKeyField(Object o, EntityOutput output)
        throws RefreshException {

        try {
            if (priKey != null) {
                priKey.write(o, output);
            } else if (superAccessor != null) {
                superAccessor.writePriKeyField(o, output);
            } else {
                throw DbCompat.unexpectedState("No primary key field");
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public void readPriKeyField(Object o, EntityInput input)
        throws RefreshException {

        try {
            if (priKey != null) {
                priKey.read(o, input);
            } else if (superAccessor != null) {
                superAccessor.readPriKeyField(o, input);
            } else {
                throw DbCompat.unexpectedState("No primary key field");
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public void writeSecKeyFields(Object o, EntityOutput output)
        throws RefreshException {

        try {
        
            /* 
             * In JE 5.0, String is treated as primitive type, so String does
             * not need to be registered. [#19247]
             */
            if (priKey != null && !priKey.isPrimitive && !priKey.isString) {
                output.registerPriKeyObject(priKey.field.get(o));
            }
            if (superAccessor != null) {
                superAccessor.writeSecKeyFields(o, output);
            }
            for (int i = 0; i < secKeys.length; i += 1) {
                secKeys[i].write(o, output);
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public void readSecKeyFields(Object o,
                                 EntityInput input,
                                 int startField,
                                 int endField,
                                 int superLevel)
        throws RefreshException {

        try {
            if (priKey != null && !priKey.isPrimitive && !priKey.isString) {
                input.registerPriKeyObject(priKey.field.get(o));
            } else if (priKey != null && priKey.isString) {
                input.registerPriStringKeyObject(priKey.field.get(o));
            }
            if (superLevel != 0 && superAccessor != null) {
                superAccessor.readSecKeyFields
                    (o, input, startField, endField, superLevel - 1);
            } else {
                if (superLevel > 0) {
                    throw DbCompat.unexpectedState
                        ("Superclass does not exist");
                }
            }
            if (superLevel <= 0) {
                for (int i = startField;
                     i <= endField && i < secKeys.length;
                     i += 1) {
                    secKeys[i].read(o, input);
                }
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public void writeNonKeyFields(Object o, EntityOutput output)
        throws RefreshException {

        try {
            if (superAccessor != null) {
                superAccessor.writeNonKeyFields(o, output);
            }
            for (int i = 0; i < nonKeys.length; i += 1) {
                nonKeys[i].write(o, output);
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public void readNonKeyFields(Object o,
                                 EntityInput input,
                                 int startField,
                                 int endField,
                                 int superLevel)
        throws RefreshException {

        try {
            if (superLevel != 0 && superAccessor != null) {
                superAccessor.readNonKeyFields
                    (o, input, startField, endField, superLevel - 1);
            } else {
                if (superLevel > 0) {
                    throw DbCompat.unexpectedState
                        ("Superclass does not exist");
                }
            }
            if (superLevel <= 0) {
                for (int i = startField;
                     i <= endField && i < nonKeys.length;
                     i += 1) {
                    nonKeys[i].read(o, input);
                }
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public void writeCompositeKeyFields(Object o, EntityOutput output)
        throws RefreshException {

        try {
            for (int i = 0; i < nonKeys.length; i += 1) {
                nonKeys[i].write(o, output);
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public void readCompositeKeyFields(Object o, EntityInput input)
        throws RefreshException {

        try {
            for (int i = 0; i < nonKeys.length; i += 1) {
                nonKeys[i].read(o, input);
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public Object getField(Object o,
                           int field,
                           int superLevel,
                           boolean isSecField) {
        if (superLevel > 0) {
            return superAccessor.getField
                (o, field, superLevel - 1, isSecField);
        }
        try {
            Field fld =
                isSecField ? secKeys[field].field : nonKeys[field].field;
            return fld.get(o);
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    public void setField(Object o,
                         int field,
                         int superLevel,
                         boolean isSecField,
                         Object value) {
        if (superLevel > 0) {
            superAccessor.setField
                (o, field, superLevel - 1, isSecField, value);
            return;
        }
        try {
            Field fld =
                isSecField ? secKeys[field].field : nonKeys[field].field;
            fld.set(o, value);
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }
    
    public void setPriField(Object o, Object value) {
        try {
            if (priKey != null) {
                priKey.field.set(o, value);
            } else if (superAccessor != null) {
                superAccessor.setPriField(o, value);
            } else {
                throw DbCompat.unexpectedState("No primary key field");
            }
        } catch (IllegalAccessException e) {
            throw DbCompat.unexpectedException(e);
        }
    }

    /**
     * Abstract base class for field access classes.
     */
    private static abstract class FieldAccess {

        Field field;
        boolean isPrimitive;
        boolean isString = false;

        FieldAccess(Field field) {
            this.field = field;
            isPrimitive = field.getType().isPrimitive();
            isString = 
                field.getType().getName().equals(String.class.getName());
        }

        /**
         * Writes a field.
         */
        abstract void write(Object o, EntityOutput out)
            throws IllegalAccessException, RefreshException;

        /**
         * Reads a field.
         */
        abstract void read(Object o, EntityInput in)
            throws IllegalAccessException, RefreshException;

        /**
         * Returns whether a field is null (for reference types) or zero (for
         * primitive integer types).  This implementation handles the reference
         * types.
         */
        boolean isNullOrZero(Object o)
            throws IllegalAccessException {

            return field.get(o) == null;
        }
    }

    /**
     * Access for fields with object types.
     */
    private static class ObjectAccess extends FieldAccess {

        ObjectAccess(Field field) {
            super(field);
        }

        @Override
        void write(Object o, EntityOutput out)
            throws IllegalAccessException, RefreshException {

            out.writeObject(field.get(o), null);
        }

        @Override
        void read(Object o, EntityInput in)
            throws IllegalAccessException, RefreshException {

            field.set(o, in.readObject());
        }
    }

    /**
     * Access for primary key fields and composite key fields with object
     * types.
     */
    private static class KeyObjectAccess extends FieldAccess {

        private Format format;

        KeyObjectAccess(Field field, Format format) {
            super(field);
            this.format = format;
        }

        @Override
        void write(Object o, EntityOutput out)
            throws IllegalAccessException, RefreshException {

            out.writeKeyObject(field.get(o), format);
        }

        @Override
        void read(Object o, EntityInput in)
            throws IllegalAccessException, RefreshException {

            field.set(o, in.readKeyObject(format));
        }
    }

    /**
     * Access for String fields, that are not primary key fields or composite
     * key fields with object types.
     */
    private static class StringAccess extends FieldAccess {
        StringAccess(Field field) {
            super(field);
        }

        @Override
        void write(Object o, EntityOutput out)
            throws IllegalAccessException, RefreshException {
            
            out.writeString((String) field.get(o));
        }

        @Override
        void read(Object o, EntityInput in)
            throws IllegalAccessException, RefreshException {

            field.set(o, in.readStringObject());
        }
    }

    /**
     * Access for fields with primitive types.
     */
    private static class PrimitiveAccess extends FieldAccess {

        private SimpleFormat format;

        PrimitiveAccess(Field field, SimpleFormat format) {
            super(field);
            this.format = format;
        }

        @Override
        void write(Object o, EntityOutput out)
            throws IllegalAccessException {

            format.writePrimitiveField(o, out, field);
        }

        @Override
        void read(Object o, EntityInput in)
            throws IllegalAccessException, RefreshException {

            format.readPrimitiveField(o, in, field);
        }

        @Override
        boolean isNullOrZero(Object o)
            throws IllegalAccessException {

            return field.getLong(o) == 0;
        }
    }
}