Split Restconf implementations (draft02 and RFC) - move
[netconf.git] / restconf / restconf-nb-bierman02 / 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.StringModuleInstanceIdentifierCodec;
17 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
18 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
19 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
20 import org.opendaylight.restconf.common.util.RestUtil;
21 import org.opendaylight.yangtools.concepts.Codec;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
28 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
29 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
30 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
31 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.Module;
37 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
38 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 public class RestCodec {
45
46     private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
47
48     private RestCodec() {
49     }
50
51     public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
52             final DOMMountPoint mountPoint) {
53         return new ObjectCodec(typeDefinition, mountPoint);
54     }
55
56     @SuppressWarnings("rawtypes")
57     public static final class ObjectCodec implements Codec<Object, Object> {
58
59         private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
60
61         public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
62         private final Codec instanceIdentifier;
63         private final Codec identityrefCodec;
64
65         private final TypeDefinition<?> type;
66
67         private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint) {
68             this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
69             if (this.type instanceof IdentityrefTypeDefinition) {
70                 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint);
71             } else {
72                 this.identityrefCodec = null;
73             }
74             if (this.type instanceof InstanceIdentifierTypeDefinition) {
75                 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint);
76             } else {
77                 this.instanceIdentifier = null;
78             }
79         }
80
81         @SuppressWarnings("unchecked")
82         @Override
83         public Object deserialize(final Object input) {
84             try {
85                 if (this.type instanceof IdentityrefTypeDefinition) {
86                     if (input instanceof IdentityValuesDTO) {
87                         return this.identityrefCodec.deserialize(input);
88                     }
89                     if (LOG.isDebugEnabled()) {
90                         LOG.debug(
91                             "Value is not instance of IdentityrefTypeDefinition but is {}. "
92                                     + "Therefore NULL is used as translation of  - {}",
93                             input == null ? "null" : input.getClass(), String.valueOf(input));
94                     }
95                     return null;
96                 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
97                     if (input instanceof IdentityValuesDTO) {
98                         return this.instanceIdentifier.deserialize(input);
99                     } else {
100                         final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
101                                 ControllerContext.getInstance().getGlobalSchema());
102                         return codec.deserialize((String) input);
103                     }
104                 } else {
105                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
106                             TypeDefinitionAwareCodec.from(this.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                         LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
114                                 + "\" is not implemented yet.");
115                         return null;
116                     }
117                 }
118             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
119                 LOG.error(
120                         "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
121                         e);
122                 return null;
123             }
124         }
125
126         @SuppressWarnings("unchecked")
127         @Override
128         public Object serialize(final Object input) {
129             try {
130                 if (this.type instanceof IdentityrefTypeDefinition) {
131                     return this.identityrefCodec.serialize(input);
132                 } else if (this.type instanceof LeafrefTypeDefinition) {
133                     return LEAFREF_DEFAULT_CODEC.serialize(input);
134                 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
135                     return this.instanceIdentifier.serialize(input);
136                 } else {
137                     final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
138                             TypeDefinitionAwareCodec.from(this.type);
139                     if (typeAwarecodec != null) {
140                         return typeAwarecodec.serialize(input);
141                     } else {
142                         if (LOG.isDebugEnabled()) {
143                             LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
144                                 + "\" is not implemented yet.");
145                         }
146                         return null;
147                     }
148                 }
149             } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
150                 LOG.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 static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
162
163         private final DOMMountPoint mountPoint;
164
165         public IdentityrefCodecImpl(final DOMMountPoint 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(), null, null);
172         }
173
174         @Override
175         public QName deserialize(final IdentityValuesDTO data) {
176             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
177             final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint);
178             if (module == null) {
179                 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
180                 LOG.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 static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
205         private final DOMMountPoint mountPoint;
206
207         public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint) {
208             this.mountPoint = mountPoint;
209         }
210
211         @Override
212         public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
213             final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
214             for (final PathArgument pathArgument : data.getPathArguments()) {
215                 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
216                 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
217                     final List<Predicate> predicates =
218                             keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).getKeyValues());
219                     identityValue.setPredicates(predicates);
220                 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
221                     final List<Predicate> predicates = new ArrayList<>();
222                     final 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 YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
233             final List<PathArgument> result = new ArrayList<>();
234             final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
235             final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint);
236             if (module == null) {
237                 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
238                         valueWithNamespace.getNamespace());
239                 LOG.info("Instance-identifier will be translated as NULL for data - {}",
240                         String.valueOf(valueWithNamespace.getValue()));
241                 return null;
242             }
243
244             DataNodeContainer parentContainer = module;
245             final List<IdentityValue> identities = data.getValuesWithNamespaces();
246             for (int i = 0; i < identities.size(); i++) {
247                 final IdentityValue identityValue = identities.get(i);
248                 URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), this.mountPoint);
249                 final DataSchemaNode node = ControllerContext.findInstanceDataChildByNameAndNamespace(
250                         parentContainer, identityValue.getValue(), validNamespace);
251                 if (node == null) {
252                     LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
253                     LOG.info("Instance-identifier will be translated as NULL for data - {}",
254                             String.valueOf(identityValue.getValue()));
255                     return null;
256                 }
257                 final QName qName = node.getQName();
258                 PathArgument pathArgument = null;
259                 if (identityValue.getPredicates().isEmpty()) {
260                     pathArgument = new NodeIdentifier(qName);
261                 } else {
262                     if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
263                         final Predicate leafListPredicate = identityValue.getPredicates().get(0);
264                         if (!leafListPredicate.isLeafList()) {
265                             LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
266                             LOG.info("Instance-identifier will be translated as NULL for data - {}",
267                                     String.valueOf(identityValue.getValue()));
268                             return null;
269                         }
270                         pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
271                     } else if (node instanceof ListSchemaNode) { // predicates are keys of list
272                         final DataNodeContainer listNode = (DataNodeContainer) node;
273                         final Map<QName, Object> predicatesMap = new HashMap<>();
274                         for (final Predicate predicate : identityValue.getPredicates()) {
275                             validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint);
276                             final DataSchemaNode listKey = ControllerContext
277                                     .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
278                                             validNamespace);
279                             predicatesMap.put(listKey.getQName(), predicate.getValue());
280                         }
281                         pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
282                     } else {
283                         LOG.info("Node {} is not List or Leaf-list.", node);
284                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
285                                 String.valueOf(identityValue.getValue()));
286                         return null;
287                     }
288                 }
289                 result.add(pathArgument);
290                 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
291                     // DataNodeContainer
292                     if (node instanceof DataNodeContainer) {
293                         parentContainer = (DataNodeContainer) node;
294                     } else {
295                         LOG.info("Node {} isn't instance of DataNodeContainer", node);
296                         LOG.info("Instance-identifier will be translated as NULL for data - {}",
297                                 String.valueOf(identityValue.getValue()));
298                         return null;
299                     }
300                 }
301             }
302
303             return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
304         }
305
306         private static List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
307             final List<Predicate> result = new ArrayList<>();
308             for (final QName qualifiedName : keyValues.keySet()) {
309                 final Object value = keyValues.get(qualifiedName);
310                 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
311             }
312             return result;
313         }
314
315         private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
316             if (qualifiedName != null) {
317                 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
318             }
319             return null;
320         }
321     }
322
323     private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint) {
324         final URI validNamespace = resolveValidNamespace(namespace, mountPoint);
325
326         Module module = null;
327         if (mountPoint != null) {
328             module = ControllerContext.getInstance().findModuleByNamespace(mountPoint, validNamespace);
329         } else {
330             module = ControllerContext.getInstance().findModuleByNamespace(validNamespace);
331         }
332         if (module == null) {
333             LOG.info("Module for namespace " + validNamespace + " wasn't found.");
334             return null;
335         }
336         return module;
337     }
338
339     private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint) {
340         URI validNamespace;
341         if (mountPoint != null) {
342             validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(mountPoint, namespace);
343         } else {
344             validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(namespace);
345         }
346         if (validNamespace == null) {
347             validNamespace = URI.create(namespace);
348         }
349
350         return validNamespace;
351     }
352
353 }