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.yangtools.binding.data.codec.impl;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import java.lang.reflect.Method;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.List;
18 import java.util.Map.Entry;
19 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
20 import org.opendaylight.yangtools.sal.binding.model.api.Type;
21 import org.opendaylight.yangtools.yang.binding.Augmentable;
22 import org.opendaylight.yangtools.yang.binding.Augmentation;
23 import org.opendaylight.yangtools.yang.binding.DataObject;
24 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
25 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
34 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
35 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataContainerCodecContext<T> {
42 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
44 private final ImmutableMap<String, LeafNodeCodecContext> leafChild;
45 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
46 private final ImmutableMap<Method, NodeContextSupplier> byMethod;
47 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
48 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
49 protected final Method augmentationGetter;
51 protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
54 this.leafChild = factory().getLeafNodes(bindingClass(), schema());
56 Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass());
58 Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
59 Map<Method, NodeContextSupplier> byMethodBuilder = new HashMap<>();
60 Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
61 Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
63 // Adds leaves to mapping
64 for (LeafNodeCodecContext leaf : leafChild.values()) {
65 byMethodBuilder.put(leaf.getGetter(), leaf);
66 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
69 for (Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
70 DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
71 byMethodBuilder.put(childDataObj.getValue(), childProto);
72 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
73 byYangBuilder.put(childProto.getYangArg(), childProto);
74 if (childProto.isChoice()) {
75 ChoiceNodeCodecContext choice = (ChoiceNodeCodecContext) childProto.get();
76 for(Class<?> cazeChild : choice.getCaseChildrenClasses()) {
77 byBindingArgClassBuilder.put(cazeChild, childProto);
81 this.byMethod = ImmutableMap.copyOf(byMethodBuilder);
82 if (Augmentable.class.isAssignableFrom(bindingClass())) {
84 augmentationGetter = bindingClass().getMethod("getAugmentation", Class.class);
85 } catch (NoSuchMethodException | SecurityException e) {
86 throw new IllegalStateException("Could not get required method.",e);
88 ImmutableMap<AugmentationIdentifier, Type> augmentations = factory().getRuntimeContext()
89 .getAvailableAugmentationTypes(schema());
90 for (Entry<AugmentationIdentifier, Type> augment : augmentations.entrySet()) {
91 DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
92 if (augProto != null) {
93 byYangBuilder.put(augProto.getYangArg(), augProto);
94 byStreamClassBuilder.put(augProto.getBindingClass(), augProto);
98 augmentationGetter = null;
101 this.byYang = ImmutableMap.copyOf(byYangBuilder);
102 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
103 byBindingArgClassBuilder.putAll(byStreamClass);
104 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
108 protected DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) {
109 DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
110 if (childProto != null) {
111 return childProto.get();
114 if (Augmentation.class.isAssignableFrom(childClass)) {
116 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
117 * using reflection and walk all stream child and compare augmenations classes
118 * if they are equivalent.
120 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
122 Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
123 if ((bindingClass().equals(augTarget))) {
124 for (DataContainerCodecPrototype<?> realChild : byStreamClass.values()) {
125 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
126 && BindingReflections.isSubstitutionFor(childClass,realChild.getBindingClass())) {
127 childProto = realChild;
133 Preconditions.checkArgument(childProto != null, " Child %s is not valid child.",childClass);
134 return childProto.get();
138 protected Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass) {
139 DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
140 if(childProto != null) {
141 return Optional.<DataContainerCodecContext<?>>of(childProto.get());
143 return Optional.absent();
147 protected DataContainerCodecContext<?> getIdentifierChild(final InstanceIdentifier.PathArgument arg,
148 final List<YangInstanceIdentifier.PathArgument> builder) {
150 Class<? extends DataObject> argType = arg.getType();
151 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
152 Preconditions.checkArgument(ctxProto != null,"Invalid child");
154 DataContainerCodecContext<?> context = ctxProto.get();
155 if(context instanceof ChoiceNodeCodecContext) {
156 ChoiceNodeCodecContext casted = (ChoiceNodeCodecContext) context;
157 casted.addYangPathArgument(arg, builder);
158 DataContainerCodecContext<?> caze = casted.getCazeByChildClass(arg.getType());
159 caze.addYangPathArgument(arg, builder);
160 return caze.getIdentifierChild(arg, builder);
162 context.addYangPathArgument(arg, builder);
167 protected NodeCodecContext getYangIdentifierChild(YangInstanceIdentifier.PathArgument arg) {
168 if(arg instanceof NodeIdentifierWithPredicates) {
169 arg = new NodeIdentifier(arg.getNodeType());
171 NodeContextSupplier childSupplier = byYang.get(arg);
172 Preconditions.checkArgument(childSupplier != null, "Argument %s is not valid child of %s", arg, schema());
173 return childSupplier.get();
176 protected final LeafNodeCodecContext getLeafChild(final String name) {
177 final LeafNodeCodecContext value = leafChild.get(name);
178 Preconditions.checkArgument(value != null, "Leaf %s is not valid for %s", name, bindingClass());
182 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
183 DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
184 // Direct instantiation or use in same module in which grouping
186 DataSchemaNode sameName;
188 sameName = schema().getDataChildByName(origDef.getQName());
189 } catch (IllegalArgumentException e) {
192 final DataSchemaNode childSchema;
193 if (sameName != null) {
194 // Exactly same schema node
195 if (origDef.equals(sameName)) {
196 childSchema = sameName;
197 // We check if instantiated node was added via uses
198 // statement and is instantiation of same grouping
199 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
200 childSchema = sameName;
202 // Node has same name, but clearly is different
206 // We are looking for instantiation via uses in other module
207 QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
208 DataSchemaNode potential = schema().getDataChildByName(instantiedName);
209 // We check if it is really instantiated from same
210 // definition as class was derived
211 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
212 childSchema = potential;
217 Preconditions.checkArgument(childSchema != null, "Node %s does not have child named %s", schema(), childClass);
218 return DataContainerCodecPrototype.from(childClass, childSchema, factory());
221 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
222 ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
223 @SuppressWarnings("rawtypes")
224 final Class augClass;
226 augClass = loader.loadClass(value);
227 } catch (ClassNotFoundException e) {
228 LOG.warn("Failed to load augmentation prototype for {}", value, e);
232 Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
233 .getResolvedAugmentationSchema(schema(), augClass);
234 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
237 @SuppressWarnings("rawtypes")
238 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
239 NodeCodecContext childContext = byMethod.get(method).get();
240 Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
241 if (domChild.isPresent()) {
242 return childContext.dataFromNormalizedNode(domChild.get());
247 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
248 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
250 @SuppressWarnings("rawtypes")
251 Map map = new HashMap<>();
253 for(DataContainerCodecPrototype<?> value : byStreamClass.values()) {
254 if(Augmentation.class.isAssignableFrom(value.getBindingClass())) {
255 Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
256 if(augData.isPresent()) {
257 map.put(value.getBindingClass(), value.get().dataFromNormalizedNode(augData.get()));
264 public Collection<Method> getHashCodeAndEqualsMethods() {
265 // FIXME: Sort method in same order as in hashCode for generated class.
266 return byMethod.keySet();