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 return LEAFREF_DEFAULT_CODEC.deserialize(input);
93 } else if (type instanceof InstanceIdentifierTypeDefinition) {
94 if (input instanceof IdentityValuesDTO) {
95 return instanceIdentifier.deserialize(input);
98 "Value is not instance of InstanceIdentifierTypeDefinition but is {}. Therefore NULL is used as translation of - {}",
99 input == null ? "null" : input.getClass(), String.valueOf(input));
102 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
104 if (typeAwarecodec != null) {
105 return typeAwarecodec.deserialize(String.valueOf(input));
107 logger.debug("Codec for type \"" + type.getQName().getLocalName()
108 + "\" is not implemented yet.");
112 } catch (ClassCastException e) { // TODO remove this catch when
113 // everyone use codecs
115 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
121 @SuppressWarnings("unchecked")
123 public Object serialize(Object input) {
125 if (type instanceof IdentityrefTypeDefinition) {
126 return identityrefCodec.serialize(input);
127 } else if (type instanceof LeafrefTypeDefinition) {
128 return LEAFREF_DEFAULT_CODEC.serialize(input);
129 } else if (type instanceof InstanceIdentifierTypeDefinition) {
130 return instanceIdentifier.serialize(input);
132 TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
134 if (typeAwarecodec != null) {
135 return typeAwarecodec.serialize(input);
137 logger.debug("Codec for type \"" + type.getQName().getLocalName()
138 + "\" is not implemented yet.");
142 } catch (ClassCastException e) { // TODO remove this catch when
143 // everyone use codecs
145 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
153 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
155 private final Logger logger = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
157 private final MountInstance mountPoint;
159 public IdentityrefCodecImpl(MountInstance mountPoint) {
160 this.mountPoint = mountPoint;
164 public IdentityValuesDTO serialize(QName data) {
165 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix());
169 public QName deserialize(IdentityValuesDTO data) {
170 IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
171 Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
172 if (module == null) {
173 logger.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
174 logger.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
178 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
183 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
186 public String serialize(Object data) {
187 return String.valueOf(data);
191 public Object deserialize(String data) {
197 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
198 private final Logger logger = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
199 private final MountInstance mountPoint;
201 public InstanceIdentifierCodecImpl(MountInstance mountPoint) {
202 this.mountPoint = mountPoint;
206 public IdentityValuesDTO serialize(InstanceIdentifier data) {
207 List<PathArgument> pathArguments = data.getPath();
208 IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
209 for (PathArgument pathArgument : pathArguments) {
210 IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
211 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
212 List<Predicate> predicates = keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument)
214 identityValue.setPredicates(predicates);
215 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
216 List<Predicate> predicates = new ArrayList<>();
217 String value = String.valueOf(((NodeWithValue) pathArgument).getValue());
218 predicates.add(new Predicate(null, value));
219 identityValue.setPredicates(predicates);
221 identityValuesDTO.add(identityValue);
223 return identityValuesDTO;
227 public InstanceIdentifier deserialize(IdentityValuesDTO data) {
228 List<PathArgument> result = new ArrayList<PathArgument>();
229 IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
230 Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
231 if (module == null) {
232 logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.", valueWithNamespace.getNamespace());
233 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(valueWithNamespace.getValue()));
237 DataNodeContainer parentContainer = module;
238 List<IdentityValue> identities = data.getValuesWithNamespaces();
239 for (int i = 0; i < identities.size(); i++) {
240 IdentityValue identityValue = identities.get(i);
241 URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), mountPoint);
242 DataSchemaNode node = ControllerContext.getInstance().findInstanceDataChildByNameAndNamespace(
243 parentContainer, identityValue.getValue(), validNamespace);
245 logger.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
246 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
249 QName qName = node.getQName();
250 PathArgument pathArgument = null;
251 if (identityValue.getPredicates().isEmpty()) {
252 pathArgument = new NodeIdentifier(qName);
254 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
255 Predicate leafListPredicate = identityValue.getPredicates().get(0);
256 if (!leafListPredicate.isLeafList()) {
257 logger.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
258 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
261 pathArgument = new NodeWithValue(qName, leafListPredicate.getValue());
262 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
263 DataNodeContainer listNode = (DataNodeContainer) node;
264 Map<QName, Object> predicatesMap = new HashMap<>();
265 for (Predicate predicate : identityValue.getPredicates()) {
266 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint);
267 DataSchemaNode listKey = ControllerContext.getInstance().findInstanceDataChildByNameAndNamespace(
268 listNode, predicate.getName().getValue(), validNamespace);
269 predicatesMap.put(listKey.getQName(), predicate.getValue());
271 pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
273 logger.info("Node {} is not List or Leaf-list.", node);
274 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
278 result.add(pathArgument);
279 if (i < identities.size() - 1) { // last element in instance-identifier can be other than DataNodeContainer
280 if (node instanceof DataNodeContainer) {
281 parentContainer = (DataNodeContainer) node;
283 logger.info("Node {} isn't instance of DataNodeContainer", node);
284 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
290 return result.isEmpty() ? null : new InstanceIdentifier(result);
293 private List<Predicate> keyValuesToPredicateList(Map<QName, Object> keyValues) {
294 List<Predicate> result = new ArrayList<>();
295 for (QName qName : keyValues.keySet()) {
296 Object value = keyValues.get(qName);
297 result.add(new Predicate(qNameToIdentityValue(qName), String.valueOf(value)));
302 private IdentityValue qNameToIdentityValue(QName qName) {
304 return new IdentityValue(qName.getNamespace().toString(), qName.getLocalName(), qName.getPrefix());
310 private static Module getModuleByNamespace(String namespace, MountInstance mountPoint) {
311 URI validNamespace = resolveValidNamespace(namespace, mountPoint);
313 Module module = null;
314 if (mountPoint != null) {
315 module = ControllerContext.getInstance().findModuleByNamespace(mountPoint, validNamespace);
317 module = ControllerContext.getInstance().findModuleByNamespace(validNamespace);
319 if (module == null) {
320 logger.info("Module for namespace " + validNamespace + " wasn't found.");
326 private static URI resolveValidNamespace(String namespace, MountInstance mountPoint) {
328 if (mountPoint != null) {
329 validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(mountPoint, namespace);
331 validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(namespace);
333 if (validNamespace == null) {
334 validNamespace = URI.create(namespace);
337 return validNamespace;