Promote SchemaUnawareCodec to a top-level construct
[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.Cache;
14 import com.google.common.cache.CacheBuilder;
15 import java.lang.invoke.MethodHandle;
16 import java.lang.invoke.MethodHandles;
17 import java.lang.invoke.MethodHandles.Lookup;
18 import java.lang.invoke.MethodType;
19 import java.lang.reflect.Method;
20 import java.util.concurrent.ExecutionException;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
23 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
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 ReflectionBasedCodec implements SchemaUnawareCodec {
30     /*
31      * Use identity comparison for keys and allow classes to be GCd themselves.
32      *
33      * Since codecs can (and typically do) hold a direct or indirect strong reference to the class, they need to be also
34      * accessed via reference. Using a weak reference could be problematic, because the codec would quite often be only
35      * weakly reachable. We therefore use a soft reference, whose implementation guidance is suitable to our use case:
36      *
37      *     "Virtual machine implementations are, however, encouraged to bias against clearing recently-created or
38      *      recently-used soft references."
39      */
40     private static final Cache<Class<?>, EncapsulatedValueCodec> CACHE = CacheBuilder.newBuilder().weakKeys()
41         .softValues().build();
42     private static final MethodType OBJ_METHOD = MethodType.methodType(Object.class, Object.class);
43
44     private final MethodHandle constructor;
45     private final MethodHandle getter;
46     private final Class<?> valueType;
47
48     private EncapsulatedValueCodec(final Class<?> typeClz, final MethodHandle constructor, final MethodHandle getter,
49             final Class<?> valueType) {
50         super(typeClz);
51         this.constructor = requireNonNull(constructor);
52         this.getter = requireNonNull(getter);
53         this.valueType = requireNonNull(valueType);
54     }
55
56     static @NonNull EncapsulatedValueCodec of(final Class<?> typeClz, final TypeDefinition<?> typeDef)
57             throws ExecutionException {
58         return CACHE.get(typeClz, () -> {
59             final Method m = typeClz.getMethod(BindingMapping.SCALAR_TYPE_OBJECT_GET_VALUE_NAME);
60             final Lookup lookup = MethodHandles.publicLookup();
61             final MethodHandle getter = lookup.unreflect(m).asType(OBJ_METHOD);
62             final Class<?> valueType = m.getReturnType();
63             final MethodHandle constructor = lookup.findConstructor(typeClz,
64                 MethodType.methodType(void.class, valueType)).asType(OBJ_METHOD);
65             return new EncapsulatedValueCodec(typeClz, constructor, getter, valueType);
66         });
67     }
68
69     /**
70      * Quick check if a value object has a chance to deserialize using {@link #deserialize(Object)}.
71      *
72      * @param value Value to be checked
73      * @return True if the value can be encapsulated
74      */
75     boolean canAcceptObject(final Object value) {
76         return valueType.isInstance(value);
77     }
78
79     @Override
80     @SuppressWarnings("checkstyle:illegalCatch")
81     public Object deserialize(final Object input) {
82         try {
83             return constructor.invokeExact(input);
84         } catch (Throwable e) {
85             Throwables.throwIfUnchecked(e);
86             throw new IllegalStateException(e);
87         }
88     }
89
90     @Override
91     @SuppressWarnings("checkstyle:illegalCatch")
92     public Object serialize(final Object input) {
93         try {
94             return getter.invokeExact(input);
95         } catch (Throwable e) {
96             Throwables.throwIfUnchecked(e);
97             throw new IllegalStateException(e);
98         }
99     }
100 }