MDSAL-298: properly handle unkeyed lists
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / DataContainerCodecContext.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.collect.ImmutableCollection;
12 import com.google.common.collect.ImmutableSet;
13 import java.io.IOException;
14 import java.util.List;
15 import javax.annotation.Nonnull;
16 import javax.annotation.Nullable;
17 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
18 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
19 import org.opendaylight.yangtools.yang.binding.DataObject;
20 import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
21 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
22 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.common.QNameModule;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
28 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
29 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
30
31 abstract class DataContainerCodecContext<D extends DataObject,T> extends NodeCodecContext<D>  {
32
33     private final DataContainerCodecPrototype<T> prototype;
34     private volatile DataObjectSerializer eventStreamSerializer;
35
36     protected DataContainerCodecContext(final DataContainerCodecPrototype<T> prototype) {
37         this.prototype = prototype;
38     }
39
40     @Override
41     public final T getSchema() {
42         return prototype.getSchema();
43     }
44
45     @Override
46     public final ChildAddressabilitySummary getChildAddressabilitySummary() {
47         return prototype.getChildAddressabilitySummary();
48     }
49
50     protected final QNameModule namespace() {
51         return prototype.getNamespace();
52     }
53
54     protected final CodecContextFactory factory() {
55         return prototype.getFactory();
56     }
57
58     @Override
59     protected YangInstanceIdentifier.PathArgument getDomPathArgument() {
60         return prototype.getYangArg();
61     }
62
63     /**
64      * Returns nested node context using supplied YANG Instance Identifier
65      *
66      * @param arg Yang Instance Identifier Argument
67      * @return Context of child
68      * @throws IllegalArgumentException If supplied argument does not represent valid child.
69      */
70     @Override
71     public abstract NodeCodecContext<?> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg);
72
73     /**
74      * Returns nested node context using supplied Binding Instance Identifier
75      * and adds YANG instance identifiers to supplied list.
76      *
77      * @param arg Binding Instance Identifier Argument
78      * @return Context of child or null if supplied {@code arg} does not represent valid child.
79      * @throws IllegalArgumentException If supplied argument does not represent valid child.
80      */
81     @Override
82     public @Nullable DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
83             final List<YangInstanceIdentifier.PathArgument> builder) {
84         final DataContainerCodecContext<?,?> child = streamChild(arg.getType());
85         if(child != null) {
86             if (builder != null) {
87                 child.addYangPathArgument(arg,builder);
88             }
89             return child;
90         }
91         throw new IllegalArgumentException("SUpplied argument is not valid child");
92     }
93
94     /**
95      * Returns deserialized Binding Path Argument from YANG instance identifier.
96      *
97      * @param domArg
98      * @return
99      */
100     protected PathArgument getBindingPathArgument(final YangInstanceIdentifier.PathArgument domArg) {
101         return bindingArg();
102     }
103
104     protected final PathArgument bindingArg() {
105         return prototype.getBindingArg();
106     }
107
108     @SuppressWarnings("unchecked")
109     @Override
110     public final Class<D> getBindingClass() {
111         return Class.class.cast(prototype.getBindingClass());
112     }
113
114     /**
115      *
116      * Returns child context as if it was walked by
117      * {@link BindingStreamEventWriter}. This means that to enter case, one
118      * must issue getChild(ChoiceClass).getChild(CaseClass).
119      *
120      * @param childClass
121      * @return Context of child node or null, if supplied class is not subtree child
122      * @throws IllegalArgumentException If supplied child class is not valid in specified context.
123      */
124     @Override
125     public abstract @Nullable <DV extends DataObject> DataContainerCodecContext<DV,?> streamChild(final Class<DV> childClass) throws IllegalArgumentException;
126
127     /**
128      *
129      * Returns child context as if it was walked by
130      * {@link BindingStreamEventWriter}. This means that to enter case, one
131      * must issue getChild(ChoiceClass).getChild(CaseClass).
132      *
133      * @param childClass
134      * @return Context of child or Optional absent is supplied class is not applicable in context.
135      */
136     @Override
137     public abstract <DV extends DataObject> Optional<DataContainerCodecContext<DV,?>> possibleStreamChild(final Class<DV> childClass);
138
139     @Override
140     public String toString() {
141         return getClass().getSimpleName() + " [" + prototype.getBindingClass() + "]";
142     }
143
144     @Override
145     public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
146             final ImmutableCollection<Class<? extends DataObject>> cacheSpecifier) {
147         if(cacheSpecifier.isEmpty()) {
148             return new NonCachingCodec<>(this);
149         }
150         return new CachingNormalizedNodeCodec<D>(this,ImmutableSet.copyOf(cacheSpecifier));
151     }
152
153     BindingStreamEventWriter createWriter(final NormalizedNodeStreamWriter domWriter) {
154         return BindingToNormalizedStreamWriter.create(this, domWriter);
155     }
156
157     @Nonnull
158     protected final <V> V childNonNull(@Nullable final V nullable, final YangInstanceIdentifier.PathArgument child,
159             final String message, final Object... args) {
160         if (nullable != null) {
161             return nullable;
162         }
163         MissingSchemaException.checkModulePresent(factory().getRuntimeContext().getSchemaContext(), child);
164         throw IncorrectNestingException.create(message, args);
165     }
166
167     @Nonnull
168     protected final <V> V childNonNull(@Nullable final V nullable, final QName child, final String message,
169             final Object... args) {
170         if (nullable != null) {
171             return nullable;
172         }
173         MissingSchemaException.checkModulePresent(factory().getRuntimeContext().getSchemaContext(), child);
174         throw IncorrectNestingException.create(message, args);
175     }
176
177     @Nonnull
178     protected final <V> V childNonNull(@Nullable final V nullable, final Class<?> childClass, final String message,
179             final Object... args) {
180         if (nullable != null) {
181             return nullable;
182         }
183         MissingSchemaForClassException.check(factory().getRuntimeContext(), childClass);
184         MissingClassInLoadingStrategyException.check(factory().getRuntimeContext().getStrategy(), childClass);
185         throw IncorrectNestingException.create(message, args);
186     }
187
188     DataObjectSerializer eventStreamSerializer() {
189         if(eventStreamSerializer == null) {
190             eventStreamSerializer = factory().getEventStreamSerializer(getBindingClass());
191         }
192         return eventStreamSerializer;
193     }
194
195     @Override
196     public NormalizedNode<?, ?> serialize(final D data) {
197         final NormalizedNodeResult result = new NormalizedNodeResult();
198         // We create DOM stream writer which produces normalized nodes
199         final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
200         writeAsNormalizedNode(data, domWriter);
201         return result.getResult();
202     }
203
204     @Override
205     public void writeAsNormalizedNode(final D data, final NormalizedNodeStreamWriter writer) {
206         try {
207             eventStreamSerializer().serialize(data, createWriter(writer));
208         } catch (final IOException e) {
209             throw new IllegalStateException("Failed to serialize Binding DTO",e);
210         }
211     }
212
213 }