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.controller.sal.restconf.impl;
11 import java.util.ArrayList;
12 import java.util.HashMap;
13 import java.util.List;
16 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
17 import org.opendaylight.controller.sal.rest.impl.RestUtil;
18 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
19 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.Predicate;
20 import org.opendaylight.yangtools.concepts.Codec;
21 import org.opendaylight.yangtools.yang.common.QName;
22 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
25 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
26 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
27 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
28 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
29 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
30 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
31 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
32 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.Module;
36 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
37 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
38 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 public class RestCodec {
45 private static final Logger logger = LoggerFactory.getLogger(RestCodec.class);
50 public static final Codec<Object, Object> from(TypeDefinition<?> typeDefinition, MountInstance mountPoint) {
51 return new ObjectCodec(typeDefinition, mountPoint);
54 @SuppressWarnings("rawtypes")
55 public static final class ObjectCodec implements Codec<Object, Object> {
57 private final Logger logger = LoggerFactory.getLogger(RestCodec.class);
59 public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
60 private final Codec instanceIdentifier;
61 private final Codec identityrefCodec;
63 private final TypeDefinition<?> type;
65 private ObjectCodec(TypeDefinition<?> typeDefinition, MountInstance mountPoint) {
66 type = RestUtil.resolveBaseTypeFrom(typeDefinition);
67 if (type instanceof IdentityrefTypeDefinition) {
68 identityrefCodec = new IdentityrefCodecImpl(mountPoint);
70 identityrefCodec = null;
72 if (type instanceof InstanceIdentifierTypeDefinition) {
73 instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint);
75 instanceIdentifier = null;
79 @SuppressWarnings("unchecked")
81 public Object deserialize(Object input) {
83 if (type instanceof IdentityrefTypeDefinition) {
84 if (input instanceof IdentityValuesDTO) {
85 return identityrefCodec.deserialize(input);
88 "Value is not instance of IdentityrefTypeDefinition but is {}. Therefore NULL is used as translation of - {}",
89 input == null ? "null" : input.getClass(), String.valueOf(input));
91 } else if (type instanceof LeafrefTypeDefinition) {
92 if (input instanceof IdentityValuesDTO) {
93 return LEAFREF_DEFAULT_CODEC.deserialize(((IdentityValuesDTO)input).getOriginValue());
95 return LEAFREF_DEFAULT_CODEC.deserialize(input);
96 } else if (type instanceof InstanceIdentifierTypeDefinition) {
97 if (input instanceof IdentityValuesDTO) {
98 return instanceIdentifier.deserialize(input);
101 "Value is not instance of InstanceIdentifierTypeDefinition but is {}. Therefore NULL is used as translation of - {}",
102 input == null ? "null" : input.getClass(), String.valueOf(input));
105 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
107 if (typeAwarecodec != null) {
108 if (input instanceof IdentityValuesDTO) {
109 return typeAwarecodec.deserialize(((IdentityValuesDTO)input).getOriginValue());
111 return typeAwarecodec.deserialize(String.valueOf(input));
113 logger.debug("Codec for type \"" + type.getQName().getLocalName()
114 + "\" is not implemented yet.");
118 } catch (ClassCastException e) { // TODO remove this catch when
119 // everyone use codecs
121 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
127 @SuppressWarnings("unchecked")
129 public Object serialize(Object input) {
131 if (type instanceof IdentityrefTypeDefinition) {
132 return identityrefCodec.serialize(input);
133 } else if (type instanceof LeafrefTypeDefinition) {
134 return LEAFREF_DEFAULT_CODEC.serialize(input);
135 } else if (type instanceof InstanceIdentifierTypeDefinition) {
136 return instanceIdentifier.serialize(input);
138 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
140 if (typeAwarecodec != null) {
141 return typeAwarecodec.serialize(input);
143 logger.debug("Codec for type \"" + type.getQName().getLocalName()
144 + "\" is not implemented yet.");
148 } catch (ClassCastException e) { // TODO remove this catch when
149 // everyone use codecs
151 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
159 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
161 private final Logger logger = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
163 private final MountInstance mountPoint;
165 public IdentityrefCodecImpl(MountInstance mountPoint) {
166 this.mountPoint = mountPoint;
170 public IdentityValuesDTO serialize(QName data) {
171 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(),null);
175 public QName deserialize(IdentityValuesDTO data) {
176 IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
177 Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
178 if (module == null) {
179 logger.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
180 logger.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
184 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
189 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
192 public String serialize(Object data) {
193 return String.valueOf(data);
197 public Object deserialize(String data) {
203 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
204 private final Logger logger = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
205 private final MountInstance mountPoint;
207 public InstanceIdentifierCodecImpl(MountInstance mountPoint) {
208 this.mountPoint = mountPoint;
212 public IdentityValuesDTO serialize(InstanceIdentifier data) {
213 List<PathArgument> pathArguments = data.getPath();
214 IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
215 for (PathArgument pathArgument : pathArguments) {
216 IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
217 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
218 List<Predicate> predicates = keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument)
220 identityValue.setPredicates(predicates);
221 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
222 List<Predicate> predicates = new ArrayList<>();
223 String value = String.valueOf(((NodeWithValue) pathArgument).getValue());
224 predicates.add(new Predicate(null, value));
225 identityValue.setPredicates(predicates);
227 identityValuesDTO.add(identityValue);
229 return identityValuesDTO;
233 public InstanceIdentifier deserialize(IdentityValuesDTO data) {
234 List<PathArgument> result = new ArrayList<PathArgument>();
235 IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
236 Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
237 if (module == null) {
238 logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.", valueWithNamespace.getNamespace());
239 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(valueWithNamespace.getValue()));
243 DataNodeContainer parentContainer = module;
244 List<IdentityValue> identities = data.getValuesWithNamespaces();
245 for (int i = 0; i < identities.size(); i++) {
246 IdentityValue identityValue = identities.get(i);
247 URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), mountPoint);
248 DataSchemaNode node = ControllerContext.getInstance().findInstanceDataChildByNameAndNamespace(
249 parentContainer, identityValue.getValue(), validNamespace);
251 logger.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
252 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
255 QName qName = node.getQName();
256 PathArgument pathArgument = null;
257 if (identityValue.getPredicates().isEmpty()) {
258 pathArgument = new NodeIdentifier(qName);
260 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
261 Predicate leafListPredicate = identityValue.getPredicates().get(0);
262 if (!leafListPredicate.isLeafList()) {
263 logger.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
264 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
267 pathArgument = new NodeWithValue(qName, leafListPredicate.getValue());
268 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
269 DataNodeContainer listNode = (DataNodeContainer) node;
270 Map<QName, Object> predicatesMap = new HashMap<>();
271 for (Predicate predicate : identityValue.getPredicates()) {
272 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint);
273 DataSchemaNode listKey = ControllerContext.getInstance().findInstanceDataChildByNameAndNamespace(
274 listNode, predicate.getName().getValue(), validNamespace);
275 predicatesMap.put(listKey.getQName(), predicate.getValue());
277 pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
279 logger.info("Node {} is not List or Leaf-list.", node);
280 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
284 result.add(pathArgument);
285 if (i < identities.size() - 1) { // last element in instance-identifier can be other than DataNodeContainer
286 if (node instanceof DataNodeContainer) {
287 parentContainer = (DataNodeContainer) node;
289 logger.info("Node {} isn't instance of DataNodeContainer", node);
290 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
296 return result.isEmpty() ? null : new InstanceIdentifier(result);
299 private List<Predicate> keyValuesToPredicateList(Map<QName, Object> keyValues) {
300 List<Predicate> result = new ArrayList<>();
301 for (QName qName : keyValues.keySet()) {
302 Object value = keyValues.get(qName);
303 result.add(new Predicate(qNameToIdentityValue(qName), String.valueOf(value)));
308 private IdentityValue qNameToIdentityValue(QName qName) {
310 return new IdentityValue(qName.getNamespace().toString(), qName.getLocalName(), qName.getPrefix());
316 private static Module getModuleByNamespace(String namespace, MountInstance mountPoint) {
317 URI validNamespace = resolveValidNamespace(namespace, mountPoint);
319 Module module = null;
320 if (mountPoint != null) {
321 module = ControllerContext.getInstance().findModuleByNamespace(mountPoint, validNamespace);
323 module = ControllerContext.getInstance().findModuleByNamespace(validNamespace);
325 if (module == null) {
326 logger.info("Module for namespace " + validNamespace + " wasn't found.");
332 private static URI resolveValidNamespace(String namespace, MountInstance mountPoint) {
334 if (mountPoint != null) {
335 validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(mountPoint, namespace);
337 validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(namespace);
339 if (validNamespace == null) {
340 validNamespace = URI.create(namespace);
343 return validNamespace;