Split STATIC_CODECS into per-type caches
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / BitsCodec.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.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.cache.Cache;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.collect.ImmutableMap;
16 import com.google.common.collect.ImmutableSet;
17 import java.lang.invoke.MethodHandle;
18 import java.lang.invoke.MethodHandles;
19 import java.lang.invoke.MethodType;
20 import java.lang.reflect.Constructor;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.LinkedHashMap;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Set;
29 import java.util.TreeSet;
30 import java.util.concurrent.ExecutionException;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.opendaylight.mdsal.binding.dom.codec.impl.ValueTypeCodec.SchemaUnawareCodec;
33 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
34 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
35 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
36
37 final class BitsCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
38     /*
39      * Use identity comparison for keys and allow classes to be GCd themselves.
40      *
41      * Since codecs can (and typically do) hold a direct or indirect strong reference to the class, they need to be also
42      * accessed via reference. Using a weak reference could be problematic, because the codec would quite often be only
43      * weakly reachable. We therefore use a soft reference, whose implementation guidance is suitable to our use case:
44      *
45      *     "Virtual machine implementations are, however, encouraged to bias against clearing recently-created or
46      *      recently-used soft references."
47      */
48     private static final Cache<Class<?>, @NonNull BitsCodec> CACHE = CacheBuilder.newBuilder().weakKeys().softValues()
49         .build();
50     private static final MethodType CONSTRUCTOR_INVOKE_TYPE = MethodType.methodType(Object.class, Boolean[].class);
51
52     // Ordered by position
53     private final ImmutableMap<String, Method> getters;
54     // Ordered by lexical name
55     private final ImmutableSet<String> ctorArgs;
56     private final MethodHandle ctor;
57
58     private BitsCodec(final Class<?> typeClass, final MethodHandle ctor, final Set<String> ctorArgs,
59             final Map<String, Method> getters) {
60         super(typeClass);
61         this.ctor = requireNonNull(ctor);
62         this.ctorArgs = ImmutableSet.copyOf(ctorArgs);
63         this.getters = ImmutableMap.copyOf(getters);
64     }
65
66     static @NonNull BitsCodec of(final Class<?> returnType, final BitsTypeDefinition rootType)
67             throws ExecutionException {
68         return CACHE.get(returnType, () -> {
69             final Map<String, Method> getters = new LinkedHashMap<>();
70             final Set<String> ctorArgs = new TreeSet<>();
71
72             for (Bit bit : rootType.getBits()) {
73                 final Method valueGetter = returnType.getMethod(BindingMapping.GETTER_PREFIX
74                     + BindingMapping.getClassName(bit.getName()));
75                 ctorArgs.add(bit.getName());
76                 getters.put(bit.getName(), valueGetter);
77             }
78             Constructor<?> constructor = null;
79             for (Constructor<?> cst : returnType.getConstructors()) {
80                 if (!cst.getParameterTypes()[0].equals(returnType)) {
81                     constructor = cst;
82                 }
83             }
84
85             final MethodHandle ctor = MethodHandles.publicLookup().unreflectConstructor(constructor)
86                     .asSpreader(Boolean[].class, ctorArgs.size()).asType(CONSTRUCTOR_INVOKE_TYPE);
87             return new BitsCodec(returnType, ctor, ctorArgs, getters);
88         });
89     }
90
91     @Override
92     @SuppressWarnings("checkstyle:illegalCatch")
93     public Object deserialize(final Object input) {
94         checkArgument(input instanceof Set);
95         @SuppressWarnings("unchecked")
96         final Set<String> casted = (Set<String>) input;
97
98         /*
99          * We can do this walk based on field set sorted by name, since constructor arguments in Java Binding are
100          * sorted by name.
101          *
102          * This means we will construct correct array for construction of bits object.
103          */
104         final Boolean[] args = new Boolean[ctorArgs.size()];
105         int currentArg = 0;
106         for (String value : ctorArgs) {
107             args[currentArg++] = casted.contains(value);
108         }
109
110         try {
111             return ctor.invokeExact(args);
112         } catch (Throwable e) {
113             throw new IllegalStateException("Failed to instantiate object for " + input, e);
114         }
115     }
116
117     @Override
118     public Set<String> serialize(final Object input) {
119         final Collection<String> result = new ArrayList<>(getters.size());
120         for (Entry<String, Method> valueGet : getters.entrySet()) {
121             final Boolean value;
122             try {
123                 value = (Boolean) valueGet.getValue().invoke(input);
124             } catch (IllegalAccessException | InvocationTargetException e) {
125                 throw new IllegalArgumentException("Failed to get bit " + valueGet.getKey(), e);
126             }
127
128             if (value) {
129                 result.add(valueGet.getKey());
130             }
131         }
132         return result.size() == getters.size() ? getters.keySet() : ImmutableSet.copyOf(result);
133     }
134 }