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