SchemaUnawareCodec is AbstractIllegalArgumentCodec
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / EncapsulatedValueCodec.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Throwables;
13 import com.google.common.cache.CacheBuilder;
14 import com.google.common.cache.CacheLoader;
15 import com.google.common.cache.LoadingCache;
16 import java.lang.invoke.MethodHandle;
17 import java.lang.invoke.MethodHandles;
18 import java.lang.invoke.MethodHandles.Lookup;
19 import java.lang.invoke.MethodType;
20 import java.lang.reflect.Method;
21 import java.util.concurrent.ExecutionException;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
24
25 /**
26  * Derived YANG types are just immutable value holders for simple value
27  * types, which are same as in NormalizedNode model.
28  */
29 final class EncapsulatedValueCodec extends SchemaUnawareCodec {
30     private static final MethodType OBJ_METHOD = MethodType.methodType(Object.class, Object.class);
31
32     /*
33      * Use identity comparison for keys and allow classes to be GCd themselves.
34      *
35      * Since codecs can (and typically do) hold a direct or indirect strong reference to the class, they need to be also
36      * accessed via reference. Using a weak reference could be problematic, because the codec would quite often be only
37      * weakly reachable. We therefore use a soft reference, whose implementation guidance is suitable to our use case:
38      *
39      *     "Virtual machine implementations are, however, encouraged to bias against clearing recently-created or
40      *      recently-used soft references."
41      */
42     private static final LoadingCache<Class<?>, EncapsulatedValueCodec> CACHE = CacheBuilder.newBuilder().weakKeys()
43         .softValues().build(new CacheLoader<>() {
44             @Override
45             public EncapsulatedValueCodec load(final Class<?> key) throws ReflectiveOperationException {
46                 final Method m = key.getMethod(BindingMapping.SCALAR_TYPE_OBJECT_GET_VALUE_NAME);
47                 final Lookup lookup = MethodHandles.publicLookup();
48                 final MethodHandle getter = lookup.unreflect(m).asType(OBJ_METHOD);
49                 final Class<?> valueType = m.getReturnType();
50                 final MethodHandle constructor = lookup.findConstructor(key,
51                     MethodType.methodType(void.class, valueType)).asType(OBJ_METHOD);
52                 return new EncapsulatedValueCodec(constructor, getter, valueType);
53             }
54         });
55
56     private final MethodHandle constructor;
57     private final MethodHandle getter;
58     private final Class<?> valueType;
59
60     private EncapsulatedValueCodec(final MethodHandle constructor, final MethodHandle getter,
61             final Class<?> valueType) {
62         this.constructor = requireNonNull(constructor);
63         this.getter = requireNonNull(getter);
64         this.valueType = requireNonNull(valueType);
65     }
66
67     static @NonNull EncapsulatedValueCodec of(final Class<?> typeClz) throws ExecutionException {
68         // FIXME: require base class to be ScalarTypeObject
69         return CACHE.get(typeClz);
70     }
71
72     /**
73      * Quick check if a value object has a chance to deserialize using {@link #deserialize(Object)}.
74      *
75      * @param value Value to be checked
76      * @return True if the value can be encapsulated
77      */
78     boolean canAcceptObject(final Object value) {
79         return valueType.isInstance(value);
80     }
81
82     @Override
83     @SuppressWarnings("checkstyle:illegalCatch")
84     protected Object deserializeImpl(final Object input) {
85         try {
86             return constructor.invokeExact(input);
87         } catch (Throwable e) {
88             Throwables.throwIfUnchecked(e);
89             throw new IllegalStateException(e);
90         }
91     }
92
93     @Override
94     @SuppressWarnings("checkstyle:illegalCatch")
95     protected Object serializeImpl(final Object input) {
96         try {
97             return getter.invokeExact(input);
98         } catch (Throwable e) {
99             Throwables.throwIfUnchecked(e);
100             throw new IllegalStateException(e);
101         }
102     }
103 }