Update MRI projects for Aluminium
[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.Set;
22 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
23 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
24 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
25 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
26 import org.opendaylight.restconf.common.util.RestUtil;
27 import org.opendaylight.yangtools.concepts.IllegalArgumentCodec;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
35 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
36 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
37 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
38 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.Module;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 public final class RestCodec {
57
58     private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
59
60     private RestCodec() {
61     }
62
63     // FIXME: IllegalArgumentCodec is not quite accurate
64     public static IllegalArgumentCodec<Object, Object> from(final TypeDefinition<?> typeDefinition,
65             final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
66         return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
67     }
68
69     @SuppressWarnings("rawtypes")
70     public static final class ObjectCodec implements IllegalArgumentCodec<Object, Object> {
71
72         private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
73
74         public static final IllegalArgumentCodec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
75         private final IllegalArgumentCodec instanceIdentifier;
76         private final IllegalArgumentCodec identityrefCodec;
77
78         private final TypeDefinition<?> type;
79
80         private final SchemaContext schemaContext;
81
82         private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
83                 final SchemaContext schemaContext) {
84             this.schemaContext = schemaContext;
85             this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
86             if (this.type instanceof IdentityrefTypeDefinition) {
87                 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
88             } else {
89                 this.identityrefCodec = null;
90             }
91             if (this.type instanceof InstanceIdentifierTypeDefinition) {
92                 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
93             } else {
94                 this.instanceIdentifier = null;
95             }
96         }
97
98         @SuppressWarnings("unchecked")
99         @Override
100         public Object deserialize(final Object input) {
101             try {
102                 if (this.type instanceof IdentityrefTypeDefinition) {
103                     if (input instanceof IdentityValuesDTO) {
104                         return this.identityrefCodec.deserialize(input);
105                     }
106                     if (LOG.isDebugEnabled()) {
107                         LOG.debug(
108                             "Value is not instance of IdentityrefTypeDefinition but is {}. "
109                                     + "Therefore NULL is used as translation of - {}",
110                             input == null ? "null" : input.getClass(), String.valueOf(input));
111                     }
112                     return null;
113                 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
114                     if (input instanceof IdentityValuesDTO) {
115                         return this.instanceIdentifier.deserialize(input);
116                     } else {
117                         final StringModuleInstanceIdentifierCodec codec =
118                                 new StringModuleInstanceIdentifierCodec(schemaContext);
119                         return codec.deserialize((String) input);
120                     }
121                 } else {
122                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
123                             TypeDefinitionAwareCodec.from(this.type);
124                     if (typeAwarecodec != null) {
125                         if (input instanceof IdentityValuesDTO) {
126                             return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
127                         }
128                         return typeAwarecodec.deserialize(String.valueOf(input));
129                     } else {
130                         LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
131                         return null;
132                     }
133                 }
134             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
135                 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
136                 return null;
137             }
138         }
139
140         @SuppressWarnings("unchecked")
141         @Override
142         public Object serialize(final Object input) {
143             try {
144                 if (this.type instanceof IdentityrefTypeDefinition) {
145                     return this.identityrefCodec.serialize(input);
146                 } else if (this.type instanceof LeafrefTypeDefinition) {
147                     return LEAFREF_DEFAULT_CODEC.serialize(input);
148                 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
149                     return this.instanceIdentifier.serialize(input);
150                 } else {
151                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
152                             TypeDefinitionAwareCodec.from(this.type);
153                     if (typeAwarecodec != null) {
154                         return typeAwarecodec.serialize(input);
155                     } else {
156                         if (LOG.isDebugEnabled()) {
157                             LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
158                         }
159                         return null;
160                     }
161                 }
162             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
163                 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
164                 return input;
165             }
166         }
167     }
168
169     public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
170
171         private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
172
173         private final DOMMountPoint mountPoint;
174
175         private final SchemaContext schemaContext;
176
177         public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
178             this.mountPoint = mountPoint;
179             this.schemaContext = schemaContext;
180         }
181
182         @Override
183         public IdentityValuesDTO serialize(final QName data) {
184             return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
185         }
186
187         @Override
188         public QName deserialize(final IdentityValuesDTO data) {
189             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
190             final Module module =
191                     getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
192             if (module == null) {
193                 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
194                 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
195                 return null;
196             }
197
198             return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
199         }
200
201     }
202
203     public static class LeafrefCodecImpl implements LeafrefCodec<String> {
204
205         @Override
206         public String serialize(final Object data) {
207             return String.valueOf(data);
208         }
209
210         @Override
211         public Object deserialize(final String data) {
212             return data;
213         }
214
215     }
216
217     public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
218         private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
219         private final DOMMountPoint mountPoint;
220         private final SchemaContext schemaContext;
221
222         public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
223             this.mountPoint = mountPoint;
224             this.schemaContext = schemaContext;
225         }
226
227         @Override
228         public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
229             final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
230             for (final PathArgument pathArgument : data.getPathArguments()) {
231                 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
232                 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
233                     final List<Predicate> predicates =
234                             keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).entrySet());
235                     identityValue.setPredicates(predicates);
236                 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
237                     final List<Predicate> predicates = new ArrayList<>();
238                     final String value = String.valueOf(((NodeWithValue<?>) pathArgument).getValue());
239                     predicates.add(new Predicate(null, value));
240                     identityValue.setPredicates(predicates);
241                 }
242                 identityValuesDTO.add(identityValue);
243             }
244             return identityValuesDTO;
245         }
246
247         @SuppressFBWarnings(value = {"NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
248                 "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE"}, justification = "Unrecognised NullableDecl")
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 = NodeIdentifierWithPredicates.of(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 Set<Entry<QName, Object>> keyValues) {
327             final List<Predicate> result = new ArrayList<>();
328             for (final Entry<QName, Object> entry : keyValues) {
329                 final QName qualifiedName = entry.getKey();
330                 final Object value = entry.getValue();
331                 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
332             }
333             return result;
334         }
335
336         private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
337             if (qualifiedName != null) {
338                 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
339             }
340             return null;
341         }
342     }
343
344     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
345             justification = "https://github.com/spotbugs/spotbugs/issues/811")
346     private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
347             final SchemaContext schemaContext) {
348         final URI validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext);
349         Module module = null;
350         if (mountPoint != null) {
351             module = mountPoint.getSchemaContext().findModules(validNamespace).iterator().next();
352         } else {
353             module = schemaContext.findModules(validNamespace).iterator().next();
354         }
355         if (module == null) {
356             LOG.info("Module for namespace {} was not found.", validNamespace);
357             return null;
358         }
359         return module;
360     }
361
362     private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
363             final SchemaContext schemaContext) {
364         URI validNamespace;
365         if (mountPoint != null) {
366             validNamespace = findFirstModuleByName(mountPoint.getSchemaContext(), namespace);
367         } else {
368             validNamespace = findFirstModuleByName(schemaContext, namespace);
369         }
370         if (validNamespace == null) {
371             validNamespace = URI.create(namespace);
372         }
373
374         return validNamespace;
375     }
376
377     private static URI findFirstModuleByName(final SchemaContext schemaContext, final String name) {
378         for (final Module module : schemaContext.getModules()) {
379             if (module.getName().equals(name)) {
380                 return module.getNamespace();
381             }
382         }
383         return null;
384     }
385
386     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
387             justification = "https://github.com/spotbugs/spotbugs/issues/811")
388     private static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
389             final String name, final URI namespace) {
390         requireNonNull(namespace);
391
392         final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
393             node -> namespace.equals(node.getQName().getNamespace()));
394         return Iterables.getFirst(result, null);
395     }
396
397     private static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
398             final String name) {
399         final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
400         collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
401             requireNonNull(name));
402         return instantiatedDataNodeContainers;
403     }
404
405     private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
406             final DataNodeContainer container, final String name) {
407
408         final Iterable<? extends DataSchemaNode> nodes =
409                 Iterables.filter(container.getChildNodes(), node -> name.equals(node.getQName().getLocalName()));
410
411         // Can't combine this loop with the filter above because the filter is
412         // lazily-applied by Iterables.filter.
413         for (final DataSchemaNode potentialNode : nodes) {
414             if (isInstantiatedDataSchema(potentialNode)) {
415                 potentialSchemaNodes.add(potentialNode);
416             }
417         }
418
419         final Iterable<ChoiceSchemaNode> choiceNodes =
420                 Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
421         final Iterable<Collection<? extends CaseSchemaNode>> map = Iterables.transform(choiceNodes,
422             choice -> choice.getCases());
423         for (final CaseSchemaNode caze : Iterables.concat(map)) {
424             collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
425         }
426     }
427
428     private static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
429         return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
430                 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
431                 || node instanceof AnyxmlSchemaNode;
432     }
433 }