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;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.HashMap;
18 import java.util.List;
20 import java.util.Map.Entry;
22 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
23 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
24 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
25 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
26 import org.opendaylight.restconf.common.util.RestUtil;
27 import org.opendaylight.yangtools.concepts.IllegalArgumentCodec;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
35 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
36 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
37 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
38 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.Module;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 public final class RestCodec {
58 private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
63 // FIXME: IllegalArgumentCodec is not quite accurate
64 public static IllegalArgumentCodec<Object, Object> from(final TypeDefinition<?> typeDefinition,
65 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
66 return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
69 @SuppressWarnings("rawtypes")
70 public static final class ObjectCodec implements IllegalArgumentCodec<Object, Object> {
72 private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
74 public static final IllegalArgumentCodec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
75 private final IllegalArgumentCodec instanceIdentifier;
76 private final IllegalArgumentCodec identityrefCodec;
78 private final TypeDefinition<?> type;
80 private final SchemaContext schemaContext;
82 private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
83 final SchemaContext schemaContext) {
84 this.schemaContext = schemaContext;
85 this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
86 if (this.type instanceof IdentityrefTypeDefinition) {
87 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
89 this.identityrefCodec = null;
91 if (this.type instanceof InstanceIdentifierTypeDefinition) {
92 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
94 this.instanceIdentifier = null;
98 @SuppressWarnings("unchecked")
100 public Object deserialize(final Object input) {
102 if (this.type instanceof IdentityrefTypeDefinition) {
103 if (input instanceof IdentityValuesDTO) {
104 return this.identityrefCodec.deserialize(input);
106 if (LOG.isDebugEnabled()) {
108 "Value is not instance of IdentityrefTypeDefinition but is {}. "
109 + "Therefore NULL is used as translation of - {}",
110 input == null ? "null" : input.getClass(), String.valueOf(input));
113 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
114 if (input instanceof IdentityValuesDTO) {
115 return this.instanceIdentifier.deserialize(input);
117 final StringModuleInstanceIdentifierCodec codec =
118 new StringModuleInstanceIdentifierCodec(schemaContext);
119 return codec.deserialize((String) input);
122 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
123 TypeDefinitionAwareCodec.from(this.type);
124 if (typeAwarecodec != null) {
125 if (input instanceof IdentityValuesDTO) {
126 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
128 return typeAwarecodec.deserialize(String.valueOf(input));
130 LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
134 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
135 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
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 \"{}\" is not implemented yet.", type.getQName().getLocalName());
162 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
163 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
169 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
171 private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
173 private final DOMMountPoint mountPoint;
175 private final SchemaContext schemaContext;
177 public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
178 this.mountPoint = mountPoint;
179 this.schemaContext = schemaContext;
183 public IdentityValuesDTO serialize(final QName data) {
184 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
188 public QName deserialize(final IdentityValuesDTO data) {
189 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
190 final Module module =
191 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
192 if (module == null) {
193 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
194 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
198 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
203 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
206 public String serialize(final Object data) {
207 return String.valueOf(data);
211 public Object deserialize(final String data) {
217 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
218 private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
219 private final DOMMountPoint mountPoint;
220 private final SchemaContext schemaContext;
222 public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
223 this.mountPoint = mountPoint;
224 this.schemaContext = schemaContext;
228 public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
229 final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
230 for (final PathArgument pathArgument : data.getPathArguments()) {
231 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
232 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
233 final List<Predicate> predicates =
234 keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).entrySet());
235 identityValue.setPredicates(predicates);
236 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
237 final List<Predicate> predicates = new ArrayList<>();
238 final String value = String.valueOf(((NodeWithValue<?>) pathArgument).getValue());
239 predicates.add(new Predicate(null, value));
240 identityValue.setPredicates(predicates);
242 identityValuesDTO.add(identityValue);
244 return identityValuesDTO;
247 @SuppressFBWarnings(value = {"NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
248 "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE"}, justification = "Unrecognised NullableDecl")
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 = NodeIdentifierWithPredicates.of(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 Set<Entry<QName, Object>> keyValues) {
327 final List<Predicate> result = new ArrayList<>();
328 for (final Entry<QName, Object> entry : keyValues) {
329 final QName qualifiedName = entry.getKey();
330 final Object value = entry.getValue();
331 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
336 private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
337 if (qualifiedName != null) {
338 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
344 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
345 justification = "https://github.com/spotbugs/spotbugs/issues/811")
346 private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
347 final SchemaContext schemaContext) {
348 final URI validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext);
349 Module module = null;
350 if (mountPoint != null) {
351 module = mountPoint.getSchemaContext().findModules(validNamespace).iterator().next();
353 module = schemaContext.findModules(validNamespace).iterator().next();
355 if (module == null) {
356 LOG.info("Module for namespace {} was not found.", validNamespace);
362 private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
363 final SchemaContext schemaContext) {
365 if (mountPoint != null) {
366 validNamespace = findFirstModuleByName(mountPoint.getSchemaContext(), namespace);
368 validNamespace = findFirstModuleByName(schemaContext, namespace);
370 if (validNamespace == null) {
371 validNamespace = URI.create(namespace);
374 return validNamespace;
377 private static URI findFirstModuleByName(final SchemaContext schemaContext, final String name) {
378 for (final Module module : schemaContext.getModules()) {
379 if (module.getName().equals(name)) {
380 return module.getNamespace();
386 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
387 justification = "https://github.com/spotbugs/spotbugs/issues/811")
388 private static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
389 final String name, final URI namespace) {
390 requireNonNull(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 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
400 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
401 requireNonNull(name));
402 return instantiatedDataNodeContainers;
405 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
406 final DataNodeContainer container, final String name) {
408 final Iterable<? extends DataSchemaNode> nodes =
409 Iterables.filter(container.getChildNodes(), node -> name.equals(node.getQName().getLocalName()));
411 // Can't combine this loop with the filter above because the filter is
412 // lazily-applied by Iterables.filter.
413 for (final DataSchemaNode potentialNode : nodes) {
414 if (isInstantiatedDataSchema(potentialNode)) {
415 potentialSchemaNodes.add(potentialNode);
419 final Iterable<ChoiceSchemaNode> choiceNodes =
420 Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
421 final Iterable<Collection<? extends CaseSchemaNode>> map = Iterables.transform(choiceNodes,
422 choice -> choice.getCases());
423 for (final CaseSchemaNode caze : Iterables.concat(map)) {
424 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
428 private static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
429 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
430 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
431 || node instanceof AnyxmlSchemaNode;