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