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