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