Binding2 runtime - Codecs impl - codecs - part3
[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);
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     public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
105         final Object[] bindingValues = new Object[keysInBindingOrder.size()];
106         int offset = 0;
107
108         for (final QName key : keysInBindingOrder) {
109             final Object yangValue = input.getKeyValues().get(key);
110             bindingValues[offset++] = keyValueContexts.get(key).deserialize(yangValue);
111         }
112
113         final Identifier identifier;
114         try {
115             identifier = (Identifier) ctorInvoker.invokeExact(ctor, bindingValues);
116         } catch (final Throwable e) {
117             throw Throwables.propagate(e);
118         }
119
120         @SuppressWarnings({ "rawtypes", "unchecked" })
121         final IdentifiableItem identifiableItem = new IdentifiableItem(identifiable, identifier);
122         return identifiableItem;
123     }
124
125     @Override
126     public NodeIdentifierWithPredicates serialize(final IdentifiableItem<?, ?> input) {
127         final Object value = input.getKey();
128
129         final Map<QName, Object> values = new LinkedHashMap<>();
130         for (final Entry<QName, ValueContext> valueCtx : keyValueContexts.entrySet()) {
131             values.put(valueCtx.getKey(), valueCtx.getValue().getAndSerialize(value));
132         }
133         return new NodeIdentifierWithPredicates(schema.getQName(), values);
134     }
135
136     @SuppressWarnings("unchecked")
137     private static Constructor<? extends Identifier> getConstructor(final Class<? extends Identifier> clazz) {
138         for (@SuppressWarnings("rawtypes")
139         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 }