Bump odlparent to 6.0.0
[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.net.URI;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.List;
15 import java.util.Map;
16 import java.util.Map.Entry;
17 import java.util.Set;
18 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
19 import org.opendaylight.netconf.sal.rest.impl.StringModuleInstanceIdentifierCodec;
20 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
21 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
22 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
23 import org.opendaylight.restconf.common.util.RestUtil;
24 import org.opendaylight.yangtools.concepts.Codec;
25 import org.opendaylight.yangtools.yang.common.QName;
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     public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
55             final DOMMountPoint mountPoint, final ControllerContext controllerContext) {
56         return new ObjectCodec(typeDefinition, mountPoint, controllerContext);
57     }
58
59     @SuppressWarnings("rawtypes")
60     public static final class ObjectCodec implements Codec<Object, Object> {
61
62         private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
63
64         public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
65
66         private final ControllerContext controllerContext;
67         private final Codec instanceIdentifier;
68         private final Codec identityrefCodec;
69
70         private final TypeDefinition<?> type;
71
72         private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
73                 final ControllerContext controllerContext) {
74             this.controllerContext = controllerContext;
75             this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
76             if (this.type instanceof IdentityrefTypeDefinition) {
77                 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, controllerContext);
78             } else {
79                 this.identityrefCodec = null;
80             }
81             if (this.type instanceof InstanceIdentifierTypeDefinition) {
82                 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, controllerContext);
83             } else {
84                 this.instanceIdentifier = null;
85             }
86         }
87
88         @SuppressWarnings("unchecked")
89         @Override
90         public Object deserialize(final Object input) {
91             try {
92                 if (this.type instanceof IdentityrefTypeDefinition) {
93                     if (input instanceof IdentityValuesDTO) {
94                         return this.identityrefCodec.deserialize(input);
95                     }
96                     if (LOG.isDebugEnabled()) {
97                         LOG.debug(
98                             "Value is not instance of IdentityrefTypeDefinition but is {}. "
99                                     + "Therefore NULL is used as translation of  - {}",
100                             input == null ? "null" : input.getClass(), String.valueOf(input));
101                     }
102                     return null;
103                 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
104                     if (input instanceof IdentityValuesDTO) {
105                         return this.instanceIdentifier.deserialize(input);
106                     } else {
107                         final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
108                                 controllerContext.getGlobalSchema());
109                         return codec.deserialize((String) input);
110                     }
111                 } else {
112                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
113                             TypeDefinitionAwareCodec.from(this.type);
114                     if (typeAwarecodec != null) {
115                         if (input instanceof IdentityValuesDTO) {
116                             return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
117                         }
118                         return typeAwarecodec.deserialize(String.valueOf(input));
119                     } else {
120                         LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
121                         return null;
122                     }
123                 }
124             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
125                 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
126                 return null;
127             }
128         }
129
130         @SuppressWarnings("unchecked")
131         @Override
132         public Object serialize(final Object input) {
133             try {
134                 if (this.type instanceof IdentityrefTypeDefinition) {
135                     return this.identityrefCodec.serialize(input);
136                 } else if (this.type instanceof LeafrefTypeDefinition) {
137                     return LEAFREF_DEFAULT_CODEC.serialize(input);
138                 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
139                     return this.instanceIdentifier.serialize(input);
140                 } else {
141                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
142                             TypeDefinitionAwareCodec.from(this.type);
143                     if (typeAwarecodec != null) {
144                         return typeAwarecodec.serialize(input);
145                     } else {
146                         LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
147                         return null;
148                     }
149                 }
150             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
151                 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
152                 return input;
153             }
154         }
155
156     }
157
158     public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
159
160         private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
161
162         private final DOMMountPoint mountPoint;
163         private final ControllerContext controllerContext;
164
165         public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final ControllerContext controllerContext) {
166             this.mountPoint = mountPoint;
167             this.controllerContext = controllerContext;
168         }
169
170         @Override
171         public IdentityValuesDTO serialize(final QName data) {
172             return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
173         }
174
175         @Override
176         public QName deserialize(final IdentityValuesDTO data) {
177             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
178             final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint,
179                     controllerContext);
180             if (module == null) {
181                 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
182                 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
183                 return null;
184             }
185
186             return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
187         }
188
189     }
190
191     public static class LeafrefCodecImpl implements LeafrefCodec<String> {
192
193         @Override
194         public String serialize(final Object data) {
195             return String.valueOf(data);
196         }
197
198         @Override
199         public Object deserialize(final String data) {
200             return data;
201         }
202
203     }
204
205     public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
206         private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
207
208         private final DOMMountPoint mountPoint;
209         private final ControllerContext controllerContext;
210
211         public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint,
212                 final ControllerContext controllerContext) {
213             this.mountPoint = mountPoint;
214             this.controllerContext = controllerContext;
215         }
216
217         @Override
218         public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
219             final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
220             for (final PathArgument pathArgument : data.getPathArguments()) {
221                 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
222                 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
223                     final List<Predicate> predicates =
224                             keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).entrySet());
225                     identityValue.setPredicates(predicates);
226                 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
227                     final List<Predicate> predicates = new ArrayList<>();
228                     final String value = String.valueOf(((NodeWithValue<?>) pathArgument).getValue());
229                     predicates.add(new Predicate(null, value));
230                     identityValue.setPredicates(predicates);
231                 }
232                 identityValuesDTO.add(identityValue);
233             }
234             return identityValuesDTO;
235         }
236
237         @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE",
238                 justification = "Unrecognised NullableDecl")
239         @Override
240         public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
241             final List<PathArgument> result = new ArrayList<>();
242             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
243             final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint,
244                     controllerContext);
245             if (module == null) {
246                 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
247                         valueWithNamespace.getNamespace());
248                 LOG.info("Instance-identifier will be translated as NULL for data - {}",
249                         String.valueOf(valueWithNamespace.getValue()));
250                 return null;
251             }
252
253             DataNodeContainer parentContainer = module;
254             final List<IdentityValue> identities = data.getValuesWithNamespaces();
255             for (int i = 0; i < identities.size(); i++) {
256                 final IdentityValue identityValue = identities.get(i);
257                 URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), this.mountPoint,
258                         controllerContext);
259                 final DataSchemaNode node = ControllerContext.findInstanceDataChildByNameAndNamespace(
260                         parentContainer, identityValue.getValue(), validNamespace);
261                 if (node == null) {
262                     LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
263                     LOG.info("Instance-identifier will be translated as NULL for data - {}",
264                             String.valueOf(identityValue.getValue()));
265                     return null;
266                 }
267                 final QName qName = node.getQName();
268                 PathArgument pathArgument = null;
269                 if (identityValue.getPredicates().isEmpty()) {
270                     pathArgument = new NodeIdentifier(qName);
271                 } else {
272                     if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
273                         final Predicate leafListPredicate = identityValue.getPredicates().get(0);
274                         if (!leafListPredicate.isLeafList()) {
275                             LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
276                             LOG.info("Instance-identifier will be translated as NULL for data - {}",
277                                     String.valueOf(identityValue.getValue()));
278                             return null;
279                         }
280                         pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
281                     } else if (node instanceof ListSchemaNode) { // predicates are keys of list
282                         final DataNodeContainer listNode = (DataNodeContainer) node;
283                         final Map<QName, Object> predicatesMap = new HashMap<>();
284                         for (final Predicate predicate : identityValue.getPredicates()) {
285                             validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
286                                     controllerContext);
287                             final DataSchemaNode listKey = ControllerContext
288                                     .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
289                                             validNamespace);
290                             predicatesMap.put(listKey.getQName(), predicate.getValue());
291                         }
292                         pathArgument = NodeIdentifierWithPredicates.of(qName, predicatesMap);
293                     } else {
294                         LOG.info("Node {} is not List or Leaf-list.", node);
295                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
296                                 String.valueOf(identityValue.getValue()));
297                         return null;
298                     }
299                 }
300                 result.add(pathArgument);
301                 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
302                     // DataNodeContainer
303                     if (node instanceof DataNodeContainer) {
304                         parentContainer = (DataNodeContainer) node;
305                     } else {
306                         LOG.info("Node {} isn't instance of DataNodeContainer", node);
307                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
308                                 String.valueOf(identityValue.getValue()));
309                         return null;
310                     }
311                 }
312             }
313
314             return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
315         }
316
317         private static List<Predicate> keyValuesToPredicateList(final Set<Entry<QName, Object>> keyValues) {
318             final List<Predicate> result = new ArrayList<>();
319             for (final Entry<QName, Object> entry : keyValues) {
320                 final QName qualifiedName = entry.getKey();
321                 final Object value = entry.getValue();
322                 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
323             }
324             return result;
325         }
326
327         private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
328             if (qualifiedName != null) {
329                 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
330             }
331             return null;
332         }
333     }
334
335     @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
336             justification = "https://github.com/spotbugs/spotbugs/issues/811")
337     private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
338             final ControllerContext controllerContext) {
339         final URI validNamespace = resolveValidNamespace(namespace, mountPoint, controllerContext);
340
341         Module module = null;
342         if (mountPoint != null) {
343             module = controllerContext.findModuleByNamespace(mountPoint, validNamespace);
344         } else {
345             module = controllerContext.findModuleByNamespace(validNamespace);
346         }
347         if (module == null) {
348             LOG.info("Module for namespace {} was not found.", validNamespace);
349             return null;
350         }
351         return module;
352     }
353
354     private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
355             final ControllerContext controllerContext) {
356         URI validNamespace;
357         if (mountPoint != null) {
358             validNamespace = controllerContext.findNamespaceByModuleName(mountPoint, namespace);
359         } else {
360             validNamespace = controllerContext.findNamespaceByModuleName(namespace);
361         }
362         if (validNamespace == null) {
363             validNamespace = URI.create(namespace);
364         }
365
366         return validNamespace;
367     }
368
369 }