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