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