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