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;
12 import java.util.ArrayList;
13 import java.util.HashMap;
14 import java.util.List;
16 import java.util.Map.Entry;
17 import org.opendaylight.controller.md.sal.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.Codec;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
31 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
32 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
33 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
34 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
35 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
40 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
41 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 public final class RestCodec {
48 private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
53 public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
54 final DOMMountPoint mountPoint) {
55 return new ObjectCodec(typeDefinition, mountPoint);
58 @SuppressWarnings("rawtypes")
59 public static final class ObjectCodec implements Codec<Object, Object> {
61 private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
63 public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
64 private final Codec instanceIdentifier;
65 private final Codec identityrefCodec;
67 private final TypeDefinition<?> type;
69 private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint) {
70 this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
71 if (this.type instanceof IdentityrefTypeDefinition) {
72 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint);
74 this.identityrefCodec = null;
76 if (this.type instanceof InstanceIdentifierTypeDefinition) {
77 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint);
79 this.instanceIdentifier = null;
83 @SuppressWarnings("unchecked")
85 public Object deserialize(final Object input) {
87 if (this.type instanceof IdentityrefTypeDefinition) {
88 if (input instanceof IdentityValuesDTO) {
89 return this.identityrefCodec.deserialize(input);
91 if (LOG.isDebugEnabled()) {
93 "Value is not instance of IdentityrefTypeDefinition but is {}. "
94 + "Therefore NULL is used as translation of - {}",
95 input == null ? "null" : input.getClass(), String.valueOf(input));
98 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
99 if (input instanceof IdentityValuesDTO) {
100 return this.instanceIdentifier.deserialize(input);
102 final StringModuleInstanceIdentifierCodec codec = new StringModuleInstanceIdentifierCodec(
103 ControllerContext.getInstance().getGlobalSchema());
104 return codec.deserialize((String) input);
107 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
108 TypeDefinitionAwareCodec.from(this.type);
109 if (typeAwarecodec != null) {
110 if (input instanceof IdentityValuesDTO) {
111 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
113 return typeAwarecodec.deserialize(String.valueOf(input));
115 LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
116 + "\" is not implemented yet.");
120 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
122 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
128 @SuppressWarnings("unchecked")
130 public Object serialize(final Object input) {
132 if (this.type instanceof IdentityrefTypeDefinition) {
133 return this.identityrefCodec.serialize(input);
134 } else if (this.type instanceof LeafrefTypeDefinition) {
135 return LEAFREF_DEFAULT_CODEC.serialize(input);
136 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
137 return this.instanceIdentifier.serialize(input);
139 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
140 TypeDefinitionAwareCodec.from(this.type);
141 if (typeAwarecodec != null) {
142 return typeAwarecodec.serialize(input);
144 if (LOG.isDebugEnabled()) {
145 LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
146 + "\" is not implemented yet.");
151 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
153 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
161 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
163 private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
165 private final DOMMountPoint mountPoint;
167 public IdentityrefCodecImpl(final DOMMountPoint mountPoint) {
168 this.mountPoint = mountPoint;
172 public IdentityValuesDTO serialize(final QName data) {
173 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
177 public QName deserialize(final IdentityValuesDTO data) {
178 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
179 final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint);
180 if (module == null) {
181 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
182 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
186 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
191 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
194 public String serialize(final Object data) {
195 return String.valueOf(data);
199 public Object deserialize(final String data) {
205 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
206 private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
207 private final DOMMountPoint mountPoint;
209 public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint) {
210 this.mountPoint = mountPoint;
214 public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
215 final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
216 for (final PathArgument pathArgument : data.getPathArguments()) {
217 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
218 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
219 final List<Predicate> predicates =
220 keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).getKeyValues());
221 identityValue.setPredicates(predicates);
222 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
223 final List<Predicate> predicates = new ArrayList<>();
224 final String value = String.valueOf(((NodeWithValue) pathArgument).getValue());
225 predicates.add(new Predicate(null, value));
226 identityValue.setPredicates(predicates);
228 identityValuesDTO.add(identityValue);
230 return identityValuesDTO;
233 @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE",
234 justification = "Unrecognised NullableDecl")
236 public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
237 final List<PathArgument> result = new ArrayList<>();
238 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
239 final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint);
240 if (module == null) {
241 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
242 valueWithNamespace.getNamespace());
243 LOG.info("Instance-identifier will be translated as NULL for data - {}",
244 String.valueOf(valueWithNamespace.getValue()));
248 DataNodeContainer parentContainer = module;
249 final List<IdentityValue> identities = data.getValuesWithNamespaces();
250 for (int i = 0; i < identities.size(); i++) {
251 final IdentityValue identityValue = identities.get(i);
252 URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), this.mountPoint);
253 final DataSchemaNode node = ControllerContext.findInstanceDataChildByNameAndNamespace(
254 parentContainer, identityValue.getValue(), validNamespace);
256 LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
257 LOG.info("Instance-identifier will be translated as NULL for data - {}",
258 String.valueOf(identityValue.getValue()));
261 final QName qName = node.getQName();
262 PathArgument pathArgument = null;
263 if (identityValue.getPredicates().isEmpty()) {
264 pathArgument = new NodeIdentifier(qName);
266 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
267 final Predicate leafListPredicate = identityValue.getPredicates().get(0);
268 if (!leafListPredicate.isLeafList()) {
269 LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
270 LOG.info("Instance-identifier will be translated as NULL for data - {}",
271 String.valueOf(identityValue.getValue()));
274 pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
275 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
276 final DataNodeContainer listNode = (DataNodeContainer) node;
277 final Map<QName, Object> predicatesMap = new HashMap<>();
278 for (final Predicate predicate : identityValue.getPredicates()) {
279 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint);
280 final DataSchemaNode listKey = ControllerContext
281 .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
283 predicatesMap.put(listKey.getQName(), predicate.getValue());
285 pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
287 LOG.info("Node {} is not List or Leaf-list.", node);
288 LOG.info("Instance-identifier will be translated as NULL for data - {}",
289 String.valueOf(identityValue.getValue()));
293 result.add(pathArgument);
294 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
296 if (node instanceof DataNodeContainer) {
297 parentContainer = (DataNodeContainer) node;
299 LOG.info("Node {} isn't instance of DataNodeContainer", node);
300 LOG.info("Instance-identifier will be translated as NULL for data - {}",
301 String.valueOf(identityValue.getValue()));
307 return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
310 private static List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
311 final List<Predicate> result = new ArrayList<>();
312 for (final Entry<QName, Object> entry : keyValues.entrySet()) {
313 final QName qualifiedName = entry.getKey();
314 final Object value = entry.getValue();
315 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
320 private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
321 if (qualifiedName != null) {
322 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
328 private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint) {
329 final URI validNamespace = resolveValidNamespace(namespace, mountPoint);
331 Module module = null;
332 if (mountPoint != null) {
333 module = ControllerContext.getInstance().findModuleByNamespace(mountPoint, validNamespace);
335 module = ControllerContext.getInstance().findModuleByNamespace(validNamespace);
337 if (module == null) {
338 LOG.info("Module for namespace " + validNamespace + " wasn't found.");
344 private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint) {
346 if (mountPoint != null) {
347 validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(mountPoint, namespace);
349 validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(namespace);
351 if (validNamespace == null) {
352 validNamespace = URI.create(namespace);
355 return validNamespace;