340ad77f37e01aa14f61713cc94dc8f63e3efe90
[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.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableSet;
15 import java.lang.invoke.MethodHandle;
16 import java.lang.invoke.MethodHandles;
17 import java.lang.invoke.MethodType;
18 import java.lang.reflect.Constructor;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.LinkedHashMap;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Set;
27 import java.util.TreeSet;
28 import java.util.concurrent.Callable;
29 import org.opendaylight.mdsal.binding.dom.codec.impl.ValueTypeCodec.SchemaUnawareCodec;
30 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
31 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
32 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
33
34 final class BitsCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
35     private static final MethodType CONSTRUCTOR_INVOKE_TYPE = MethodType.methodType(Object.class, Boolean[].class);
36
37     // Ordered by position
38     private final ImmutableMap<String, Method> getters;
39     // Ordered by lexical name
40     private final ImmutableSet<String> ctorArgs;
41     private final MethodHandle ctor;
42
43     private BitsCodec(final Class<?> typeClass, final MethodHandle ctor, final Set<String> ctorArgs,
44             final Map<String, Method> getters) {
45         super(typeClass);
46         this.ctor = requireNonNull(ctor);
47         this.ctorArgs = ImmutableSet.copyOf(ctorArgs);
48         this.getters = ImmutableMap.copyOf(getters);
49     }
50
51     static Callable<BitsCodec> loader(final Class<?> returnType, final BitsTypeDefinition rootType) {
52         return () -> {
53             final Map<String, Method> getters = new LinkedHashMap<>();
54             final Set<String> ctorArgs = new TreeSet<>();
55
56             for (Bit bit : rootType.getBits()) {
57                 final Method valueGetter = returnType.getMethod(BindingMapping.GETTER_PREFIX
58                     + BindingMapping.getClassName(bit.getName()));
59                 ctorArgs.add(bit.getName());
60                 getters.put(bit.getName(), valueGetter);
61             }
62             Constructor<?> constructor = null;
63             for (Constructor<?> cst : returnType.getConstructors()) {
64                 if (!cst.getParameterTypes()[0].equals(returnType)) {
65                     constructor = cst;
66                 }
67             }
68
69             final MethodHandle ctor = MethodHandles.publicLookup().unreflectConstructor(constructor)
70                     .asSpreader(Boolean[].class, ctorArgs.size()).asType(CONSTRUCTOR_INVOKE_TYPE);
71             return new BitsCodec(returnType, ctor, ctorArgs, getters);
72         };
73     }
74
75     @Override
76     @SuppressWarnings("checkstyle:illegalCatch")
77     public Object deserialize(final Object input) {
78         checkArgument(input instanceof Set);
79         @SuppressWarnings("unchecked")
80         final Set<String> casted = (Set<String>) input;
81
82         /*
83          * We can do this walk based on field set sorted by name, since constructor arguments in Java Binding are
84          * sorted by name.
85          *
86          * This means we will construct correct array for construction of bits object.
87          */
88         final Boolean[] args = new Boolean[ctorArgs.size()];
89         int currentArg = 0;
90         for (String value : ctorArgs) {
91             args[currentArg++] = casted.contains(value);
92         }
93
94         try {
95             return ctor.invokeExact(args);
96         } catch (Throwable e) {
97             throw new IllegalStateException("Failed to instantiate object for " + input, e);
98         }
99     }
100
101     @Override
102     public Set<String> serialize(final Object input) {
103         final Collection<String> result = new ArrayList<>(getters.size());
104         for (Entry<String, Method> valueGet : getters.entrySet()) {
105             final Boolean value;
106             try {
107                 value = (Boolean) valueGet.getValue().invoke(input);
108             } catch (IllegalAccessException | InvocationTargetException e) {
109                 throw new IllegalArgumentException("Failed to get bit " + valueGet.getKey(), e);
110             }
111
112             if (value) {
113                 result.add(valueGet.getKey());
114             }
115         }
116         return result.size() == getters.size() ? getters.keySet() : ImmutableSet.copyOf(result);
117     }
118 }