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