Rehost BindingMapping in yang.binding.contract.Naming
[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 com.google.common.base.Verify.verifyNotNull;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.base.Throwables;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import java.lang.invoke.MethodHandle;
18 import java.lang.invoke.MethodHandles;
19 import java.lang.invoke.MethodType;
20 import java.util.concurrent.ExecutionException;
21 import org.eclipse.jdt.annotation.NonNull;
22 import org.opendaylight.yangtools.yang.binding.ScalarTypeObject;
23 import org.opendaylight.yangtools.yang.binding.contract.Naming;
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     @SuppressWarnings("rawtypes")
43     private static final LoadingCache<Class<? extends ScalarTypeObject>, @NonNull EncapsulatedValueCodec> CACHE =
44         CacheBuilder.newBuilder().weakKeys().softValues().build(new CacheLoader<>() {
45             @Override
46             public EncapsulatedValueCodec load(final Class<? extends ScalarTypeObject> key)
47                     throws ReflectiveOperationException {
48                 final var method = key.getMethod(Naming.SCALAR_TYPE_OBJECT_GET_VALUE_NAME);
49                 final var lookup = MethodHandles.publicLookup();
50                 final var retType = method.getReturnType();
51                 return new EncapsulatedValueCodec(lookup.findConstructor(key,
52                     MethodType.methodType(void.class, retType)).asType(OBJ_METHOD),
53                     lookup.unreflect(method).asType(OBJ_METHOD), retType);
54             }
55         });
56
57     private final MethodHandle constructor;
58     private final MethodHandle getter;
59     private final Class<?> valueType;
60
61     private EncapsulatedValueCodec(final MethodHandle constructor, final MethodHandle getter,
62             final Class<?> valueType) {
63         this.constructor = requireNonNull(constructor);
64         this.getter = requireNonNull(getter);
65         this.valueType = requireNonNull(valueType);
66     }
67
68     static @NonNull EncapsulatedValueCodec of(final Class<?> typeClz) throws ExecutionException {
69         return CACHE.get(typeClz.asSubclass(ScalarTypeObject.class));
70     }
71
72     static @NonNull EncapsulatedValueCodec ofUnchecked(final Class<?> typeClz) {
73         return CACHE.getUnchecked(typeClz.asSubclass(ScalarTypeObject.class));
74     }
75
76     /**
77      * Quick check if a value object has a chance to deserialize using {@link #deserialize(Object)}.
78      *
79      * @param value Value to be checked
80      * @return True if the value can be encapsulated
81      */
82     boolean canAcceptObject(final Object value) {
83         return valueType.isInstance(value);
84     }
85
86     @Override
87     @SuppressWarnings({ "null", "checkstyle:illegalCatch" })
88     protected Object deserializeImpl(final Object input) {
89         try {
90             return constructor.invokeExact(input);
91         } catch (Throwable e) {
92             Throwables.throwIfUnchecked(e);
93             throw new IllegalStateException(e);
94         }
95     }
96
97     @Override
98     @SuppressWarnings("checkstyle:illegalCatch")
99     protected Object serializeImpl(final Object input) {
100         try {
101             return verifyNotNull(getter.invokeExact(input));
102         } catch (Throwable e) {
103             Throwables.throwIfUnchecked(e);
104             throw new IllegalStateException(e);
105         }
106     }
107 }