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