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