Mass-migrate to java.util.Optional
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / 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.mdsal.binding.dom.codec.impl;
9
10 import com.google.common.collect.ImmutableCollection;
11 import com.google.common.collect.ImmutableSet;
12 import java.io.IOException;
13 import java.util.List;
14 import java.util.Optional;
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.PathArgument;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.common.QNameModule;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
27 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
28 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
29 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
30
31 abstract class DataContainerCodecContext<D extends DataObject, T extends WithStatus> 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(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     @Nullable
83     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final PathArgument arg,
84             final List<YangInstanceIdentifier.PathArgument> builder) {
85         final DataContainerCodecContext<?,?> child = streamChild(arg.getType());
86         if (child != null) {
87             if (builder != null) {
88                 child.addYangPathArgument(arg,builder);
89             }
90             return child;
91         }
92         throw new IllegalArgumentException("Supplied argument is not valid child");
93     }
94
95     /**
96      * Returns deserialized Binding Path Argument from YANG instance identifier.
97      */
98     protected PathArgument getBindingPathArgument(final YangInstanceIdentifier.PathArgument domArg) {
99         return bindingArg();
100     }
101
102     protected final PathArgument bindingArg() {
103         return prototype.getBindingArg();
104     }
105
106     @SuppressWarnings("unchecked")
107     @Override
108     public final Class<D> getBindingClass() {
109         return Class.class.cast(prototype.getBindingClass());
110     }
111
112     /**
113      * Returns child context as if it was walked by {@link BindingStreamEventWriter}. This means that to enter case, one
114      * must issue getChild(ChoiceClass).getChild(CaseClass).
115      *
116      * @param childClass child class
117      * @return Context of child node or null, if supplied class is not subtree child
118      * @throws IllegalArgumentException If supplied child class is not valid in specified context.
119      */
120     @Override
121     public abstract @Nullable <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(Class<C> childClass);
122
123     /**
124      * Returns child context as if it was walked by {@link BindingStreamEventWriter}. This means that to enter case, one
125      * must issue getChild(ChoiceClass).getChild(CaseClass).
126      *
127      * @param childClass child class
128      * @return Context of child or Optional.empty is supplied class is not applicable in context.
129      */
130     @Override
131     public abstract <C extends DataObject> Optional<DataContainerCodecContext<C,?>> possibleStreamChild(
132             Class<C> childClass);
133
134     @Override
135     public String toString() {
136         return getClass().getSimpleName() + " [" + prototype.getBindingClass() + "]";
137     }
138
139     @Override
140     public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
141             final ImmutableCollection<Class<? extends DataObject>> cacheSpecifier) {
142         if (cacheSpecifier.isEmpty()) {
143             return new NonCachingCodec<>(this);
144         }
145         return new CachingNormalizedNodeCodec<>(this,ImmutableSet.copyOf(cacheSpecifier));
146     }
147
148     BindingStreamEventWriter createWriter(final NormalizedNodeStreamWriter domWriter) {
149         return BindingToNormalizedStreamWriter.create(this, domWriter);
150     }
151
152     @Nonnull
153     protected final <V> V childNonNull(@Nullable final V nullable, final YangInstanceIdentifier.PathArgument child,
154             final String message, final Object... args) {
155         if (nullable != null) {
156             return nullable;
157         }
158         MissingSchemaException.checkModulePresent(factory().getRuntimeContext().getSchemaContext(), child);
159         throw IncorrectNestingException.create(message, args);
160     }
161
162     @Nonnull
163     protected final <V> V childNonNull(@Nullable final V nullable, final QName child, final String message,
164             final Object... args) {
165         if (nullable != null) {
166             return nullable;
167         }
168         MissingSchemaException.checkModulePresent(factory().getRuntimeContext().getSchemaContext(), child);
169         throw IncorrectNestingException.create(message, args);
170     }
171
172     @Nonnull
173     protected final <V> V childNonNull(@Nullable final V nullable, final Class<?> childClass, final String message,
174             final Object... args) {
175         if (nullable != null) {
176             return nullable;
177         }
178         MissingSchemaForClassException.check(factory().getRuntimeContext(), childClass);
179         MissingClassInLoadingStrategyException.check(factory().getRuntimeContext().getStrategy(), childClass);
180         throw IncorrectNestingException.create(message, args);
181     }
182
183     DataObjectSerializer eventStreamSerializer() {
184         if (eventStreamSerializer == null) {
185             eventStreamSerializer = factory().getEventStreamSerializer(getBindingClass());
186         }
187         return eventStreamSerializer;
188     }
189
190     @Override
191     public NormalizedNode<?, ?> serialize(final D data) {
192         final NormalizedNodeResult result = new NormalizedNodeResult();
193         // We create DOM stream writer which produces normalized nodes
194         final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
195         writeAsNormalizedNode(data, domWriter);
196         return result.getResult();
197     }
198
199     @Override
200     public void writeAsNormalizedNode(final D data, final NormalizedNodeStreamWriter writer) {
201         try {
202             eventStreamSerializer().serialize(data, createWriter(writer));
203         } catch (final IOException e) {
204             throw new IllegalStateException("Failed to serialize Binding DTO",e);
205         }
206     }
207
208 }