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