5397e50ad4ca84981ec06afae2b27c7d02e3073a
[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.LinkedHashMap;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.ValueContext;
23 import org.opendaylight.mdsal.binding.javav2.spec.base.IdentifiableItem;
24 import org.opendaylight.yangtools.concepts.Codec;
25 import org.opendaylight.yangtools.concepts.Identifier;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
28 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
29
30 /**
31  * Codec for serialize/deserialize list.
32  */
33 @Beta
34 public final class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
35
36     private final Map<QName, ValueContext> keyValueContexts;
37     private final List<QName> keysInBindingOrder;
38     private final ListSchemaNode schema;
39     private final Class<?> identifiable;
40     private final MethodHandle ctorInvoker;
41     private final MethodHandle ctor;
42
43     /**
44      * Prepare constructor of binding object of list with resolving key values if exists.
45      *
46      * @param schema
47      *            - list schema node
48      * @param keyClass
49      *            - binding class of key
50      * @param identifiable
51      *            - binding class of list
52      * @param keyValueContexts
53      *            - key value contexts
54      */
55     public IdentifiableItemCodec(final ListSchemaNode schema, final Class<? extends Identifier> keyClass,
56             final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
57         this.schema = schema;
58         this.identifiable = identifiable;
59
60         try {
61             ctor = MethodHandles.publicLookup().unreflectConstructor(getConstructor(keyClass));
62         } catch (final IllegalAccessException e) {
63             throw new IllegalArgumentException("Missing construct in class " + keyClass, e);
64         }
65         final MethodHandle inv = MethodHandles.spreadInvoker(ctor.type(), 0);
66         this.ctorInvoker = inv.asType(inv.type().changeReturnType(Identifier.class));
67
68         /*
69          * We need to re-index to make sure we instantiate nodes in the order in which they are defined.
70          */
71         final Map<QName, ValueContext> keys = new LinkedHashMap<>();
72         for (final QName qname : schema.getKeyDefinition()) {
73             keys.put(qname, keyValueContexts.get(qname));
74         }
75         this.keyValueContexts = ImmutableMap.copyOf(keys);
76
77         /*
78          * When instantiating binding objects we need to specify constructor arguments in alphabetic order. We
79          * play a couple of tricks here to optimize CPU/memory trade-offs.
80          *
81          * We do not have to perform a sort if the source collection has less than two elements.
82          *
83          * We always perform an ImmutableList.copyOf(), as that will turn into a no-op if the source is
84          * already immutable. It will also produce optimized implementations for empty and singleton
85          * collections.
86          *
87          * BUG-2755: remove this if order is made declaration-order-dependent
88          */
89         final List<QName> unsortedKeys = schema.getKeyDefinition();
90         final List<QName> sortedKeys;
91         if (unsortedKeys.size() > 1) {
92             final List<QName> tmp = new ArrayList<>(unsortedKeys);
93             tmp.sort((q1, q2) -> q1.getLocalName().compareToIgnoreCase(q2.getLocalName()));
94             sortedKeys = tmp;
95         } else {
96             sortedKeys = unsortedKeys;
97         }
98
99         this.keysInBindingOrder = ImmutableList.copyOf(sortedKeys);
100     }
101
102     @Override
103     @SuppressWarnings("checkstyle:illegalCatch")
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") final Constructor constr : clazz.getConstructors()) {
139             final Class<?>[] parameters = constr.getParameterTypes();
140             if (!clazz.equals(parameters[0])) {
141                 // It is not copy constructor;
142                 return constr;
143             }
144         }
145         throw new IllegalArgumentException("Supplied class " + clazz + "does not have required constructor.");
146     }
147 }