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 static java.util.Objects.requireNonNull;
12 import com.google.common.collect.Iterables;
13 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 java.util.Optional;
22 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
23 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
24 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
25 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
26 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
27 import org.opendaylight.restconf.common.util.RestUtil;
28 import org.opendaylight.yangtools.concepts.IllegalArgumentCodec;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.XMLNamespace;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
37 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
38 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
39 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
40 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
47 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.Module;
51 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
52 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 public final class RestCodec {
61 private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
66 // FIXME: IllegalArgumentCodec is not quite accurate
67 public static IllegalArgumentCodec<Object, Object> from(final TypeDefinition<?> typeDefinition,
68 final DOMMountPoint mountPoint, final EffectiveModelContext schemaContext) {
69 return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
72 @SuppressWarnings("rawtypes")
73 public static final class ObjectCodec implements IllegalArgumentCodec<Object, Object> {
75 private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
77 public static final IllegalArgumentCodec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
78 private final IllegalArgumentCodec instanceIdentifier;
79 private final IllegalArgumentCodec identityrefCodec;
81 private final TypeDefinition<?> type;
83 private final EffectiveModelContext schemaContext;
85 private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
86 final EffectiveModelContext schemaContext) {
87 this.schemaContext = schemaContext;
88 this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
89 if (this.type instanceof IdentityrefTypeDefinition) {
90 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
92 this.identityrefCodec = null;
94 if (this.type instanceof InstanceIdentifierTypeDefinition) {
95 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
97 this.instanceIdentifier = null;
101 @SuppressWarnings("unchecked")
103 public Object deserialize(final Object input) {
105 if (this.type instanceof IdentityrefTypeDefinition) {
106 if (input instanceof IdentityValuesDTO) {
107 return this.identityrefCodec.deserialize(input);
109 if (LOG.isDebugEnabled()) {
111 "Value is not instance of IdentityrefTypeDefinition but is {}. "
112 + "Therefore NULL is used as translation of - {}",
113 input == null ? "null" : input.getClass(), String.valueOf(input));
116 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
117 if (input instanceof IdentityValuesDTO) {
118 return this.instanceIdentifier.deserialize(input);
120 final StringModuleInstanceIdentifierCodec codec =
121 new StringModuleInstanceIdentifierCodec(schemaContext);
122 return codec.deserialize((String) input);
125 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
126 TypeDefinitionAwareCodec.from(this.type);
127 if (typeAwarecodec != null) {
128 if (input instanceof IdentityValuesDTO) {
129 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
131 return typeAwarecodec.deserialize(String.valueOf(input));
133 LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
137 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
138 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
143 @SuppressWarnings("unchecked")
145 public Object serialize(final Object input) {
147 if (this.type instanceof IdentityrefTypeDefinition) {
148 return this.identityrefCodec.serialize(input);
149 } else if (this.type instanceof LeafrefTypeDefinition) {
150 return LEAFREF_DEFAULT_CODEC.serialize(input);
151 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
152 return this.instanceIdentifier.serialize(input);
154 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
155 TypeDefinitionAwareCodec.from(this.type);
156 if (typeAwarecodec != null) {
157 return typeAwarecodec.serialize(input);
159 if (LOG.isDebugEnabled()) {
160 LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
165 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
166 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
172 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
174 private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
176 private final DOMMountPoint mountPoint;
178 private final SchemaContext schemaContext;
180 public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
181 this.mountPoint = mountPoint;
182 this.schemaContext = schemaContext;
186 public IdentityValuesDTO serialize(final QName data) {
187 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
191 public QName deserialize(final IdentityValuesDTO data) {
192 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
193 final Module module =
194 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
195 if (module == null) {
196 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
197 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
201 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
206 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
209 public String serialize(final Object data) {
210 return String.valueOf(data);
214 public Object deserialize(final String data) {
220 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
221 private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
222 private final DOMMountPoint mountPoint;
223 private final SchemaContext schemaContext;
225 public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
226 this.mountPoint = mountPoint;
227 this.schemaContext = schemaContext;
231 public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
232 final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
233 for (final PathArgument pathArgument : data.getPathArguments()) {
234 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
235 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
236 final List<Predicate> predicates =
237 keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).entrySet());
238 identityValue.setPredicates(predicates);
239 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
240 final List<Predicate> predicates = new ArrayList<>();
241 final String value = String.valueOf(((NodeWithValue<?>) pathArgument).getValue());
242 predicates.add(new Predicate(null, value));
243 identityValue.setPredicates(predicates);
245 identityValuesDTO.add(identityValue);
247 return identityValuesDTO;
250 @SuppressFBWarnings(value = {
251 "NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
252 "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE"
253 }, justification = "Unrecognised NullableDecl")
255 public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
256 final List<PathArgument> result = new ArrayList<>();
257 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
258 final Module module =
259 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
260 if (module == null) {
261 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
262 valueWithNamespace.getNamespace());
263 LOG.info("Instance-identifier will be translated as NULL for data - {}",
264 String.valueOf(valueWithNamespace.getValue()));
268 DataNodeContainer parentContainer = module;
269 final List<IdentityValue> identities = data.getValuesWithNamespaces();
270 for (int i = 0; i < identities.size(); i++) {
271 final IdentityValue identityValue = identities.get(i);
272 XMLNamespace validNamespace =
273 resolveValidNamespace(identityValue.getNamespace(), this.mountPoint, schemaContext);
274 final DataSchemaNode node = findInstanceDataChildByNameAndNamespace(
275 parentContainer, identityValue.getValue(), validNamespace);
277 LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
278 LOG.info("Instance-identifier will be translated as NULL for data - {}",
279 String.valueOf(identityValue.getValue()));
282 final QName qName = node.getQName();
283 PathArgument pathArgument = null;
284 if (identityValue.getPredicates().isEmpty()) {
285 pathArgument = new NodeIdentifier(qName);
287 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
288 final Predicate leafListPredicate = identityValue.getPredicates().get(0);
289 if (!leafListPredicate.isLeafList()) {
290 LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
291 LOG.info("Instance-identifier will be translated as NULL for data - {}",
292 String.valueOf(identityValue.getValue()));
295 pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
296 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
297 final DataNodeContainer listNode = (DataNodeContainer) node;
298 final Map<QName, Object> predicatesMap = new HashMap<>();
299 for (final Predicate predicate : identityValue.getPredicates()) {
300 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
302 final DataSchemaNode listKey = findInstanceDataChildByNameAndNamespace(listNode,
303 predicate.getName().getValue(), validNamespace);
304 predicatesMap.put(listKey.getQName(), predicate.getValue());
306 pathArgument = NodeIdentifierWithPredicates.of(qName, predicatesMap);
308 LOG.info("Node {} is not List or Leaf-list.", node);
309 LOG.info("Instance-identifier will be translated as NULL for data - {}",
310 String.valueOf(identityValue.getValue()));
314 result.add(pathArgument);
315 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
317 if (node instanceof DataNodeContainer) {
318 parentContainer = (DataNodeContainer) node;
320 LOG.info("Node {} isn't instance of DataNodeContainer", node);
321 LOG.info("Instance-identifier will be translated as NULL for data - {}",
322 String.valueOf(identityValue.getValue()));
328 return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
331 private static List<Predicate> keyValuesToPredicateList(final Set<Entry<QName, Object>> keyValues) {
332 final List<Predicate> result = new ArrayList<>();
333 for (final Entry<QName, Object> entry : keyValues) {
334 final QName qualifiedName = entry.getKey();
335 final Object value = entry.getValue();
336 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
341 private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
342 if (qualifiedName != null) {
343 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
349 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
350 justification = "https://github.com/spotbugs/spotbugs/issues/811")
351 private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
352 final SchemaContext schemaContext) {
353 final XMLNamespace validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext);
354 Module module = null;
355 if (mountPoint != null) {
356 module = modelContext(mountPoint).findModules(validNamespace).iterator().next();
358 module = schemaContext.findModules(validNamespace).iterator().next();
360 if (module == null) {
361 LOG.info("Module for namespace {} was not found.", validNamespace);
367 private static XMLNamespace resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
368 final SchemaContext schemaContext) {
369 XMLNamespace validNamespace;
370 if (mountPoint != null) {
371 validNamespace = findFirstModuleByName(modelContext(mountPoint), namespace);
373 validNamespace = findFirstModuleByName(schemaContext, namespace);
375 if (validNamespace == null) {
376 validNamespace = XMLNamespace.of(namespace);
379 return validNamespace;
382 private static XMLNamespace findFirstModuleByName(final SchemaContext schemaContext, final String name) {
383 for (final Module module : schemaContext.getModules()) {
384 if (module.getName().equals(name)) {
385 return module.getNamespace();
391 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
392 justification = "https://github.com/spotbugs/spotbugs/issues/811")
393 private static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
394 final String name, final XMLNamespace namespace) {
395 requireNonNull(namespace);
397 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
398 node -> namespace.equals(node.getQName().getNamespace()));
399 return Iterables.getFirst(result, null);
402 private static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
404 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
405 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
406 requireNonNull(name));
407 return instantiatedDataNodeContainers;
410 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
411 final DataNodeContainer container, final String name) {
413 final Iterable<? extends DataSchemaNode> nodes =
414 Iterables.filter(container.getChildNodes(), node -> name.equals(node.getQName().getLocalName()));
416 // Can't combine this loop with the filter above because the filter is
417 // lazily-applied by Iterables.filter.
418 for (final DataSchemaNode potentialNode : nodes) {
419 if (isInstantiatedDataSchema(potentialNode)) {
420 potentialSchemaNodes.add(potentialNode);
424 final Iterable<ChoiceSchemaNode> choiceNodes =
425 Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
426 final Iterable<Collection<? extends CaseSchemaNode>> map = Iterables.transform(choiceNodes,
427 ChoiceSchemaNode::getCases);
428 for (final CaseSchemaNode caze : Iterables.concat(map)) {
429 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
433 private static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
434 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
435 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
436 || node instanceof AnyxmlSchemaNode;
439 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
440 return mountPoint.getService(DOMSchemaService.class)
441 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))