Sharpen CodecDataObject.data
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / AbstractDataObjectCodecContext.java
1 /*
2  * Copyright (c) 2023 PANTHEON.tech, s.r.o. 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.ImmutableMap;
12 import com.google.common.collect.ImmutableSet;
13 import java.lang.invoke.MethodHandle;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Optional;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
20 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
21 import org.opendaylight.yangtools.yang.binding.Augmentation;
22 import org.opendaylight.yangtools.yang.binding.DataObject;
23 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
27 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
28 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
29
30 /**
31  * Abstract base for {@link DataObjectCodecContext} and {@link AugmentationNodeContext}. They share most of their
32  * mechanics, but notably:
33  * <ol>
34  *   <li>DataObjectCodecContext has an exact DistinctNodeContainer and YangInstanceIdentifier mapping and can be the
35  *       target of augmentations (i.e. can implement Augmentable contract)</li>
36  *   <li>AugmentationNodeContext has neither of those traits and really is just a filter of its parent
37  *       DistinctNodeContainer</li>
38  * </ol>
39  *
40  * <p>
41  * Unfortunately {@code Augmentation} is a also a {@link DataObject}, so things get a bit messy.
42  *
43  * <p>
44  * While this class is public, it not part of API surface and is an implementation detail. The only reason for it being
45  * public is that it needs to be accessible by code generated at runtime.
46  */
47 public abstract class AbstractDataObjectCodecContext<D extends DataObject, T extends CompositeRuntimeType>
48         extends DataContainerCodecContext<D, T> {
49     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
50     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
51     private final ImmutableMap<NodeIdentifier, NodeContextSupplier> byYang;
52     private final ImmutableMap<String, ValueNodeCodecContext> leafChild;
53     private final MethodHandle proxyConstructor;
54
55     AbstractDataObjectCodecContext(final DataContainerCodecPrototype<T> prototype,
56             final CodecDataObjectAnalysis<T> analysis) {
57         super(prototype);
58         byBindingArgClass = analysis.byBindingArgClass;
59         byStreamClass = analysis.byStreamClass;
60         byYang = analysis.byYang;
61         leafChild = analysis.leafNodes;
62         proxyConstructor = analysis.proxyConstructor;
63     }
64
65     @Override
66     public final WithStatus getSchema() {
67         // FIXME: Bad cast, we should be returning an EffectiveStatement perhaps?
68         return (WithStatus) getType().statement();
69     }
70
71     @Override
72     @SuppressWarnings("unchecked")
73     public final <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
74         return (DataContainerCodecContext<C, ?>) childNonNull(streamChildPrototype(childClass), childClass,
75             "Child %s is not valid child of %s", getBindingClass(), childClass).get();
76     }
77
78     @SuppressWarnings("unchecked")
79     @Override
80     public final <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
81             final Class<C> childClass) {
82         final var childProto = streamChildPrototype(childClass);
83         if (childProto != null) {
84             return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
85         }
86         return Optional.empty();
87     }
88
89     @Nullable DataContainerCodecPrototype<?> streamChildPrototype(final @NonNull Class<?> childClass) {
90         return byStreamClass.get(childClass);
91     }
92
93     @Override
94     public final DataContainerCodecContext<?, ?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
95             final List<PathArgument> builder) {
96         final var argType = arg.getType();
97         final var context = childNonNull(pathChildPrototype(argType), argType,
98             "Class %s is not valid child of %s", argType, getBindingClass())
99             .get();
100         if (context instanceof ChoiceNodeCodecContext<?> choice) {
101             choice.addYangPathArgument(arg, builder);
102
103             final var caseType = arg.getCaseType();
104             final var type = arg.getType();
105             final DataContainerCodecContext<?, ?> caze;
106             if (caseType.isPresent()) {
107                 // Non-ambiguous addressing this should not pose any problems
108                 caze = choice.streamChild(caseType.orElseThrow());
109             } else {
110                 caze = choice.getCaseByChildClass(type);
111             }
112
113             caze.addYangPathArgument(arg, builder);
114             return caze.bindingPathArgumentChild(arg, builder);
115         }
116         context.addYangPathArgument(arg, builder);
117         return context;
118     }
119
120     @Nullable DataContainerCodecPrototype<?> pathChildPrototype(final @NonNull Class<? extends DataObject> argType) {
121         return byBindingArgClass.get(argType);
122     }
123
124     @Override
125     public final NodeCodecContext yangPathArgumentChild(final PathArgument arg) {
126         NodeContextSupplier supplier;
127         if (arg instanceof NodeIdentifier nodeId) {
128             supplier = yangChildSupplier(nodeId);
129         } else if (arg instanceof NodeIdentifierWithPredicates nip) {
130             supplier = yangChildSupplier(new NodeIdentifier(nip.getNodeType()));
131         } else {
132             supplier = null;
133         }
134         return childNonNull(supplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
135     }
136
137     @Nullable NodeContextSupplier yangChildSupplier(final @NonNull NodeIdentifier arg) {
138         return byYang.get(arg);
139     }
140
141     @SuppressWarnings("checkstyle:illegalCatch")
142     final @NonNull D createBindingProxy(final DataContainerNode node) {
143         try {
144             return (D) proxyConstructor.invokeExact(this, node);
145         } catch (final Throwable e) {
146             Throwables.throwIfUnchecked(e);
147             throw new IllegalStateException(e);
148         }
149     }
150
151     final ValueNodeCodecContext getLeafChild(final String name) {
152         final ValueNodeCodecContext value = leafChild.get(name);
153         if (value == null) {
154             throw new IncorrectNestingException("Leaf %s is not valid for %s", name, getBindingClass());
155         }
156         return value;
157     }
158
159     final @NonNull ImmutableSet<NodeIdentifier> byYangKeySet() {
160         return byYang.keySet();
161     }
162
163     abstract @NonNull Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
164         DataContainerNode data);
165 }