Bump versions to 4.0.0-SNAPSHOT
[netconf.git] / restconf / restconf-nb-bierman02 / src / main / java / org / opendaylight / netconf / sal / restconf / impl / 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.netconf.sal.restconf.impl;
9
10 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
11 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Map.Entry;
16 import java.util.Set;
17 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
18 import org.opendaylight.netconf.sal.rest.impl.StringModuleInstanceIdentifierCodec;
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.IllegalArgumentCodec;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.common.XMLNamespace;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
31 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
32 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
33 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
34 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
35 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.Module;
40 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 public final class RestCodec {
48
49     private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
50
51     private RestCodec() {
52     }
53
54     // FIXME: IllegalArgumentCodec is not quite accurate
55     public static IllegalArgumentCodec<Object, Object> from(final TypeDefinition<?> typeDefinition,
56             final DOMMountPoint mountPoint, final ControllerContext controllerContext) {
57         return new ObjectCodec(typeDefinition, mountPoint, controllerContext);
58     }
59
60     @SuppressWarnings("rawtypes")
61     public static final class ObjectCodec implements IllegalArgumentCodec<Object, Object> {
62
63         private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
64
65         public static final IllegalArgumentCodec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
66
67         private final ControllerContext controllerContext;
68         private final IllegalArgumentCodec instanceIdentifier;
69         private final IllegalArgumentCodec identityrefCodec;
70
71         private final TypeDefinition<?> type;
72
73         private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
74                 final ControllerContext controllerContext) {
75             this.controllerContext = controllerContext;
76             type = RestUtil.resolveBaseTypeFrom(typeDefinition);
77             if (type instanceof IdentityrefTypeDefinition) {
78                 identityrefCodec = new IdentityrefCodecImpl(mountPoint, controllerContext);
79             } else {
80                 identityrefCodec = null;
81             }
82             if (type instanceof InstanceIdentifierTypeDefinition) {
83                 instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, controllerContext);
84             } else {
85                 instanceIdentifier = null;
86             }
87         }
88
89         @SuppressWarnings("unchecked")
90         @Override
91         @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "Legacy code")
92         public Object deserialize(final Object input) {
93             try {
94                 if (type instanceof IdentityrefTypeDefinition) {
95                     if (input instanceof IdentityValuesDTO) {
96                         return identityrefCodec.deserialize(input);
97                     }
98                     if (LOG.isDebugEnabled()) {
99                         LOG.debug(
100                             "Value is not instance of IdentityrefTypeDefinition but is {}. "
101                                     + "Therefore NULL is used as translation of  - {}",
102                             input == null ? "null" : input.getClass(), String.valueOf(input));
103                     }
104                     // FIXME: this should be a hard error
105                     return null;
106                 } else if (type instanceof InstanceIdentifierTypeDefinition) {
107                     if (input instanceof IdentityValuesDTO) {
108                         return instanceIdentifier.deserialize(input);
109                     } else {
110                         final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
111                                 controllerContext.getGlobalSchema());
112                         return codec.deserialize((String) input);
113                     }
114                 } else {
115                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
116                             TypeDefinitionAwareCodec.from(type);
117                     if (typeAwarecodec != null) {
118                         if (input instanceof IdentityValuesDTO) {
119                             return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
120                         }
121                         return typeAwarecodec.deserialize(String.valueOf(input));
122                     } else {
123                         LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
124                         // FIXME: this should be a hard error
125                         return null;
126                     }
127                 }
128             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
129                 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
130                 // FIXME: this should be a hard error
131                 return null;
132             }
133         }
134
135         @SuppressWarnings("unchecked")
136         @Override
137         @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "legacy code")
138         public Object serialize(final Object input) {
139             try {
140                 if (type instanceof IdentityrefTypeDefinition) {
141                     return identityrefCodec.serialize(input);
142                 } else if (type instanceof LeafrefTypeDefinition) {
143                     return LEAFREF_DEFAULT_CODEC.serialize(input);
144                 } else if (type instanceof InstanceIdentifierTypeDefinition) {
145                     return instanceIdentifier.serialize(input);
146                 } else {
147                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
148                             TypeDefinitionAwareCodec.from(type);
149                     if (typeAwarecodec != null) {
150                         return typeAwarecodec.serialize(input);
151                     } else {
152                         LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
153                         return null;
154                     }
155                 }
156             } catch (final ClassCastException e) {
157                 // FIXME: remove this catch when everyone use codecs
158                 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
159                 // FIXME: this should be a hard error
160                 return input;
161             }
162         }
163
164     }
165
166     public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
167         private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
168
169         private final DOMMountPoint mountPoint;
170         private final ControllerContext controllerContext;
171
172         public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final ControllerContext controllerContext) {
173             this.mountPoint = mountPoint;
174             this.controllerContext = controllerContext;
175         }
176
177         @Override
178         public IdentityValuesDTO serialize(final QName data) {
179             return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
180         }
181
182         @Override
183         @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "See FIXME below")
184         public QName deserialize(final IdentityValuesDTO data) {
185             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
186             final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint,
187                     controllerContext);
188             if (module == null) {
189                 // FIXME: this should be a hard error
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     public static class LeafrefCodecImpl implements LeafrefCodec<String> {
200
201         @Override
202         public String serialize(final Object data) {
203             return String.valueOf(data);
204         }
205
206         @Override
207         public Object deserialize(final String data) {
208             return data;
209         }
210
211     }
212
213     public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
214         private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
215
216         private final DOMMountPoint mountPoint;
217         private final ControllerContext controllerContext;
218
219         public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint,
220                 final ControllerContext controllerContext) {
221             this.mountPoint = mountPoint;
222             this.controllerContext = controllerContext;
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 = { "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", "NP_NONNULL_RETURN_VIOLATION" },
246                 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 = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint,
252                     controllerContext);
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                 // FIXME: this should be a hard error
259                 return null;
260             }
261
262             DataNodeContainer parentContainer = module;
263             final List<IdentityValue> identities = data.getValuesWithNamespaces();
264             for (int i = 0; i < identities.size(); i++) {
265                 final IdentityValue identityValue = identities.get(i);
266                 XMLNamespace validNamespace = resolveValidNamespace(identityValue.getNamespace(), mountPoint,
267                         controllerContext);
268                 final var found = ControllerContext.findInstanceDataChildByNameAndNamespace(
269                     parentContainer, identityValue.getValue(), validNamespace);
270                 if (found == null) {
271                     LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
272                     LOG.info("Instance-identifier will be translated as NULL for data - {}",
273                             String.valueOf(identityValue.getValue()));
274                     // FIXME: this should be a hard error
275                     return null;
276                 }
277                 final DataSchemaNode node = found.child;
278                 final QName qName = node.getQName();
279                 PathArgument pathArgument = null;
280                 if (identityValue.getPredicates().isEmpty()) {
281                     pathArgument = new NodeIdentifier(qName);
282                 } else {
283                     if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
284                         final Predicate leafListPredicate = identityValue.getPredicates().get(0);
285                         if (!leafListPredicate.isLeafList()) {
286                             LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
287                             LOG.info("Instance-identifier will be translated as NULL for data - {}",
288                                     String.valueOf(identityValue.getValue()));
289                             // FIXME: this should be a hard error
290                             return null;
291                         }
292                         pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
293                     } else if (node instanceof ListSchemaNode) { // predicates are keys of list
294                         final DataNodeContainer listNode = (DataNodeContainer) node;
295                         final Map<QName, Object> predicatesMap = new HashMap<>();
296                         for (final Predicate predicate : identityValue.getPredicates()) {
297                             validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint,
298                                     controllerContext);
299                             final var listKey = ControllerContext
300                                     .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
301                                             validNamespace);
302                             predicatesMap.put(listKey.child.getQName(), predicate.getValue());
303                         }
304                         pathArgument = NodeIdentifierWithPredicates.of(qName, predicatesMap);
305                     } else {
306                         LOG.info("Node {} is not List or Leaf-list.", node);
307                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
308                                 String.valueOf(identityValue.getValue()));
309                         // FIXME: this should be a hard error
310                         return null;
311                     }
312                 }
313                 result.add(pathArgument);
314                 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
315                     // DataNodeContainer
316                     if (node instanceof DataNodeContainer) {
317                         parentContainer = (DataNodeContainer) node;
318                     } else {
319                         LOG.info("Node {} isn't instance of DataNodeContainer", node);
320                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
321                                 String.valueOf(identityValue.getValue()));
322                         // FIXME: this should be a hard error
323                         return null;
324                     }
325                 }
326             }
327
328             return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
329         }
330
331         private static List<Predicate> keyValuesToPredicateList(final Set<Entry<QName, Object>> keyValues) {
332             final List<Predicate> result = new ArrayList<>();
333             for (final Entry<QName, Object> entry : keyValues) {
334                 final QName qualifiedName = entry.getKey();
335                 final Object value = entry.getValue();
336                 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
337             }
338             return result;
339         }
340
341         private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
342             if (qualifiedName != null) {
343                 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
344             }
345             return null;
346         }
347     }
348
349     private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
350             final ControllerContext controllerContext) {
351         final XMLNamespace validNamespace = resolveValidNamespace(namespace, mountPoint, controllerContext);
352
353         Module module = null;
354         if (mountPoint != null) {
355             module = ControllerContext.findModuleByNamespace(mountPoint, validNamespace);
356         } else {
357             module = controllerContext.findModuleByNamespace(validNamespace);
358         }
359         if (module == null) {
360             LOG.info("Module for namespace {} was not found.", validNamespace);
361             return null;
362         }
363         return module;
364     }
365
366     private static XMLNamespace resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
367             final ControllerContext controllerContext) {
368         XMLNamespace validNamespace;
369         if (mountPoint != null) {
370             validNamespace = ControllerContext.findNamespaceByModuleName(mountPoint, namespace);
371         } else {
372             validNamespace = controllerContext.findNamespaceByModuleName(namespace);
373         }
374         if (validNamespace == null) {
375             validNamespace = XMLNamespace.of(namespace);
376         }
377
378         return validNamespace;
379     }
380 }