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