Disconnect IdentifiableItemCodec from IllegalArgumentCodec
[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 static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.ImmutableList;
14 import java.lang.invoke.MethodHandle;
15 import java.lang.invoke.MethodHandles;
16 import java.lang.invoke.MethodType;
17 import java.lang.reflect.Constructor;
18 import java.util.ArrayList;
19 import java.util.Comparator;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Map.Entry;
23 import java.util.Set;
24 import org.eclipse.jdt.annotation.NonNull;
25 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
26 import org.opendaylight.yangtools.util.ImmutableOffsetMap;
27 import org.opendaylight.yangtools.util.ImmutableOffsetMapTemplate;
28 import org.opendaylight.yangtools.yang.binding.Identifiable;
29 import org.opendaylight.yangtools.yang.binding.Identifier;
30 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
33 import org.opendaylight.yangtools.yang.model.api.stmt.KeyEffectiveStatement;
34 import org.opendaylight.yangtools.yang.model.api.stmt.ListEffectiveStatement;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * Codec support for extracting the {@link Identifiable#key()} method return from a MapEntryNode.
40  */
41 // FIXME: sealed class when we have JDK17+
42 abstract class IdentifiableItemCodec {
43     private static final class SingleKey extends IdentifiableItemCodec {
44         private static final MethodType CTOR_TYPE = MethodType.methodType(Identifier.class, Object.class);
45
46         private final ValueContext keyContext;
47         private final MethodHandle ctor;
48         private final QName keyName;
49
50         SingleKey(final ListEffectiveStatement schema, final Class<? extends Identifier<?>> keyClass,
51                 final Class<?> identifiable, final QName keyName, final ValueContext keyContext) {
52             super(schema, keyClass, identifiable);
53             this.keyContext = requireNonNull(keyContext);
54             this.keyName = requireNonNull(keyName);
55             ctor = getConstructor(keyClass, 1).asType(CTOR_TYPE);
56         }
57
58         @Override
59         Identifier<?> deserializeIdentifierImpl(final NodeIdentifierWithPredicates nip) throws Throwable {
60             return (Identifier<?>) ctor.invokeExact(keyContext.deserialize(nip.getValue(keyName)));
61         }
62
63         @Override
64         NodeIdentifierWithPredicates serializeIdentifier(final QName qname, final Identifier<?> key) {
65             return NodeIdentifierWithPredicates.of(qname, keyName, keyContext.getAndSerialize(key));
66         }
67     }
68
69     private static final class MultiKey extends IdentifiableItemCodec {
70         private final ImmutableOffsetMapTemplate<QName> predicateTemplate;
71         private final ImmutableOffsetMap<QName, ValueContext> keyValueContexts;
72         private final ImmutableList<QName> keysInBindingOrder;
73         private final MethodHandle ctor;
74
75         MultiKey(final ListEffectiveStatement schema, final Class<? extends Identifier<?>> keyClass,
76                 final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
77             super(schema, keyClass, identifiable);
78
79             final MethodHandle tmpCtor = getConstructor(keyClass, keyValueContexts.size());
80             final MethodHandle inv = MethodHandles.spreadInvoker(tmpCtor.type(), 0);
81             ctor = inv.asType(inv.type().changeReturnType(Identifier.class)).bindTo(tmpCtor);
82
83             /*
84              * We need to re-index to make sure we instantiate nodes in the order in which they are defined. We will
85              * also need to instantiate values in the same order.
86              */
87             final Set<QName> keyDef = schema.findFirstEffectiveSubstatementArgument(KeyEffectiveStatement.class)
88                 .orElseThrow();
89             predicateTemplate = ImmutableOffsetMapTemplate.ordered(keyDef);
90             this.keyValueContexts = predicateTemplate.instantiateTransformed(keyValueContexts, (key, value) -> value);
91
92             /*
93              * When instantiating binding objects we need to specify constructor arguments in alphabetic order. If the
94              * order matches definition order, we try to reuse the key definition.
95              *
96              * BUG-2755: remove this if order is made declaration-order-dependent
97              */
98             final List<QName> tmp = new ArrayList<>(keyDef);
99             // This is not terribly efficient but gets the job done
100             tmp.sort(Comparator.comparing(qname -> BindingMapping.getPropertyName(qname.getLocalName())));
101             keysInBindingOrder = ImmutableList.copyOf(tmp.equals(List.copyOf(keyDef)) ? keyDef : tmp);
102         }
103
104         @Override
105         Identifier<?> deserializeIdentifierImpl(final NodeIdentifierWithPredicates nip) throws Throwable {
106             final Object[] bindingValues = new Object[keysInBindingOrder.size()];
107             int offset = 0;
108             for (final QName key : keysInBindingOrder) {
109                 bindingValues[offset++] = keyValueContexts.get(key).deserialize(nip.getValue(key));
110             }
111
112             return (Identifier<?>) ctor.invokeExact(bindingValues);
113         }
114
115         @Override
116         NodeIdentifierWithPredicates serializeIdentifier(final QName qname, final Identifier<?> key) {
117             final Object[] values = new Object[keyValueContexts.size()];
118             int offset = 0;
119             for (final ValueContext valueCtx : keyValueContexts.values()) {
120                 values[offset++] = valueCtx.getAndSerialize(key);
121             }
122
123             return NodeIdentifierWithPredicates.of(qname, predicateTemplate.instantiateWithValues(values));
124         }
125     }
126
127     private static final Logger LOG = LoggerFactory.getLogger(IdentifiableItemCodec.class);
128
129     private final Class<?> identifiable;
130     private final QName qname;
131
132     IdentifiableItemCodec(final ListEffectiveStatement schema, final Class<? extends Identifier<?>> keyClass,
133             final Class<?> identifiable) {
134         this.identifiable = requireNonNull(identifiable);
135         qname = schema.argument();
136     }
137
138     static IdentifiableItemCodec of(final ListEffectiveStatement schema,
139             final Class<? extends Identifier<?>> keyClass, final Class<?> identifiable,
140                     final Map<QName, ValueContext> keyValueContexts) {
141         switch (keyValueContexts.size()) {
142             case 0:
143                 throw new IllegalArgumentException("Key " + keyClass + " of " + identifiable + " has no components");
144             case 1:
145                 final Entry<QName, ValueContext> entry = keyValueContexts.entrySet().iterator().next();
146                 return new SingleKey(schema, keyClass, identifiable, entry.getKey(), entry.getValue());
147             default:
148                 return new MultiKey(schema, keyClass, identifiable, keyValueContexts);
149         }
150     }
151
152     @SuppressWarnings({ "rawtypes", "unchecked" })
153     final @NonNull IdentifiableItem<?, ?> domToBinding(final NodeIdentifierWithPredicates input) {
154         return IdentifiableItem.of((Class) identifiable, (Identifier) deserializeIdentifier(requireNonNull(input)));
155     }
156
157     final @NonNull NodeIdentifierWithPredicates bindingToDom(final IdentifiableItem<?, ?> input) {
158         return serializeIdentifier(qname, input.getKey());
159     }
160
161     @SuppressWarnings("checkstyle:illegalCatch")
162     final @NonNull Identifier<?> deserializeIdentifier(final @NonNull NodeIdentifierWithPredicates input) {
163         try {
164             return deserializeIdentifierImpl(input);
165         } catch (Throwable e) {
166             Throwables.throwIfUnchecked(e);
167             throw new IllegalStateException("Failed to deserialize " + input, e);
168         }
169     }
170
171     @SuppressWarnings("checkstyle:illegalThrows")
172     abstract @NonNull Identifier<?> deserializeIdentifierImpl(@NonNull NodeIdentifierWithPredicates nip)
173             throws Throwable;
174
175     abstract @NonNull NodeIdentifierWithPredicates serializeIdentifier(QName qname, Identifier<?> key);
176
177     static MethodHandle getConstructor(final Class<? extends Identifier<?>> clazz, final int nrArgs) {
178         for (final Constructor<?> ctor : clazz.getConstructors()) {
179             // Check argument count
180             if (ctor.getParameterCount() != nrArgs) {
181                 LOG.debug("Skipping {} due to argument count mismatch", ctor);
182                 continue;
183             }
184
185             // Do not consider deprecated constructors
186             if (isDeprecated(ctor)) {
187                 LOG.debug("Skipping deprecated constructor {}", ctor);
188                 continue;
189             }
190
191             // Do not consider copy constructors
192             if (clazz.equals(ctor.getParameterTypes()[0])) {
193                 LOG.debug("Skipping copy constructor {}", ctor);
194                 continue;
195             }
196
197             try {
198                 return MethodHandles.publicLookup().unreflectConstructor(ctor);
199             } catch (IllegalAccessException e) {
200                 throw new IllegalStateException("Cannot access constructor " + ctor + " in class " + clazz, e);
201             }
202         }
203         throw new IllegalArgumentException("Supplied class " + clazz + " does not have required constructor.");
204     }
205
206     // This could be inlined, but then it throws off Eclipse analysis, which thinks the return is always non-null
207     private static boolean isDeprecated(final Constructor<?> ctor) {
208         return ctor.getAnnotation(Deprecated.class) != null;
209     }
210 }