2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.netconf.sal.restconf.impl;
10 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
11 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.List;
15 import java.util.Map.Entry;
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;
47 public final class RestCodec {
49 private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
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);
60 @SuppressWarnings("rawtypes")
61 public static final class ObjectCodec implements IllegalArgumentCodec<Object, Object> {
63 private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
65 public static final IllegalArgumentCodec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
67 private final ControllerContext controllerContext;
68 private final IllegalArgumentCodec instanceIdentifier;
69 private final IllegalArgumentCodec identityrefCodec;
71 private final TypeDefinition<?> type;
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);
80 identityrefCodec = null;
82 if (type instanceof InstanceIdentifierTypeDefinition) {
83 instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, controllerContext);
85 instanceIdentifier = null;
89 @SuppressWarnings("unchecked")
91 @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "Legacy code")
92 public Object deserialize(final Object input) {
94 if (type instanceof IdentityrefTypeDefinition) {
95 if (input instanceof IdentityValuesDTO) {
96 return identityrefCodec.deserialize(input);
98 if (LOG.isDebugEnabled()) {
100 "Value is not instance of IdentityrefTypeDefinition but is {}. "
101 + "Therefore NULL is used as translation of - {}",
102 input == null ? "null" : input.getClass(), String.valueOf(input));
104 // FIXME: this should be a hard error
106 } else if (type instanceof InstanceIdentifierTypeDefinition) {
107 if (input instanceof IdentityValuesDTO) {
108 return instanceIdentifier.deserialize(input);
110 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
111 controllerContext.getGlobalSchema());
112 return codec.deserialize((String) input);
115 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
116 TypeDefinitionAwareCodec.from(type);
117 if (typeAwarecodec != null) {
118 if (input instanceof IdentityValuesDTO) {
119 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
121 return typeAwarecodec.deserialize(String.valueOf(input));
123 LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
124 // FIXME: this should be a hard error
128 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
129 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
130 // FIXME: this should be a hard error
135 @SuppressWarnings("unchecked")
137 @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "legacy code")
138 public Object serialize(final Object input) {
140 if (type instanceof IdentityrefTypeDefinition) {
141 return identityrefCodec.serialize(input);
142 } else if (type instanceof LeafrefTypeDefinition) {
143 return LEAFREF_DEFAULT_CODEC.serialize(input);
144 } else if (type instanceof InstanceIdentifierTypeDefinition) {
145 return instanceIdentifier.serialize(input);
147 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
148 TypeDefinitionAwareCodec.from(type);
149 if (typeAwarecodec != null) {
150 return typeAwarecodec.serialize(input);
152 LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
156 } catch (final ClassCastException e) {
157 // FIXME: remove this catch when everyone use codecs
158 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
159 // FIXME: this should be a hard error
166 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
167 private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
169 private final DOMMountPoint mountPoint;
170 private final ControllerContext controllerContext;
172 public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final ControllerContext controllerContext) {
173 this.mountPoint = mountPoint;
174 this.controllerContext = controllerContext;
178 public IdentityValuesDTO serialize(final QName data) {
179 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
183 @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "See FIXME below")
184 public QName deserialize(final IdentityValuesDTO data) {
185 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
186 final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint,
188 if (module == null) {
189 // FIXME: this should be a hard error
190 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
191 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
195 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
199 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
202 public String serialize(final Object data) {
203 return String.valueOf(data);
207 public Object deserialize(final String data) {
213 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
214 private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
216 private final DOMMountPoint mountPoint;
217 private final ControllerContext controllerContext;
219 public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint,
220 final ControllerContext controllerContext) {
221 this.mountPoint = mountPoint;
222 this.controllerContext = controllerContext;
226 public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
227 final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
228 for (final PathArgument pathArgument : data.getPathArguments()) {
229 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
230 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
231 final List<Predicate> predicates =
232 keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).entrySet());
233 identityValue.setPredicates(predicates);
234 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
235 final List<Predicate> predicates = new ArrayList<>();
236 final String value = String.valueOf(((NodeWithValue<?>) pathArgument).getValue());
237 predicates.add(new Predicate(null, value));
238 identityValue.setPredicates(predicates);
240 identityValuesDTO.add(identityValue);
242 return identityValuesDTO;
245 @SuppressFBWarnings(value = { "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE", "NP_NONNULL_RETURN_VIOLATION" },
246 justification = "Unrecognised NullableDecl")
248 public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
249 final List<PathArgument> result = new ArrayList<>();
250 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
251 final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint,
253 if (module == null) {
254 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
255 valueWithNamespace.getNamespace());
256 LOG.info("Instance-identifier will be translated as NULL for data - {}",
257 String.valueOf(valueWithNamespace.getValue()));
258 // FIXME: this should be a hard error
262 DataNodeContainer parentContainer = module;
263 final List<IdentityValue> identities = data.getValuesWithNamespaces();
264 for (int i = 0; i < identities.size(); i++) {
265 final IdentityValue identityValue = identities.get(i);
266 XMLNamespace validNamespace = resolveValidNamespace(identityValue.getNamespace(), mountPoint,
268 final var found = ControllerContext.findInstanceDataChildByNameAndNamespace(
269 parentContainer, identityValue.getValue(), validNamespace);
271 LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
272 LOG.info("Instance-identifier will be translated as NULL for data - {}",
273 String.valueOf(identityValue.getValue()));
274 // FIXME: this should be a hard error
277 final DataSchemaNode node = found.child;
278 final QName qName = node.getQName();
279 PathArgument pathArgument = null;
280 if (identityValue.getPredicates().isEmpty()) {
281 pathArgument = new NodeIdentifier(qName);
283 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
284 final Predicate leafListPredicate = identityValue.getPredicates().get(0);
285 if (!leafListPredicate.isLeafList()) {
286 LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
287 LOG.info("Instance-identifier will be translated as NULL for data - {}",
288 String.valueOf(identityValue.getValue()));
289 // FIXME: this should be a hard error
292 pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
293 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
294 final DataNodeContainer listNode = (DataNodeContainer) node;
295 final Map<QName, Object> predicatesMap = new HashMap<>();
296 for (final Predicate predicate : identityValue.getPredicates()) {
297 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint,
299 final var listKey = ControllerContext
300 .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
302 predicatesMap.put(listKey.child.getQName(), predicate.getValue());
304 pathArgument = NodeIdentifierWithPredicates.of(qName, predicatesMap);
306 LOG.info("Node {} is not List or Leaf-list.", node);
307 LOG.info("Instance-identifier will be translated as NULL for data - {}",
308 String.valueOf(identityValue.getValue()));
309 // FIXME: this should be a hard error
313 result.add(pathArgument);
314 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
316 if (node instanceof DataNodeContainer) {
317 parentContainer = (DataNodeContainer) node;
319 LOG.info("Node {} isn't instance of DataNodeContainer", node);
320 LOG.info("Instance-identifier will be translated as NULL for data - {}",
321 String.valueOf(identityValue.getValue()));
322 // FIXME: this should be a hard error
328 return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
331 private static List<Predicate> keyValuesToPredicateList(final Set<Entry<QName, Object>> keyValues) {
332 final List<Predicate> result = new ArrayList<>();
333 for (final Entry<QName, Object> entry : keyValues) {
334 final QName qualifiedName = entry.getKey();
335 final Object value = entry.getValue();
336 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
341 private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
342 if (qualifiedName != null) {
343 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
349 private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
350 final ControllerContext controllerContext) {
351 final XMLNamespace validNamespace = resolveValidNamespace(namespace, mountPoint, controllerContext);
353 Module module = null;
354 if (mountPoint != null) {
355 module = ControllerContext.findModuleByNamespace(mountPoint, validNamespace);
357 module = controllerContext.findModuleByNamespace(validNamespace);
359 if (module == null) {
360 LOG.info("Module for namespace {} was not found.", validNamespace);
366 private static XMLNamespace resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
367 final ControllerContext controllerContext) {
368 XMLNamespace validNamespace;
369 if (mountPoint != null) {
370 validNamespace = ControllerContext.findNamespaceByModuleName(mountPoint, namespace);
372 validNamespace = controllerContext.findNamespaceByModuleName(namespace);
374 if (validNamespace == null) {
375 validNamespace = XMLNamespace.of(namespace);
378 return validNamespace;