2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
10 import static java.util.Objects.requireNonNull;
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;
22 import java.util.Map.Entry;
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;
39 * Codec support for extracting the {@link Identifiable#key()} method return from a MapEntryNode.
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);
46 private final ValueContext keyContext;
47 private final MethodHandle ctor;
48 private final QName keyName;
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);
59 Identifier<?> deserializeIdentifierImpl(final NodeIdentifierWithPredicates nip) throws Throwable {
60 return (Identifier<?>) ctor.invokeExact(keyContext.deserialize(nip.getValue(keyName)));
64 NodeIdentifierWithPredicates serializeIdentifier(final QName qname, final Identifier<?> key) {
65 return NodeIdentifierWithPredicates.of(qname, keyName, keyContext.getAndSerialize(key));
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;
75 MultiKey(final ListEffectiveStatement schema, final Class<? extends Identifier<?>> keyClass,
76 final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
77 super(schema, keyClass, identifiable);
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);
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.
87 final Set<QName> keyDef = schema.findFirstEffectiveSubstatementArgument(KeyEffectiveStatement.class)
89 predicateTemplate = ImmutableOffsetMapTemplate.ordered(keyDef);
90 this.keyValueContexts = predicateTemplate.instantiateTransformed(keyValueContexts, (key, value) -> value);
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.
96 * BUG-2755: remove this if order is made declaration-order-dependent
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);
105 Identifier<?> deserializeIdentifierImpl(final NodeIdentifierWithPredicates nip) throws Throwable {
106 final Object[] bindingValues = new Object[keysInBindingOrder.size()];
108 for (final QName key : keysInBindingOrder) {
109 bindingValues[offset++] = keyValueContexts.get(key).deserialize(nip.getValue(key));
112 return (Identifier<?>) ctor.invokeExact(bindingValues);
116 NodeIdentifierWithPredicates serializeIdentifier(final QName qname, final Identifier<?> key) {
117 final Object[] values = new Object[keyValueContexts.size()];
119 for (final ValueContext valueCtx : keyValueContexts.values()) {
120 values[offset++] = valueCtx.getAndSerialize(key);
123 return NodeIdentifierWithPredicates.of(qname, predicateTemplate.instantiateWithValues(values));
127 private static final Logger LOG = LoggerFactory.getLogger(IdentifiableItemCodec.class);
129 private final Class<?> identifiable;
130 private final QName qname;
132 IdentifiableItemCodec(final ListEffectiveStatement schema, final Class<? extends Identifier<?>> keyClass,
133 final Class<?> identifiable) {
134 this.identifiable = requireNonNull(identifiable);
135 qname = schema.argument();
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()) {
143 throw new IllegalArgumentException("Key " + keyClass + " of " + identifiable + " has no components");
145 final Entry<QName, ValueContext> entry = keyValueContexts.entrySet().iterator().next();
146 return new SingleKey(schema, keyClass, identifiable, entry.getKey(), entry.getValue());
148 return new MultiKey(schema, keyClass, identifiable, keyValueContexts);
152 @SuppressWarnings({ "rawtypes", "unchecked" })
153 final @NonNull IdentifiableItem<?, ?> domToBinding(final NodeIdentifierWithPredicates input) {
154 return IdentifiableItem.of((Class) identifiable, (Identifier) deserializeIdentifier(requireNonNull(input)));
157 final @NonNull NodeIdentifierWithPredicates bindingToDom(final IdentifiableItem<?, ?> input) {
158 return serializeIdentifier(qname, input.getKey());
161 @SuppressWarnings("checkstyle:illegalCatch")
162 final @NonNull Identifier<?> deserializeIdentifier(final @NonNull NodeIdentifierWithPredicates input) {
164 return deserializeIdentifierImpl(input);
165 } catch (Throwable e) {
166 Throwables.throwIfUnchecked(e);
167 throw new IllegalStateException("Failed to deserialize " + input, e);
171 @SuppressWarnings("checkstyle:illegalThrows")
172 abstract @NonNull Identifier<?> deserializeIdentifierImpl(@NonNull NodeIdentifierWithPredicates nip)
175 abstract @NonNull NodeIdentifierWithPredicates serializeIdentifier(QName qname, Identifier<?> key);
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);
185 // Do not consider deprecated constructors
186 if (isDeprecated(ctor)) {
187 LOG.debug("Skipping deprecated constructor {}", ctor);
191 // Do not consider copy constructors
192 if (clazz.equals(ctor.getParameterTypes()[0])) {
193 LOG.debug("Skipping copy constructor {}", ctor);
198 return MethodHandles.publicLookup().unreflectConstructor(ctor);
199 } catch (IllegalAccessException e) {
200 throw new IllegalStateException("Cannot access constructor " + ctor + " in class " + clazz, e);
203 throw new IllegalArgumentException("Supplied class " + clazz + " does not have required constructor.");
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;