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