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;
15 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
16 import org.opendaylight.controller.sal.rest.impl.RestUtil;
17 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
18 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.Predicate;
19 import org.opendaylight.yangtools.concepts.Codec;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
25 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
26 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
27 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
28 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
29 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
30 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
31 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
36 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
37 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
38 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 public class RestCodec {
44 private static final Logger logger = LoggerFactory.getLogger(RestCodec.class);
49 public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
50 final DOMMountPoint 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(final TypeDefinition<?> typeDefinition, final DOMMountPoint 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(final 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 InstanceIdentifierTypeDefinition) {
92 if (input instanceof IdentityValuesDTO) {
93 return instanceIdentifier.deserialize(input);
96 "Value is not instance of InstanceIdentifierTypeDefinition but is {}. Therefore NULL is used as translation of - {}",
97 input == null ? "null" : input.getClass(), String.valueOf(input));
100 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec = TypeDefinitionAwareCodec
102 if (typeAwarecodec != null) {
103 if (input instanceof IdentityValuesDTO) {
104 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
106 return typeAwarecodec.deserialize(String.valueOf(input));
108 logger.debug("Codec for type \"" + type.getQName().getLocalName()
109 + "\" is not implemented yet.");
113 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
115 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
121 @SuppressWarnings("unchecked")
123 public Object serialize(final 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 final 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 (final ClassCastException e) { // TODO remove this catch when everyone use codecs
144 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
152 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
154 private final Logger logger = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
156 private final DOMMountPoint mountPoint;
158 public IdentityrefCodecImpl(final DOMMountPoint mountPoint) {
159 this.mountPoint = mountPoint;
163 public IdentityValuesDTO serialize(final QName data) {
164 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
168 public QName deserialize(final IdentityValuesDTO data) {
169 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
170 final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
171 if (module == null) {
172 logger.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
173 logger.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
177 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
182 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
185 public String serialize(final Object data) {
186 return String.valueOf(data);
190 public Object deserialize(final String data) {
196 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
197 private final Logger logger = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
198 private final DOMMountPoint mountPoint;
200 public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint) {
201 this.mountPoint = mountPoint;
205 public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
206 final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
207 for (final PathArgument pathArgument : data.getPathArguments()) {
208 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
209 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
210 final List<Predicate> predicates = keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument)
212 identityValue.setPredicates(predicates);
213 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
214 final List<Predicate> predicates = new ArrayList<>();
215 final String value = String.valueOf(((NodeWithValue) pathArgument).getValue());
216 predicates.add(new Predicate(null, value));
217 identityValue.setPredicates(predicates);
219 identityValuesDTO.add(identityValue);
221 return identityValuesDTO;
225 public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
226 final List<PathArgument> result = new ArrayList<PathArgument>();
227 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
228 final Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
229 if (module == null) {
230 logger.info("Module by namespace '{}' of first node in instance-identifier was not found.",
231 valueWithNamespace.getNamespace());
232 logger.info("Instance-identifier will be translated as NULL for data - {}",
233 String.valueOf(valueWithNamespace.getValue()));
237 DataNodeContainer parentContainer = module;
238 final List<IdentityValue> identities = data.getValuesWithNamespaces();
239 for (int i = 0; i < identities.size(); i++) {
240 final IdentityValue identityValue = identities.get(i);
241 URI validNamespace = resolveValidNamespace(identityValue.getNamespace(), mountPoint);
242 final DataSchemaNode node = ControllerContext.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 - {}",
247 String.valueOf(identityValue.getValue()));
250 final QName qName = node.getQName();
251 PathArgument pathArgument = null;
252 if (identityValue.getPredicates().isEmpty()) {
253 pathArgument = new NodeIdentifier(qName);
255 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
256 final Predicate leafListPredicate = identityValue.getPredicates().get(0);
257 if (!leafListPredicate.isLeafList()) {
258 logger.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
259 logger.info("Instance-identifier will be translated as NULL for data - {}",
260 String.valueOf(identityValue.getValue()));
263 pathArgument = new NodeWithValue(qName, leafListPredicate.getValue());
264 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
265 final DataNodeContainer listNode = (DataNodeContainer) node;
266 final Map<QName, Object> predicatesMap = new HashMap<>();
267 for (final Predicate predicate : identityValue.getPredicates()) {
268 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint);
269 final DataSchemaNode listKey = ControllerContext
270 .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
272 predicatesMap.put(listKey.getQName(), predicate.getValue());
274 pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
276 logger.info("Node {} is not List or Leaf-list.", node);
277 logger.info("Instance-identifier will be translated as NULL for data - {}",
278 String.valueOf(identityValue.getValue()));
282 result.add(pathArgument);
283 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
285 if (node instanceof DataNodeContainer) {
286 parentContainer = (DataNodeContainer) node;
288 logger.info("Node {} isn't instance of DataNodeContainer", node);
289 logger.info("Instance-identifier will be translated as NULL for data - {}",
290 String.valueOf(identityValue.getValue()));
296 return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
299 private List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
300 final List<Predicate> result = new ArrayList<>();
301 for (final QName qName : keyValues.keySet()) {
302 final Object value = keyValues.get(qName);
303 result.add(new Predicate(qNameToIdentityValue(qName), String.valueOf(value)));
308 private IdentityValue qNameToIdentityValue(final QName qName) {
310 return new IdentityValue(qName.getNamespace().toString(), qName.getLocalName());
316 private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint) {
317 final 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(final String namespace, final DOMMountPoint 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;