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