Bug 3067: Fixed missing argument in message.
[yangtools.git] / code-generator / binding-data-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / ChoiceNodeCodecContext.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.yangtools.binding.data.codec.impl;
9
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.Iterables;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Set;
19 import javax.annotation.Nonnull;
20 import javax.annotation.Nullable;
21 import org.opendaylight.yangtools.yang.binding.DataObject;
22 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
23 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D,ChoiceSchemaNode> {
36     private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
37     private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChild;
38     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
39     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClass;
40
41     public ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceSchemaNode> prototype) {
42         super(prototype);
43         final Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder = new HashMap<>();
44         final Map<Class<?>, DataContainerCodecPrototype<?>> byClassBuilder = new HashMap<>();
45         final Map<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClassBuilder = new HashMap<>();
46         final Set<Class<?>> potentialSubstitutions = new HashSet<>();
47         // Walks all cases for supplied choice in current runtime context
48         for (final Class<?> caze : factory().getRuntimeContext().getCases(getBindingClass())) {
49             // We try to load case using exact match thus name
50             // and original schema must equals
51             final DataContainerCodecPrototype<ChoiceCaseNode> cazeDef = loadCase(caze);
52             // If we have case definition, this case is instantiated
53             // at current location and thus is valid in context of parent choice
54             if (cazeDef != null) {
55                 byClassBuilder.put(cazeDef.getBindingClass(), cazeDef);
56                 // Updates collection of case children
57                 @SuppressWarnings("unchecked")
58                 final Class<? extends DataObject> cazeCls = (Class<? extends DataObject>) caze;
59                 for (final Class<? extends DataObject> cazeChild : BindingReflections.getChildrenClasses(cazeCls)) {
60                     byCaseChildClassBuilder.put(cazeChild, cazeDef);
61                 }
62                 // Updates collection of YANG instance identifier to case
63                 for (final DataSchemaNode cazeChild : cazeDef.getSchema().getChildNodes()) {
64                     byYangCaseChildBuilder.put(new NodeIdentifier(cazeChild.getQName()), cazeDef);
65                 }
66             } else {
67                 /*
68                  * If case definition is not available, we store it for
69                  * later check if it could be used as substitution of existing one.
70                  */
71                 potentialSubstitutions.add(caze);
72             }
73         }
74
75         final Map<Class<?>, DataContainerCodecPrototype<?>> bySubstitutionBuilder = new HashMap<>();
76         /*
77          * Walks all cases which are not directly instantiated and
78          * tries to match them to instantiated cases - represent same data as instantiated case,
79          * only case name or schema path is different. This is required due property of
80          * binding specification, that if choice is in grouping schema path location is lost,
81          * and users may use incorrect case class using copy builders.
82          */
83         for(final Class<?> substitution : potentialSubstitutions) {
84             search: for(final Entry<Class<?>, DataContainerCodecPrototype<?>> real : byClassBuilder.entrySet()) {
85                 if(BindingReflections.isSubstitutionFor(substitution, real.getKey())) {
86                     bySubstitutionBuilder.put(substitution, real.getValue());
87                     break search;
88                 }
89             }
90         }
91         byClassBuilder.putAll(bySubstitutionBuilder);
92         byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
93         byClass = ImmutableMap.copyOf(byClassBuilder);
94         byCaseChildClass = ImmutableMap.copyOf(byCaseChildClassBuilder);
95     }
96
97
98     @SuppressWarnings("unchecked")
99     @Override
100     public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass) {
101         final DataContainerCodecPrototype<?> child = byClass.get(childClass);
102         return (DataContainerCodecContext<DV, ?>) childNonNull(child, childClass, "Supplied class %s is not valid case", childClass).get();
103     }
104
105
106     @SuppressWarnings("unchecked")
107     @Override
108     public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
109             final Class<DV> childClass) {
110         final DataContainerCodecPrototype<?> child = byClass.get(childClass);
111         if(child != null) {
112             return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV, ?>) child.get());
113         }
114         return Optional.absent();
115     }
116
117     Iterable<Class<?>> getCaseChildrenClasses() {
118         return byCaseChildClass.keySet();
119     }
120
121     protected DataContainerCodecPrototype<ChoiceCaseNode> loadCase(final Class<?> childClass) {
122         final Optional<ChoiceCaseNode> childSchema = factory().getRuntimeContext().getCaseSchemaDefinition(schema(), childClass);
123         if (childSchema.isPresent()) {
124             return DataContainerCodecPrototype.from(childClass, childSchema.get(), factory());
125         }
126
127         LOG.debug("Supplied class %s is not valid case in schema %s", childClass, schema());
128         return null;
129     }
130
131     @Override
132     public NodeCodecContext<?> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
133         final DataContainerCodecPrototype<?> cazeProto = byYangCaseChild.get(arg);
134         childNonNull(cazeProto != null, arg,"Argument %s is not valid child of %s", arg, schema());
135         return cazeProto.get().yangPathArgumentChild(arg);
136     }
137
138     @SuppressWarnings("unchecked")
139     @Override
140     @Nullable
141     public D deserialize(final NormalizedNode<?, ?> data) {
142         Preconditions.checkArgument(data instanceof ChoiceNode);
143         final NormalizedNodeContainer<?, ?, NormalizedNode<?,?>> casted = (NormalizedNodeContainer<?, ?, NormalizedNode<?,?>>) data;
144         final NormalizedNode<?, ?> first = Iterables.getFirst(casted.getValue(), null);
145
146         if (first == null) {
147             return null;
148         }
149         final DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
150         return (D) caze.get().deserialize(data);
151     }
152
153     DataContainerCodecContext<?, ?> getCazeByChildClass(final @Nonnull Class<? extends DataObject> type) {
154         final DataContainerCodecPrototype<?> protoCtx =
155                 childNonNull(byCaseChildClass.get(type), type, "Class %s is not child of any cases for %s", type,
156                         bindingArg());
157         return protoCtx.get();
158     }
159
160     @Override
161     protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
162         return deserialize(normalizedNode);
163     }
164
165     @Override
166     public PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
167         Preconditions.checkArgument(getDomPathArgument().equals(arg));
168         return null;
169     }
170
171     @Override
172     public YangInstanceIdentifier.PathArgument serializePathArgument(
173             final PathArgument arg) {
174         // FIXME: check for null, since binding container is null.
175         return getDomPathArgument();
176     }
177
178 }