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