Fix findbugs violations in restconf-nb-rfc8040
[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 com.google.common.base.Preconditions;
11 import com.google.common.collect.Iterables;
12 import java.net.URI;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.List;
17 import java.util.Map;
18 import java.util.Map.Entry;
19 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
20 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
21 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
22 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
23 import org.opendaylight.restconf.common.util.RestUtil;
24 import org.opendaylight.yangtools.concepts.Codec;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
31 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
32 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
33 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
34 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
35 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
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.api.LeafListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.Module;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 public final class RestCodec {
54
55     private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
56
57     private RestCodec() {
58     }
59
60     public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
61             final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
62         return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
63     }
64
65     @SuppressWarnings("rawtypes")
66     public static final class ObjectCodec implements Codec<Object, Object> {
67
68         private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
69
70         public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
71         private final Codec instanceIdentifier;
72         private final Codec identityrefCodec;
73
74         private final TypeDefinition<?> type;
75
76         private final SchemaContext schemaContext;
77
78         private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
79                 final SchemaContext schemaContext) {
80             this.schemaContext = schemaContext;
81             this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
82             if (this.type instanceof IdentityrefTypeDefinition) {
83                 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
84             } else {
85                 this.identityrefCodec = null;
86             }
87             if (this.type instanceof InstanceIdentifierTypeDefinition) {
88                 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
89             } else {
90                 this.instanceIdentifier = null;
91             }
92         }
93
94         @SuppressWarnings("unchecked")
95         @Override
96         public Object deserialize(final Object input) {
97             try {
98                 if (this.type instanceof IdentityrefTypeDefinition) {
99                     if (input instanceof IdentityValuesDTO) {
100                         return this.identityrefCodec.deserialize(input);
101                     }
102                     if (LOG.isDebugEnabled()) {
103                         LOG.debug(
104                             "Value is not instance of IdentityrefTypeDefinition but is {}. "
105                                     + "Therefore NULL is used as translation of  - {}",
106                             input == null ? "null" : input.getClass(), String.valueOf(input));
107                     }
108                     return null;
109                 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
110                     if (input instanceof IdentityValuesDTO) {
111                         return this.instanceIdentifier.deserialize(input);
112                     } else {
113                         final StringModuleInstanceIdentifierCodec codec =
114                                 new StringModuleInstanceIdentifierCodec(schemaContext);
115                         return codec.deserialize((String) input);
116                     }
117                 } else {
118                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
119                             TypeDefinitionAwareCodec.from(this.type);
120                     if (typeAwarecodec != null) {
121                         if (input instanceof IdentityValuesDTO) {
122                             return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
123                         }
124                         return typeAwarecodec.deserialize(String.valueOf(input));
125                     } else {
126                         LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
127                                 + "\" is not implemented yet.");
128                         return null;
129                     }
130                 }
131             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
132                 LOG.error(
133                         "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
134                         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 \"" + this.type.getQName().getLocalName()
157                                 + "\" is not implemented yet.");
158                         }
159                         return null;
160                     }
161                 }
162             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
163                 LOG.error(
164                         "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
165                         e);
166                 return input;
167             }
168         }
169
170     }
171
172     public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
173
174         private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
175
176         private final DOMMountPoint mountPoint;
177
178         private final SchemaContext schemaContext;
179
180         public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
181             this.mountPoint = mountPoint;
182             this.schemaContext = schemaContext;
183         }
184
185         @Override
186         public IdentityValuesDTO serialize(final QName data) {
187             return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
188         }
189
190         @Override
191         public QName deserialize(final IdentityValuesDTO data) {
192             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
193             final Module module =
194                     getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
195             if (module == null) {
196                 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
197                 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
198                 return null;
199             }
200
201             return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
202         }
203
204     }
205
206     public static class LeafrefCodecImpl implements LeafrefCodec<String> {
207
208         @Override
209         public String serialize(final Object data) {
210             return String.valueOf(data);
211         }
212
213         @Override
214         public Object deserialize(final String data) {
215             return data;
216         }
217
218     }
219
220     public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
221         private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
222         private final DOMMountPoint mountPoint;
223         private final SchemaContext schemaContext;
224
225         public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
226             this.mountPoint = mountPoint;
227             this.schemaContext = schemaContext;
228         }
229
230         @Override
231         public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
232             final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
233             for (final PathArgument pathArgument : data.getPathArguments()) {
234                 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
235                 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
236                     final List<Predicate> predicates =
237                             keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).getKeyValues());
238                     identityValue.setPredicates(predicates);
239                 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
240                     final List<Predicate> predicates = new ArrayList<>();
241                     final String value = String.valueOf(((NodeWithValue) pathArgument).getValue());
242                     predicates.add(new Predicate(null, value));
243                     identityValue.setPredicates(predicates);
244                 }
245                 identityValuesDTO.add(identityValue);
246             }
247             return identityValuesDTO;
248         }
249
250         @Override
251         public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
252             final List<PathArgument> result = new ArrayList<>();
253             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
254             final Module module =
255                     getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
256             if (module == null) {
257                 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
258                         valueWithNamespace.getNamespace());
259                 LOG.info("Instance-identifier will be translated as NULL for data - {}",
260                         String.valueOf(valueWithNamespace.getValue()));
261                 return null;
262             }
263
264             DataNodeContainer parentContainer = module;
265             final List<IdentityValue> identities = data.getValuesWithNamespaces();
266             for (int i = 0; i < identities.size(); i++) {
267                 final IdentityValue identityValue = identities.get(i);
268                 URI validNamespace =
269                         resolveValidNamespace(identityValue.getNamespace(), this.mountPoint, schemaContext);
270                 final DataSchemaNode node = findInstanceDataChildByNameAndNamespace(
271                         parentContainer, identityValue.getValue(), validNamespace);
272                 if (node == null) {
273                     LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
274                     LOG.info("Instance-identifier will be translated as NULL for data - {}",
275                             String.valueOf(identityValue.getValue()));
276                     return null;
277                 }
278                 final QName qName = node.getQName();
279                 PathArgument pathArgument = null;
280                 if (identityValue.getPredicates().isEmpty()) {
281                     pathArgument = new NodeIdentifier(qName);
282                 } else {
283                     if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
284                         final Predicate leafListPredicate = identityValue.getPredicates().get(0);
285                         if (!leafListPredicate.isLeafList()) {
286                             LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
287                             LOG.info("Instance-identifier will be translated as NULL for data - {}",
288                                     String.valueOf(identityValue.getValue()));
289                             return null;
290                         }
291                         pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
292                     } else if (node instanceof ListSchemaNode) { // predicates are keys of list
293                         final DataNodeContainer listNode = (DataNodeContainer) node;
294                         final Map<QName, Object> predicatesMap = new HashMap<>();
295                         for (final Predicate predicate : identityValue.getPredicates()) {
296                             validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
297                                     schemaContext);
298                             final DataSchemaNode listKey = findInstanceDataChildByNameAndNamespace(listNode,
299                                     predicate.getName().getValue(), validNamespace);
300                             predicatesMap.put(listKey.getQName(), predicate.getValue());
301                         }
302                         pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
303                     } else {
304                         LOG.info("Node {} is not List or Leaf-list.", node);
305                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
306                                 String.valueOf(identityValue.getValue()));
307                         return null;
308                     }
309                 }
310                 result.add(pathArgument);
311                 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
312                     // DataNodeContainer
313                     if (node instanceof DataNodeContainer) {
314                         parentContainer = (DataNodeContainer) node;
315                     } else {
316                         LOG.info("Node {} isn't instance of DataNodeContainer", node);
317                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
318                                 String.valueOf(identityValue.getValue()));
319                         return null;
320                     }
321                 }
322             }
323
324             return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
325         }
326
327         private static List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
328             final List<Predicate> result = new ArrayList<>();
329             for (final Entry<QName, Object> entry : keyValues.entrySet()) {
330                 final QName qualifiedName = entry.getKey();
331                 final Object value = entry.getValue();
332                 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
333             }
334             return result;
335         }
336
337         private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
338             if (qualifiedName != null) {
339                 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
340             }
341             return null;
342         }
343     }
344
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 " + validNamespace + " wasn't found.");
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     private static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
386             final String name, final URI namespace) {
387         Preconditions.checkNotNull(namespace);
388
389         final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
390             node -> namespace.equals(node.getQName().getNamespace()));
391         return Iterables.getFirst(result, null);
392     }
393
394     private static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
395             final String name) {
396         Preconditions.checkNotNull(container);
397         Preconditions.checkNotNull(name);
398
399         final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
400         collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, 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 }