Convert to using requireNonNull()
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / codecs / RestCodec.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.restconf.nb.rfc8040.codecs;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.Iterables;
13 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.net.URI;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Map.Entry;
21 import java.util.Set;
22 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
23 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
24 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
25 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
26 import org.opendaylight.restconf.common.util.RestUtil;
27 import org.opendaylight.yangtools.concepts.Codec;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
35 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
36 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
37 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
38 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.Module;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 public final class RestCodec {
57
58     private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
59
60     private RestCodec() {
61     }
62
63     public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
64             final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
65         return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
66     }
67
68     @SuppressWarnings("rawtypes")
69     public static final class ObjectCodec implements Codec<Object, Object> {
70
71         private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
72
73         public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
74         private final Codec instanceIdentifier;
75         private final Codec identityrefCodec;
76
77         private final TypeDefinition<?> type;
78
79         private final SchemaContext schemaContext;
80
81         private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
82                 final SchemaContext schemaContext) {
83             this.schemaContext = schemaContext;
84             this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
85             if (this.type instanceof IdentityrefTypeDefinition) {
86                 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
87             } else {
88                 this.identityrefCodec = null;
89             }
90             if (this.type instanceof InstanceIdentifierTypeDefinition) {
91                 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
92             } else {
93                 this.instanceIdentifier = null;
94             }
95         }
96
97         @SuppressWarnings("unchecked")
98         @Override
99         public Object deserialize(final Object input) {
100             try {
101                 if (this.type instanceof IdentityrefTypeDefinition) {
102                     if (input instanceof IdentityValuesDTO) {
103                         return this.identityrefCodec.deserialize(input);
104                     }
105                     if (LOG.isDebugEnabled()) {
106                         LOG.debug(
107                             "Value is not instance of IdentityrefTypeDefinition but is {}. "
108                                     + "Therefore NULL is used as translation of - {}",
109                             input == null ? "null" : input.getClass(), String.valueOf(input));
110                     }
111                     return null;
112                 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
113                     if (input instanceof IdentityValuesDTO) {
114                         return this.instanceIdentifier.deserialize(input);
115                     } else {
116                         final StringModuleInstanceIdentifierCodec codec =
117                                 new StringModuleInstanceIdentifierCodec(schemaContext);
118                         return codec.deserialize((String) input);
119                     }
120                 } else {
121                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
122                             TypeDefinitionAwareCodec.from(this.type);
123                     if (typeAwarecodec != null) {
124                         if (input instanceof IdentityValuesDTO) {
125                             return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
126                         }
127                         return typeAwarecodec.deserialize(String.valueOf(input));
128                     } else {
129                         LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
130                         return null;
131                     }
132                 }
133             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
134                 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
135                 return null;
136             }
137         }
138
139         @SuppressWarnings("unchecked")
140         @Override
141         public Object serialize(final Object input) {
142             try {
143                 if (this.type instanceof IdentityrefTypeDefinition) {
144                     return this.identityrefCodec.serialize(input);
145                 } else if (this.type instanceof LeafrefTypeDefinition) {
146                     return LEAFREF_DEFAULT_CODEC.serialize(input);
147                 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
148                     return this.instanceIdentifier.serialize(input);
149                 } else {
150                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
151                             TypeDefinitionAwareCodec.from(this.type);
152                     if (typeAwarecodec != null) {
153                         return typeAwarecodec.serialize(input);
154                     } else {
155                         if (LOG.isDebugEnabled()) {
156                             LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
157                         }
158                         return null;
159                     }
160                 }
161             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
162                 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
163                 return input;
164             }
165         }
166     }
167
168     public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
169
170         private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
171
172         private final DOMMountPoint mountPoint;
173
174         private final SchemaContext schemaContext;
175
176         public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
177             this.mountPoint = mountPoint;
178             this.schemaContext = schemaContext;
179         }
180
181         @Override
182         public IdentityValuesDTO serialize(final QName data) {
183             return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
184         }
185
186         @Override
187         public QName deserialize(final IdentityValuesDTO data) {
188             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
189             final Module module =
190                     getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
191             if (module == null) {
192                 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
193                 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
194                 return null;
195             }
196
197             return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
198         }
199
200     }
201
202     public static class LeafrefCodecImpl implements LeafrefCodec<String> {
203
204         @Override
205         public String serialize(final Object data) {
206             return String.valueOf(data);
207         }
208
209         @Override
210         public Object deserialize(final String data) {
211             return data;
212         }
213
214     }
215
216     public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
217         private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
218         private final DOMMountPoint mountPoint;
219         private final SchemaContext schemaContext;
220
221         public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
222             this.mountPoint = mountPoint;
223             this.schemaContext = schemaContext;
224         }
225
226         @Override
227         public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
228             final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
229             for (final PathArgument pathArgument : data.getPathArguments()) {
230                 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
231                 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
232                     final List<Predicate> predicates =
233                             keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).entrySet());
234                     identityValue.setPredicates(predicates);
235                 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
236                     final List<Predicate> predicates = new ArrayList<>();
237                     final String value = String.valueOf(((NodeWithValue<?>) pathArgument).getValue());
238                     predicates.add(new Predicate(null, value));
239                     identityValue.setPredicates(predicates);
240                 }
241                 identityValuesDTO.add(identityValue);
242             }
243             return identityValuesDTO;
244         }
245
246         @SuppressFBWarnings(value = {"NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
247                 "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE"}, justification = "Unrecognised NullableDecl")
248         @Override
249         public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
250             final List<PathArgument> result = new ArrayList<>();
251             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
252             final Module module =
253                     getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
254             if (module == null) {
255                 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
256                         valueWithNamespace.getNamespace());
257                 LOG.info("Instance-identifier will be translated as NULL for data - {}",
258                         String.valueOf(valueWithNamespace.getValue()));
259                 return null;
260             }
261
262             DataNodeContainer parentContainer = module;
263             final List<IdentityValue> identities = data.getValuesWithNamespaces();
264             for (int i = 0; i < identities.size(); i++) {
265                 final IdentityValue identityValue = identities.get(i);
266                 URI validNamespace =
267                         resolveValidNamespace(identityValue.getNamespace(), this.mountPoint, schemaContext);
268                 final DataSchemaNode node = findInstanceDataChildByNameAndNamespace(
269                         parentContainer, identityValue.getValue(), validNamespace);
270                 if (node == null) {
271                     LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
272                     LOG.info("Instance-identifier will be translated as NULL for data - {}",
273                             String.valueOf(identityValue.getValue()));
274                     return null;
275                 }
276                 final QName qName = node.getQName();
277                 PathArgument pathArgument = null;
278                 if (identityValue.getPredicates().isEmpty()) {
279                     pathArgument = new NodeIdentifier(qName);
280                 } else {
281                     if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
282                         final Predicate leafListPredicate = identityValue.getPredicates().get(0);
283                         if (!leafListPredicate.isLeafList()) {
284                             LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
285                             LOG.info("Instance-identifier will be translated as NULL for data - {}",
286                                     String.valueOf(identityValue.getValue()));
287                             return null;
288                         }
289                         pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
290                     } else if (node instanceof ListSchemaNode) { // predicates are keys of list
291                         final DataNodeContainer listNode = (DataNodeContainer) node;
292                         final Map<QName, Object> predicatesMap = new HashMap<>();
293                         for (final Predicate predicate : identityValue.getPredicates()) {
294                             validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
295                                     schemaContext);
296                             final DataSchemaNode listKey = findInstanceDataChildByNameAndNamespace(listNode,
297                                     predicate.getName().getValue(), validNamespace);
298                             predicatesMap.put(listKey.getQName(), predicate.getValue());
299                         }
300                         pathArgument = NodeIdentifierWithPredicates.of(qName, predicatesMap);
301                     } else {
302                         LOG.info("Node {} is not List or Leaf-list.", node);
303                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
304                                 String.valueOf(identityValue.getValue()));
305                         return null;
306                     }
307                 }
308                 result.add(pathArgument);
309                 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
310                     // DataNodeContainer
311                     if (node instanceof DataNodeContainer) {
312                         parentContainer = (DataNodeContainer) node;
313                     } else {
314                         LOG.info("Node {} isn't instance of DataNodeContainer", node);
315                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
316                                 String.valueOf(identityValue.getValue()));
317                         return null;
318                     }
319                 }
320             }
321
322             return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
323         }
324
325         private static List<Predicate> keyValuesToPredicateList(final Set<Entry<QName, Object>> keyValues) {
326             final List<Predicate> result = new ArrayList<>();
327             for (final Entry<QName, Object> entry : keyValues) {
328                 final QName qualifiedName = entry.getKey();
329                 final Object value = entry.getValue();
330                 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
331             }
332             return result;
333         }
334
335         private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
336             if (qualifiedName != null) {
337                 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
338             }
339             return null;
340         }
341     }
342
343     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
344             justification = "https://github.com/spotbugs/spotbugs/issues/811")
345     private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
346             final SchemaContext schemaContext) {
347         final URI validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext);
348         Module module = null;
349         if (mountPoint != null) {
350             module = mountPoint.getSchemaContext().findModules(validNamespace).iterator().next();
351         } else {
352             module = schemaContext.findModules(validNamespace).iterator().next();
353         }
354         if (module == null) {
355             LOG.info("Module for namespace {} was not found.", validNamespace);
356             return null;
357         }
358         return module;
359     }
360
361     private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
362             final SchemaContext schemaContext) {
363         URI validNamespace;
364         if (mountPoint != null) {
365             validNamespace = findFirstModuleByName(mountPoint.getSchemaContext(), namespace);
366         } else {
367             validNamespace = findFirstModuleByName(schemaContext, namespace);
368         }
369         if (validNamespace == null) {
370             validNamespace = URI.create(namespace);
371         }
372
373         return validNamespace;
374     }
375
376     private static URI findFirstModuleByName(final SchemaContext schemaContext, final String name) {
377         for (final Module module : schemaContext.getModules()) {
378             if (module.getName().equals(name)) {
379                 return module.getNamespace();
380             }
381         }
382         return null;
383     }
384
385     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
386             justification = "https://github.com/spotbugs/spotbugs/issues/811")
387     private static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
388             final String name, final URI namespace) {
389         requireNonNull(namespace);
390
391         final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
392             node -> namespace.equals(node.getQName().getNamespace()));
393         return Iterables.getFirst(result, null);
394     }
395
396     private static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
397             final String name) {
398         final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
399         collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
400             requireNonNull(name));
401         return instantiatedDataNodeContainers;
402     }
403
404     private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
405             final DataNodeContainer container, final String name) {
406
407         final Iterable<DataSchemaNode> nodes =
408                 Iterables.filter(container.getChildNodes(), node -> name.equals(node.getQName().getLocalName()));
409
410         // Can't combine this loop with the filter above because the filter is
411         // lazily-applied by Iterables.filter.
412         for (final DataSchemaNode potentialNode : nodes) {
413             if (isInstantiatedDataSchema(potentialNode)) {
414                 potentialSchemaNodes.add(potentialNode);
415             }
416         }
417
418         final Iterable<ChoiceSchemaNode> choiceNodes =
419                 Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
420         final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
421             choice -> choice.getCases().values());
422         for (final CaseSchemaNode caze : Iterables.concat(map)) {
423             collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
424         }
425     }
426
427     private static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
428         return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
429                 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
430                 || node instanceof AnyXmlSchemaNode;
431     }
432 }