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