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