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