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