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;
12 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
14 import java.util.ArrayList;
15 import java.util.Collection;
16 import java.util.HashMap;
17 import java.util.List;
19 import java.util.Map.Entry;
20 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
21 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
22 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
23 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
24 import org.opendaylight.restconf.common.util.RestUtil;
25 import org.opendaylight.yangtools.concepts.Codec;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
33 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
34 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
35 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
36 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
41 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
54 public final class RestCodec {
56 private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
61 public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
62 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
63 return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
66 @SuppressWarnings("rawtypes")
67 public static final class ObjectCodec implements Codec<Object, Object> {
69 private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
71 public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
72 private final Codec instanceIdentifier;
73 private final Codec identityrefCodec;
75 private final TypeDefinition<?> type;
77 private final SchemaContext schemaContext;
79 private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
80 final SchemaContext schemaContext) {
81 this.schemaContext = schemaContext;
82 this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
83 if (this.type instanceof IdentityrefTypeDefinition) {
84 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
86 this.identityrefCodec = null;
88 if (this.type instanceof InstanceIdentifierTypeDefinition) {
89 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
91 this.instanceIdentifier = null;
95 @SuppressWarnings("unchecked")
97 public Object deserialize(final Object input) {
99 if (this.type instanceof IdentityrefTypeDefinition) {
100 if (input instanceof IdentityValuesDTO) {
101 return this.identityrefCodec.deserialize(input);
103 if (LOG.isDebugEnabled()) {
105 "Value is not instance of IdentityrefTypeDefinition but is {}. "
106 + "Therefore NULL is used as translation of - {}",
107 input == null ? "null" : input.getClass(), String.valueOf(input));
110 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
111 if (input instanceof IdentityValuesDTO) {
112 return this.instanceIdentifier.deserialize(input);
114 final StringModuleInstanceIdentifierCodec codec =
115 new StringModuleInstanceIdentifierCodec(schemaContext);
116 return codec.deserialize((String) input);
119 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
120 TypeDefinitionAwareCodec.from(this.type);
121 if (typeAwarecodec != null) {
122 if (input instanceof IdentityValuesDTO) {
123 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
125 return typeAwarecodec.deserialize(String.valueOf(input));
127 LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
128 + "\" is not implemented yet.");
132 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
134 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
140 @SuppressWarnings("unchecked")
142 public Object serialize(final Object input) {
144 if (this.type instanceof IdentityrefTypeDefinition) {
145 return this.identityrefCodec.serialize(input);
146 } else if (this.type instanceof LeafrefTypeDefinition) {
147 return LEAFREF_DEFAULT_CODEC.serialize(input);
148 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
149 return this.instanceIdentifier.serialize(input);
151 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
152 TypeDefinitionAwareCodec.from(this.type);
153 if (typeAwarecodec != null) {
154 return typeAwarecodec.serialize(input);
156 if (LOG.isDebugEnabled()) {
157 LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
158 + "\" is not implemented yet.");
163 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
165 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
173 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
175 private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
177 private final DOMMountPoint mountPoint;
179 private final SchemaContext schemaContext;
181 public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
182 this.mountPoint = mountPoint;
183 this.schemaContext = schemaContext;
187 public IdentityValuesDTO serialize(final QName data) {
188 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
192 public QName deserialize(final IdentityValuesDTO data) {
193 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
194 final Module module =
195 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
196 if (module == null) {
197 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
198 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
202 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
207 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
210 public String serialize(final Object data) {
211 return String.valueOf(data);
215 public Object deserialize(final String data) {
221 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
222 private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
223 private final DOMMountPoint mountPoint;
224 private final SchemaContext schemaContext;
226 public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
227 this.mountPoint = mountPoint;
228 this.schemaContext = schemaContext;
232 public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
233 final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
234 for (final PathArgument pathArgument : data.getPathArguments()) {
235 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
236 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
237 final List<Predicate> predicates =
238 keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).getKeyValues());
239 identityValue.setPredicates(predicates);
240 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
241 final List<Predicate> predicates = new ArrayList<>();
242 final String value = String.valueOf(((NodeWithValue) pathArgument).getValue());
243 predicates.add(new Predicate(null, value));
244 identityValue.setPredicates(predicates);
246 identityValuesDTO.add(identityValue);
248 return identityValuesDTO;
251 @SuppressFBWarnings(value = {"NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
252 "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE"}, justification = "Unrecognised NullableDecl")
254 public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
255 final List<PathArgument> result = new ArrayList<>();
256 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
257 final Module module =
258 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
259 if (module == null) {
260 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
261 valueWithNamespace.getNamespace());
262 LOG.info("Instance-identifier will be translated as NULL for data - {}",
263 String.valueOf(valueWithNamespace.getValue()));
267 DataNodeContainer parentContainer = module;
268 final List<IdentityValue> identities = data.getValuesWithNamespaces();
269 for (int i = 0; i < identities.size(); i++) {
270 final IdentityValue identityValue = identities.get(i);
272 resolveValidNamespace(identityValue.getNamespace(), this.mountPoint, schemaContext);
273 final DataSchemaNode node = findInstanceDataChildByNameAndNamespace(
274 parentContainer, identityValue.getValue(), validNamespace);
276 LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
277 LOG.info("Instance-identifier will be translated as NULL for data - {}",
278 String.valueOf(identityValue.getValue()));
281 final QName qName = node.getQName();
282 PathArgument pathArgument = null;
283 if (identityValue.getPredicates().isEmpty()) {
284 pathArgument = new NodeIdentifier(qName);
286 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
287 final Predicate leafListPredicate = identityValue.getPredicates().get(0);
288 if (!leafListPredicate.isLeafList()) {
289 LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
290 LOG.info("Instance-identifier will be translated as NULL for data - {}",
291 String.valueOf(identityValue.getValue()));
294 pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
295 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
296 final DataNodeContainer listNode = (DataNodeContainer) node;
297 final Map<QName, Object> predicatesMap = new HashMap<>();
298 for (final Predicate predicate : identityValue.getPredicates()) {
299 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
301 final DataSchemaNode listKey = findInstanceDataChildByNameAndNamespace(listNode,
302 predicate.getName().getValue(), validNamespace);
303 predicatesMap.put(listKey.getQName(), predicate.getValue());
305 pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
307 LOG.info("Node {} is not List or Leaf-list.", node);
308 LOG.info("Instance-identifier will be translated as NULL for data - {}",
309 String.valueOf(identityValue.getValue()));
313 result.add(pathArgument);
314 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
316 if (node instanceof DataNodeContainer) {
317 parentContainer = (DataNodeContainer) node;
319 LOG.info("Node {} isn't instance of DataNodeContainer", node);
320 LOG.info("Instance-identifier will be translated as NULL for data - {}",
321 String.valueOf(identityValue.getValue()));
327 return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
330 private static List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
331 final List<Predicate> result = new ArrayList<>();
332 for (final Entry<QName, Object> entry : keyValues.entrySet()) {
333 final QName qualifiedName = entry.getKey();
334 final Object value = entry.getValue();
335 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
340 private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
341 if (qualifiedName != null) {
342 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
348 private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
349 final SchemaContext schemaContext) {
350 final URI validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext);
351 Module module = null;
352 if (mountPoint != null) {
353 module = mountPoint.getSchemaContext().findModules(validNamespace).iterator().next();
355 module = schemaContext.findModules(validNamespace).iterator().next();
357 if (module == null) {
358 LOG.info("Module for namespace " + validNamespace + " wasn't found.");
364 private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
365 final SchemaContext schemaContext) {
367 if (mountPoint != null) {
368 validNamespace = findFirstModuleByName(mountPoint.getSchemaContext(), namespace);
370 validNamespace = findFirstModuleByName(schemaContext, namespace);
372 if (validNamespace == null) {
373 validNamespace = URI.create(namespace);
376 return validNamespace;
379 private static URI findFirstModuleByName(final SchemaContext schemaContext, final String name) {
380 for (final Module module : schemaContext.getModules()) {
381 if (module.getName().equals(name)) {
382 return module.getNamespace();
388 private static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
389 final String name, final URI namespace) {
390 Preconditions.checkNotNull(namespace);
392 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
393 node -> namespace.equals(node.getQName().getNamespace()));
394 return Iterables.getFirst(result, null);
397 private static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
399 Preconditions.checkNotNull(container);
400 Preconditions.checkNotNull(name);
402 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
403 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
404 return instantiatedDataNodeContainers;
407 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
408 final DataNodeContainer container, final String name) {
410 final Iterable<DataSchemaNode> nodes =
411 Iterables.filter(container.getChildNodes(), node -> name.equals(node.getQName().getLocalName()));
413 // Can't combine this loop with the filter above because the filter is
414 // lazily-applied by Iterables.filter.
415 for (final DataSchemaNode potentialNode : nodes) {
416 if (isInstantiatedDataSchema(potentialNode)) {
417 potentialSchemaNodes.add(potentialNode);
421 final Iterable<ChoiceSchemaNode> choiceNodes =
422 Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
423 final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
424 choice -> choice.getCases().values());
425 for (final CaseSchemaNode caze : Iterables.concat(map)) {
426 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
430 private static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
431 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
432 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
433 || node instanceof AnyXmlSchemaNode;