Fix odlparent-3.0.0 checkstyle issues
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / IdentifiableItemCodec.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.Throwables;
11 import com.google.common.collect.ImmutableList;
12 import com.google.common.collect.ImmutableMap;
13 import java.lang.invoke.MethodHandle;
14 import java.lang.invoke.MethodHandles;
15 import java.lang.reflect.Constructor;
16 import java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.LinkedHashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import org.opendaylight.yangtools.concepts.Codec;
23 import org.opendaylight.yangtools.yang.binding.Identifier;
24 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
27 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
28
29 final class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
30     private final Map<QName, ValueContext> keyValueContexts;
31     private final List<QName> keysInBindingOrder;
32     private final ListSchemaNode schema;
33     private final Class<?> identifiable;
34     private final MethodHandle ctorInvoker;
35     private final MethodHandle ctor;
36
37     IdentifiableItemCodec(final ListSchemaNode schema, final Class<? extends Identifier<?>> keyClass,
38             final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
39         this.schema = schema;
40         this.identifiable = identifiable;
41
42         try {
43             ctor = MethodHandles.publicLookup().unreflectConstructor(getConstructor(keyClass));
44         } catch (IllegalAccessException e) {
45             throw new IllegalArgumentException("Missing constructor in class " + keyClass, e);
46         }
47         final MethodHandle inv = MethodHandles.spreadInvoker(ctor.type(), 0);
48         this.ctorInvoker = inv.asType(inv.type().changeReturnType(Identifier.class));
49
50         /*
51          * We need to re-index to make sure we instantiate nodes in the order in which
52          * they are defined.
53          */
54         final Map<QName, ValueContext> keys = new LinkedHashMap<>();
55         for (final QName qname : schema.getKeyDefinition()) {
56             keys.put(qname, keyValueContexts.get(qname));
57         }
58         this.keyValueContexts = ImmutableMap.copyOf(keys);
59
60         /*
61          * When instantiating binding objects we need to specify constructor arguments
62          * in alphabetic order. We play a couple of tricks here to optimize CPU/memory
63          * trade-offs.
64          *
65          * We do not have to perform a sort if the source collection has less than two
66          * elements.
67
68          * We always perform an ImmutableList.copyOf(), as that will turn into a no-op
69          * if the source is already immutable. It will also produce optimized implementations
70          * for empty and singleton collections.
71          *
72          * BUG-2755: remove this if order is made declaration-order-dependent
73          */
74         final List<QName> unsortedKeys = schema.getKeyDefinition();
75         final List<QName> sortedKeys;
76         if (unsortedKeys.size() > 1) {
77             final List<QName> tmp = new ArrayList<>(unsortedKeys);
78             Collections.sort(tmp, (q1, q2) -> q1.getLocalName().compareToIgnoreCase(q2.getLocalName()));
79             sortedKeys = tmp;
80         } else {
81             sortedKeys = unsortedKeys;
82         }
83
84         this.keysInBindingOrder = ImmutableList.copyOf(sortedKeys);
85     }
86
87     @Override
88     @SuppressWarnings("checkstyle:illegalCatch")
89     public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
90         final Object[] bindingValues = new Object[keysInBindingOrder.size()];
91         int offset = 0;
92
93         for (final QName key : keysInBindingOrder) {
94             final Object yangValue = input.getKeyValues().get(key);
95             bindingValues[offset++] = keyValueContexts.get(key).deserialize(yangValue);
96         }
97
98         final Identifier<?> identifier;
99         try {
100             identifier = (Identifier<?>) ctorInvoker.invokeExact(ctor, bindingValues);
101         } catch (Throwable e) {
102             Throwables.throwIfUnchecked(e);
103             throw new RuntimeException(e);
104         }
105
106         @SuppressWarnings({ "rawtypes", "unchecked" })
107         final IdentifiableItem identifiableItem = new IdentifiableItem(identifiable, identifier);
108         return identifiableItem;
109     }
110
111     @Override
112     public NodeIdentifierWithPredicates serialize(final IdentifiableItem<?, ?> input) {
113         final Object value = input.getKey();
114
115         final Map<QName, Object> values = new LinkedHashMap<>();
116         for (final Entry<QName, ValueContext> valueCtx : keyValueContexts.entrySet()) {
117             values.put(valueCtx.getKey(), valueCtx.getValue().getAndSerialize(value));
118         }
119         return new NodeIdentifierWithPredicates(schema.getQName(), values);
120     }
121
122     @SuppressWarnings("unchecked")
123     private static Constructor<? extends Identifier<?>> getConstructor(final Class<? extends Identifier<?>> clazz) {
124         for (@SuppressWarnings("rawtypes") final Constructor constr : clazz.getConstructors()) {
125             final Class<?>[] parameters = constr.getParameterTypes();
126             if (!clazz.equals(parameters[0])) {
127                 // It is not copy constructor;
128                 return constr;
129             }
130         }
131         throw new IllegalArgumentException("Supplied class " + clazz + "does not have required constructor.");
132     }
133 }