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