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);
216 identityValuesDTO.add(identityValue);
218 return identityValuesDTO;
222 public InstanceIdentifier deserialize(IdentityValuesDTO data) {
223 List<PathArgument> result = new ArrayList<PathArgument>();
224 IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
225 Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
226 if (module == null) {
227 logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.", valueWithNamespace.getNamespace());
228 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(valueWithNamespace.getValue()));
232 DataNodeContainer parentContainer = module;
233 List<IdentityValue> identities = data.getValuesWithNamespaces();
234 for (int i = 0; i < identities.size(); i++) {
235 IdentityValue identityValue = identities.get(i);
236 URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), mountPoint);
237 DataSchemaNode node = ControllerContext.getInstance().findInstanceDataChildByNameAndNamespace(
238 parentContainer, identityValue.getValue(), validNamespace);
240 logger.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
241 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
244 QName qName = node.getQName();
245 PathArgument pathArgument = null;
246 if (identityValue.getPredicates().isEmpty()) {
247 pathArgument = new NodeIdentifier(qName);
249 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
250 Predicate leafListPredicate = identityValue.getPredicates().get(0);
251 if (!leafListPredicate.isLeafList()) {
252 logger.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
253 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
256 pathArgument = new NodeWithValue(qName, leafListPredicate.getValue());
257 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
258 DataNodeContainer listNode = (DataNodeContainer) node;
259 Map<QName, Object> predicatesMap = new HashMap<>();
260 for (Predicate predicate : identityValue.getPredicates()) {
261 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint);
262 DataSchemaNode listKey = ControllerContext.getInstance().findInstanceDataChildByNameAndNamespace(
263 listNode, predicate.getName().getValue(), validNamespace);
264 predicatesMap.put(listKey.getQName(), predicate.getValue());
266 pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
268 logger.info("Node {} is not List or Leaf-list.", node);
269 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
273 result.add(pathArgument);
274 if (i < identities.size() - 1) { // last element in instance-identifier can be other than DataNodeContainer
275 if (node instanceof DataNodeContainer) {
276 parentContainer = (DataNodeContainer) node;
278 logger.info("Node {} isn't instance of DataNodeContainer", node);
279 logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
285 return result.isEmpty() ? null : new InstanceIdentifier(result);
288 private List<Predicate> keyValuesToPredicateList(Map<QName, Object> keyValues) {
289 List<Predicate> result = new ArrayList<>();
290 for (QName qName : keyValues.keySet()) {
291 Object value = keyValues.get(qName);
292 result.add(new Predicate(qNameToIdentityValue(qName), String.valueOf(value)));
297 private IdentityValue qNameToIdentityValue(QName qName) {
299 return new IdentityValue(qName.getNamespace().toString(), qName.getLocalName(), qName.getPrefix());
305 private static Module getModuleByNamespace(String namespace, MountInstance mountPoint) {
306 URI validNamespace = resolveValidNamespace(namespace, mountPoint);
308 Module module = null;
309 if (mountPoint != null) {
310 module = ControllerContext.getInstance().findModuleByNamespace(mountPoint, validNamespace);
312 module = ControllerContext.getInstance().findModuleByNamespace(validNamespace);
314 if (module == null) {
315 logger.info("Module for namespace " + validNamespace + " wasn't found.");
321 private static URI resolveValidNamespace(String namespace, MountInstance mountPoint) {
323 if (mountPoint != null) {
324 validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(mountPoint, namespace);
326 validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(namespace);
328 if (validNamespace == null) {
329 validNamespace = URI.create(namespace);
332 return validNamespace;