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.restconf.nb.rfc8040.codecs;
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.Iterables;
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.List;
18 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
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.AnyXmlSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
36 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.Module;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
52 public class RestCodec {
54 private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
59 public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
60 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
61 return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
64 @SuppressWarnings("rawtypes")
65 public static final class ObjectCodec implements Codec<Object, Object> {
67 private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
69 public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
70 private final Codec instanceIdentifier;
71 private final Codec identityrefCodec;
73 private final TypeDefinition<?> type;
75 private final SchemaContext schemaContext;
77 private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
78 final SchemaContext schemaContext) {
79 this.schemaContext = schemaContext;
80 this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
81 if (this.type instanceof IdentityrefTypeDefinition) {
82 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
84 this.identityrefCodec = null;
86 if (this.type instanceof InstanceIdentifierTypeDefinition) {
87 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
89 this.instanceIdentifier = null;
93 @SuppressWarnings("unchecked")
95 public Object deserialize(final Object input) {
97 if (this.type instanceof IdentityrefTypeDefinition) {
98 if (input instanceof IdentityValuesDTO) {
99 return this.identityrefCodec.deserialize(input);
101 if (LOG.isDebugEnabled()) {
103 "Value is not instance of IdentityrefTypeDefinition but is {}. "
104 + "Therefore NULL is used as translation of - {}",
105 input == null ? "null" : input.getClass(), String.valueOf(input));
108 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
109 if (input instanceof IdentityValuesDTO) {
110 return this.instanceIdentifier.deserialize(input);
112 final StringModuleInstanceIdentifierCodec codec =
113 new StringModuleInstanceIdentifierCodec(schemaContext);
114 return codec.deserialize((String) input);
117 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
118 TypeDefinitionAwareCodec.from(this.type);
119 if (typeAwarecodec != null) {
120 if (input instanceof IdentityValuesDTO) {
121 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
123 return typeAwarecodec.deserialize(String.valueOf(input));
125 LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
126 + "\" is not implemented yet.");
130 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
132 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
138 @SuppressWarnings("unchecked")
140 public Object serialize(final Object input) {
142 if (this.type instanceof IdentityrefTypeDefinition) {
143 return this.identityrefCodec.serialize(input);
144 } else if (this.type instanceof LeafrefTypeDefinition) {
145 return LEAFREF_DEFAULT_CODEC.serialize(input);
146 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
147 return this.instanceIdentifier.serialize(input);
149 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
150 TypeDefinitionAwareCodec.from(this.type);
151 if (typeAwarecodec != null) {
152 return typeAwarecodec.serialize(input);
154 if (LOG.isDebugEnabled()) {
155 LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
156 + "\" is not implemented yet.");
161 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
163 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
171 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
173 private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
175 private final DOMMountPoint mountPoint;
177 private final SchemaContext schemaContext;
179 public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
180 this.mountPoint = mountPoint;
181 this.schemaContext = schemaContext;
185 public IdentityValuesDTO serialize(final QName data) {
186 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
190 public QName deserialize(final IdentityValuesDTO data) {
191 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
192 final Module module =
193 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
194 if (module == null) {
195 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
196 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
200 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
205 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
208 public String serialize(final Object data) {
209 return String.valueOf(data);
213 public Object deserialize(final String data) {
219 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
220 private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
221 private final DOMMountPoint mountPoint;
222 private final SchemaContext schemaContext;
224 public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
225 this.mountPoint = mountPoint;
226 this.schemaContext = schemaContext;
230 public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
231 final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
232 for (final PathArgument pathArgument : data.getPathArguments()) {
233 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
234 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
235 final List<Predicate> predicates =
236 keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).getKeyValues());
237 identityValue.setPredicates(predicates);
238 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
239 final List<Predicate> predicates = new ArrayList<>();
240 final String value = String.valueOf(((NodeWithValue) pathArgument).getValue());
241 predicates.add(new Predicate(null, value));
242 identityValue.setPredicates(predicates);
244 identityValuesDTO.add(identityValue);
246 return identityValuesDTO;
250 public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
251 final List<PathArgument> result = new ArrayList<>();
252 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
253 final Module module =
254 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
255 if (module == null) {
256 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
257 valueWithNamespace.getNamespace());
258 LOG.info("Instance-identifier will be translated as NULL for data - {}",
259 String.valueOf(valueWithNamespace.getValue()));
263 DataNodeContainer parentContainer = module;
264 final List<IdentityValue> identities = data.getValuesWithNamespaces();
265 for (int i = 0; i < identities.size(); i++) {
266 final IdentityValue identityValue = identities.get(i);
268 resolveValidNamespace(identityValue.getNamespace(), this.mountPoint, schemaContext);
269 final DataSchemaNode node = findInstanceDataChildByNameAndNamespace(
270 parentContainer, identityValue.getValue(), validNamespace);
272 LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
273 LOG.info("Instance-identifier will be translated as NULL for data - {}",
274 String.valueOf(identityValue.getValue()));
277 final QName qName = node.getQName();
278 PathArgument pathArgument = null;
279 if (identityValue.getPredicates().isEmpty()) {
280 pathArgument = new NodeIdentifier(qName);
282 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
283 final Predicate leafListPredicate = identityValue.getPredicates().get(0);
284 if (!leafListPredicate.isLeafList()) {
285 LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
286 LOG.info("Instance-identifier will be translated as NULL for data - {}",
287 String.valueOf(identityValue.getValue()));
290 pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
291 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
292 final DataNodeContainer listNode = (DataNodeContainer) node;
293 final Map<QName, Object> predicatesMap = new HashMap<>();
294 for (final Predicate predicate : identityValue.getPredicates()) {
295 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
297 final DataSchemaNode listKey = findInstanceDataChildByNameAndNamespace(listNode,
298 predicate.getName().getValue(), validNamespace);
299 predicatesMap.put(listKey.getQName(), predicate.getValue());
301 pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
303 LOG.info("Node {} is not List or Leaf-list.", node);
304 LOG.info("Instance-identifier will be translated as NULL for data - {}",
305 String.valueOf(identityValue.getValue()));
309 result.add(pathArgument);
310 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
312 if (node instanceof DataNodeContainer) {
313 parentContainer = (DataNodeContainer) node;
315 LOG.info("Node {} isn't instance of DataNodeContainer", node);
316 LOG.info("Instance-identifier will be translated as NULL for data - {}",
317 String.valueOf(identityValue.getValue()));
323 return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
326 private static List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
327 final List<Predicate> result = new ArrayList<>();
328 for (final QName qualifiedName : keyValues.keySet()) {
329 final Object value = keyValues.get(qualifiedName);
330 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
335 private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
336 if (qualifiedName != null) {
337 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
343 private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
344 final SchemaContext schemaContext) {
345 final URI validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext);
346 Module module = null;
347 if (mountPoint != null) {
348 module = mountPoint.getSchemaContext().findModuleByNamespace(validNamespace).iterator().next();
350 module = schemaContext.findModuleByNamespace(validNamespace).iterator().next();
352 if (module == null) {
353 LOG.info("Module for namespace " + validNamespace + " wasn't found.");
359 private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
361 if (mountPoint != null) {
362 validNamespace = findFirstModuleByName(schemaContext, namespace);
364 validNamespace = findFirstModuleByName(schemaContext, namespace);
366 if (validNamespace == null) {
367 validNamespace = URI.create(namespace);
370 return validNamespace;
373 private static URI findFirstModuleByName(final SchemaContext schemaContext, final String name) {
374 for (final Module module : schemaContext.getModules()) {
375 if (module.getName().equals(name)) {
376 return module.getNamespace();
382 private static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
383 final String name, final URI namespace) {
384 Preconditions.checkNotNull(namespace);
386 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
387 node -> namespace.equals(node.getQName().getNamespace()));
388 return Iterables.getFirst(result, null);
391 private static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
393 Preconditions.checkNotNull(container);
394 Preconditions.checkNotNull(name);
396 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
397 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
398 return instantiatedDataNodeContainers;
401 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
402 final DataNodeContainer container, final String name) {
404 final Iterable<DataSchemaNode> nodes =
405 Iterables.filter(container.getChildNodes(), node -> name.equals(node.getQName().getLocalName()));
407 // Can't combine this loop with the filter above because the filter is
408 // lazily-applied by Iterables.filter.
409 for (final DataSchemaNode potentialNode : nodes) {
410 if (isInstantiatedDataSchema(potentialNode)) {
411 potentialSchemaNodes.add(potentialNode);
415 final Iterable<ChoiceSchemaNode> choiceNodes =
416 Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
417 final Iterable<Set<ChoiceCaseNode>> map = Iterables.transform(choiceNodes, ChoiceSchemaNode::getCases);
418 for (final ChoiceCaseNode caze : Iterables.concat(map)) {
419 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
423 private static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
424 return (node instanceof LeafSchemaNode) || (node instanceof LeafListSchemaNode)
425 || (node instanceof ContainerSchemaNode) || (node instanceof ListSchemaNode)
426 || (node instanceof AnyXmlSchemaNode);