2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
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;
27 import java.util.Map.Entry;
29 import java.util.TreeSet;
30 import java.util.concurrent.ExecutionException;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
33 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
34 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
36 final class BitsCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
38 * Use identity comparison for keys and allow classes to be GCd themselves.
40 * Since codecs can (and typically do) hold a direct or indirect strong reference to the class, they need to be also
41 * accessed via reference. Using a weak reference could be problematic, because the codec would quite often be only
42 * weakly reachable. We therefore use a soft reference, whose implementation guidance is suitable to our use case:
44 * "Virtual machine implementations are, however, encouraged to bias against clearing recently-created or
45 * recently-used soft references."
47 private static final Cache<Class<?>, @NonNull BitsCodec> CACHE = CacheBuilder.newBuilder().weakKeys().softValues()
49 private static final MethodType CONSTRUCTOR_INVOKE_TYPE = MethodType.methodType(Object.class, Boolean[].class);
51 // Ordered by position
52 private final ImmutableMap<String, Method> getters;
53 // Ordered by lexical name
54 private final ImmutableSet<String> ctorArgs;
55 private final MethodHandle ctor;
57 private BitsCodec(final Class<?> typeClass, final MethodHandle ctor, final Set<String> ctorArgs,
58 final Map<String, Method> getters) {
60 this.ctor = requireNonNull(ctor);
61 this.ctorArgs = ImmutableSet.copyOf(ctorArgs);
62 this.getters = ImmutableMap.copyOf(getters);
65 static @NonNull BitsCodec of(final Class<?> returnType, final BitsTypeDefinition rootType)
66 throws ExecutionException {
67 return CACHE.get(returnType, () -> {
68 final Map<String, Method> getters = new LinkedHashMap<>();
69 final Set<String> ctorArgs = new TreeSet<>();
71 for (Bit bit : rootType.getBits()) {
72 final Method valueGetter = returnType.getMethod(BindingMapping.GETTER_PREFIX
73 + BindingMapping.getClassName(bit.getName()));
74 ctorArgs.add(bit.getName());
75 getters.put(bit.getName(), valueGetter);
77 Constructor<?> constructor = null;
78 for (Constructor<?> cst : returnType.getConstructors()) {
79 if (!cst.getParameterTypes()[0].equals(returnType)) {
84 final MethodHandle ctor = MethodHandles.publicLookup().unreflectConstructor(constructor)
85 .asSpreader(Boolean[].class, ctorArgs.size()).asType(CONSTRUCTOR_INVOKE_TYPE);
86 return new BitsCodec(returnType, ctor, ctorArgs, getters);
91 @SuppressWarnings("checkstyle:illegalCatch")
92 public Object deserialize(final Object input) {
93 checkArgument(input instanceof Set);
94 @SuppressWarnings("unchecked")
95 final Set<String> casted = (Set<String>) input;
98 * We can do this walk based on field set sorted by name, since constructor arguments in Java Binding are
101 * This means we will construct correct array for construction of bits object.
103 final Boolean[] args = new Boolean[ctorArgs.size()];
105 for (String value : ctorArgs) {
106 args[currentArg++] = casted.contains(value);
110 return ctor.invokeExact(args);
111 } catch (Throwable e) {
112 throw new IllegalStateException("Failed to instantiate object for " + input, e);
117 public Set<String> serialize(final Object input) {
118 final Collection<String> result = new ArrayList<>(getters.size());
119 for (Entry<String, Method> valueGet : getters.entrySet()) {
122 value = (Boolean) valueGet.getValue().invoke(input);
123 } catch (IllegalAccessException | InvocationTargetException e) {
124 throw new IllegalArgumentException("Failed to get bit " + valueGet.getKey(), e);
128 result.add(valueGet.getKey());
131 return result.size() == getters.size() ? getters.keySet() : ImmutableSet.copyOf(result);