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