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 com.google.common.collect.ImmutableSortedMap;
14 import java.lang.reflect.Method;
15 import java.util.Collection;
16 import java.util.Comparator;
17 import java.util.HashMap;
18 import java.util.List;
20 import java.util.Map.Entry;
21 import java.util.SortedMap;
22 import java.util.TreeMap;
23 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
24 import org.opendaylight.yangtools.sal.binding.model.api.Type;
25 import org.opendaylight.yangtools.yang.binding.Augmentable;
26 import org.opendaylight.yangtools.yang.binding.Augmentation;
27 import org.opendaylight.yangtools.yang.binding.DataObject;
28 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
29 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
30 import org.opendaylight.yangtools.yang.common.QName;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
38 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
39 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataContainerCodecContext<T> {
46 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
48 private static final Comparator<Method> METHOD_BY_ALPHABET = new Comparator<Method>() {
51 public int compare(final Method o1, final Method o2) {
52 return o1.getName().compareTo(o2.getName());
56 private final ImmutableMap<String, LeafNodeCodecContext> leafChild;
57 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
58 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
59 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
60 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
61 protected final Method augmentationGetter;
63 protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
66 this.leafChild = factory().getLeafNodes(bindingClass(), schema());
68 Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass());
70 Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
71 SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
72 Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
73 Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
75 // Adds leaves to mapping
76 for (LeafNodeCodecContext leaf : leafChild.values()) {
77 byMethodBuilder.put(leaf.getGetter(), leaf);
78 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
81 for (Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
82 DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
83 byMethodBuilder.put(childDataObj.getValue(), childProto);
84 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
85 byYangBuilder.put(childProto.getYangArg(), childProto);
86 if (childProto.isChoice()) {
87 ChoiceNodeCodecContext choice = (ChoiceNodeCodecContext) childProto.get();
88 for(Class<?> cazeChild : choice.getCaseChildrenClasses()) {
89 byBindingArgClassBuilder.put(cazeChild, childProto);
93 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
94 if (Augmentable.class.isAssignableFrom(bindingClass())) {
96 augmentationGetter = bindingClass().getMethod("getAugmentation", Class.class);
97 } catch (NoSuchMethodException | SecurityException e) {
98 throw new IllegalStateException("Could not get required method.",e);
100 ImmutableMap<AugmentationIdentifier, Type> augmentations = factory().getRuntimeContext()
101 .getAvailableAugmentationTypes(schema());
102 for (Entry<AugmentationIdentifier, Type> augment : augmentations.entrySet()) {
103 DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
104 if (augProto != null) {
105 byYangBuilder.put(augProto.getYangArg(), augProto);
106 byStreamClassBuilder.put(augProto.getBindingClass(), augProto);
110 augmentationGetter = null;
113 this.byYang = ImmutableMap.copyOf(byYangBuilder);
114 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
115 byBindingArgClassBuilder.putAll(byStreamClass);
116 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
120 protected DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) {
121 DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
122 if (childProto != null) {
123 return childProto.get();
126 if (Augmentation.class.isAssignableFrom(childClass)) {
128 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
129 * using reflection and walk all stream child and compare augmenations classes
130 * if they are equivalent.
132 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
134 Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
135 if ((bindingClass().equals(augTarget))) {
136 for (DataContainerCodecPrototype<?> realChild : byStreamClass.values()) {
137 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
138 && BindingReflections.isSubstitutionFor(childClass,realChild.getBindingClass())) {
139 childProto = realChild;
145 Preconditions.checkArgument(childProto != null, " Child %s is not valid child.",childClass);
146 return childProto.get();
150 protected Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass) {
151 DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
152 if(childProto != null) {
153 return Optional.<DataContainerCodecContext<?>>of(childProto.get());
155 return Optional.absent();
159 protected DataContainerCodecContext<?> getIdentifierChild(final InstanceIdentifier.PathArgument arg,
160 final List<YangInstanceIdentifier.PathArgument> builder) {
162 Class<? extends DataObject> argType = arg.getType();
163 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
164 Preconditions.checkArgument(ctxProto != null,"Invalid child");
166 DataContainerCodecContext<?> context = ctxProto.get();
167 if(context instanceof ChoiceNodeCodecContext) {
168 ChoiceNodeCodecContext casted = (ChoiceNodeCodecContext) context;
169 casted.addYangPathArgument(arg, builder);
170 DataContainerCodecContext<?> caze = casted.getCazeByChildClass(arg.getType());
171 caze.addYangPathArgument(arg, builder);
172 return caze.getIdentifierChild(arg, builder);
174 context.addYangPathArgument(arg, builder);
179 protected NodeCodecContext getYangIdentifierChild(YangInstanceIdentifier.PathArgument arg) {
180 if(arg instanceof NodeIdentifierWithPredicates) {
181 arg = new NodeIdentifier(arg.getNodeType());
183 NodeContextSupplier childSupplier = byYang.get(arg);
184 Preconditions.checkArgument(childSupplier != null, "Argument %s is not valid child of %s", arg, schema());
185 return childSupplier.get();
188 protected final LeafNodeCodecContext getLeafChild(final String name) {
189 final LeafNodeCodecContext value = leafChild.get(name);
190 Preconditions.checkArgument(value != null, "Leaf %s is not valid for %s", name, bindingClass());
194 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
195 DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
196 // Direct instantiation or use in same module in which grouping
198 DataSchemaNode sameName;
200 sameName = schema().getDataChildByName(origDef.getQName());
201 } catch (IllegalArgumentException e) {
204 final DataSchemaNode childSchema;
205 if (sameName != null) {
206 // Exactly same schema node
207 if (origDef.equals(sameName)) {
208 childSchema = sameName;
209 // We check if instantiated node was added via uses
210 // statement and is instantiation of same grouping
211 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
212 childSchema = sameName;
214 // Node has same name, but clearly is different
218 // We are looking for instantiation via uses in other module
219 QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
220 DataSchemaNode potential = schema().getDataChildByName(instantiedName);
221 // We check if it is really instantiated from same
222 // definition as class was derived
223 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
224 childSchema = potential;
229 Preconditions.checkArgument(childSchema != null, "Node %s does not have child named %s", schema(), childClass);
230 return DataContainerCodecPrototype.from(childClass, childSchema, factory());
233 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
234 ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
235 @SuppressWarnings("rawtypes")
236 final Class augClass;
238 augClass = loader.loadClass(value);
239 } catch (ClassNotFoundException e) {
240 LOG.warn("Failed to load augmentation prototype for {}", value, e);
244 Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
245 .getResolvedAugmentationSchema(schema(), augClass);
246 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
249 @SuppressWarnings("rawtypes")
250 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
251 NodeCodecContext childContext = byMethod.get(method).get();
252 Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
253 if (domChild.isPresent()) {
254 return childContext.dataFromNormalizedNode(domChild.get());
259 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
260 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
262 @SuppressWarnings("rawtypes")
263 Map map = new HashMap<>();
265 for(DataContainerCodecPrototype<?> value : byStreamClass.values()) {
266 if(Augmentation.class.isAssignableFrom(value.getBindingClass())) {
267 Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
268 if(augData.isPresent()) {
269 map.put(value.getBindingClass(), value.get().dataFromNormalizedNode(augData.get()));
276 public Collection<Method> getHashCodeAndEqualsMethods() {
277 // FIXME: Sort method in same order as in hashCode for generated class.
278 return byMethod.keySet();