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