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