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;
21 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
22 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
23 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
24 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
25 import org.opendaylight.restconf.common.util.RestUtil;
26 import org.opendaylight.yangtools.concepts.Codec;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
34 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
35 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
36 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
37 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
55 public final class RestCodec {
57 private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
62 public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
63 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
64 return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
67 @SuppressWarnings("rawtypes")
68 public static final class ObjectCodec implements Codec<Object, Object> {
70 private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
72 public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
73 private final Codec instanceIdentifier;
74 private final Codec identityrefCodec;
76 private final TypeDefinition<?> type;
78 private final SchemaContext schemaContext;
80 private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
81 final SchemaContext schemaContext) {
82 this.schemaContext = schemaContext;
83 this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
84 if (this.type instanceof IdentityrefTypeDefinition) {
85 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
87 this.identityrefCodec = null;
89 if (this.type instanceof InstanceIdentifierTypeDefinition) {
90 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
92 this.instanceIdentifier = null;
96 @SuppressWarnings("unchecked")
98 public Object deserialize(final Object input) {
100 if (this.type instanceof IdentityrefTypeDefinition) {
101 if (input instanceof IdentityValuesDTO) {
102 return this.identityrefCodec.deserialize(input);
104 if (LOG.isDebugEnabled()) {
106 "Value is not instance of IdentityrefTypeDefinition but is {}. "
107 + "Therefore NULL is used as translation of - {}",
108 input == null ? "null" : input.getClass(), String.valueOf(input));
111 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
112 if (input instanceof IdentityValuesDTO) {
113 return this.instanceIdentifier.deserialize(input);
115 final StringModuleInstanceIdentifierCodec codec =
116 new StringModuleInstanceIdentifierCodec(schemaContext);
117 return codec.deserialize((String) input);
120 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
121 TypeDefinitionAwareCodec.from(this.type);
122 if (typeAwarecodec != null) {
123 if (input instanceof IdentityValuesDTO) {
124 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
126 return typeAwarecodec.deserialize(String.valueOf(input));
128 LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
132 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
133 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
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 \"{}\" is not implemented yet.", type.getQName().getLocalName());
160 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
161 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
167 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
169 private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
171 private final DOMMountPoint mountPoint;
173 private final SchemaContext schemaContext;
175 public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
176 this.mountPoint = mountPoint;
177 this.schemaContext = schemaContext;
181 public IdentityValuesDTO serialize(final QName data) {
182 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
186 public QName deserialize(final IdentityValuesDTO data) {
187 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
188 final Module module =
189 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
190 if (module == null) {
191 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
192 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
196 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
201 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
204 public String serialize(final Object data) {
205 return String.valueOf(data);
209 public Object deserialize(final String data) {
215 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
216 private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
217 private final DOMMountPoint mountPoint;
218 private final SchemaContext schemaContext;
220 public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
221 this.mountPoint = mountPoint;
222 this.schemaContext = schemaContext;
226 public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
227 final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
228 for (final PathArgument pathArgument : data.getPathArguments()) {
229 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
230 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
231 final List<Predicate> predicates =
232 keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).entrySet());
233 identityValue.setPredicates(predicates);
234 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
235 final List<Predicate> predicates = new ArrayList<>();
236 final String value = String.valueOf(((NodeWithValue<?>) pathArgument).getValue());
237 predicates.add(new Predicate(null, value));
238 identityValue.setPredicates(predicates);
240 identityValuesDTO.add(identityValue);
242 return identityValuesDTO;
245 @SuppressFBWarnings(value = {"NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
246 "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE"}, justification = "Unrecognised NullableDecl")
248 public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
249 final List<PathArgument> result = new ArrayList<>();
250 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
251 final Module module =
252 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
253 if (module == null) {
254 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
255 valueWithNamespace.getNamespace());
256 LOG.info("Instance-identifier will be translated as NULL for data - {}",
257 String.valueOf(valueWithNamespace.getValue()));
261 DataNodeContainer parentContainer = module;
262 final List<IdentityValue> identities = data.getValuesWithNamespaces();
263 for (int i = 0; i < identities.size(); i++) {
264 final IdentityValue identityValue = identities.get(i);
266 resolveValidNamespace(identityValue.getNamespace(), this.mountPoint, schemaContext);
267 final DataSchemaNode node = findInstanceDataChildByNameAndNamespace(
268 parentContainer, identityValue.getValue(), validNamespace);
270 LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
271 LOG.info("Instance-identifier will be translated as NULL for data - {}",
272 String.valueOf(identityValue.getValue()));
275 final QName qName = node.getQName();
276 PathArgument pathArgument = null;
277 if (identityValue.getPredicates().isEmpty()) {
278 pathArgument = new NodeIdentifier(qName);
280 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
281 final Predicate leafListPredicate = identityValue.getPredicates().get(0);
282 if (!leafListPredicate.isLeafList()) {
283 LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
284 LOG.info("Instance-identifier will be translated as NULL for data - {}",
285 String.valueOf(identityValue.getValue()));
288 pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
289 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
290 final DataNodeContainer listNode = (DataNodeContainer) node;
291 final Map<QName, Object> predicatesMap = new HashMap<>();
292 for (final Predicate predicate : identityValue.getPredicates()) {
293 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
295 final DataSchemaNode listKey = findInstanceDataChildByNameAndNamespace(listNode,
296 predicate.getName().getValue(), validNamespace);
297 predicatesMap.put(listKey.getQName(), predicate.getValue());
299 pathArgument = NodeIdentifierWithPredicates.of(qName, predicatesMap);
301 LOG.info("Node {} is not List or Leaf-list.", node);
302 LOG.info("Instance-identifier will be translated as NULL for data - {}",
303 String.valueOf(identityValue.getValue()));
307 result.add(pathArgument);
308 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
310 if (node instanceof DataNodeContainer) {
311 parentContainer = (DataNodeContainer) node;
313 LOG.info("Node {} isn't instance of DataNodeContainer", node);
314 LOG.info("Instance-identifier will be translated as NULL for data - {}",
315 String.valueOf(identityValue.getValue()));
321 return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
324 private static List<Predicate> keyValuesToPredicateList(final Set<Entry<QName, Object>> keyValues) {
325 final List<Predicate> result = new ArrayList<>();
326 for (final Entry<QName, Object> entry : keyValues) {
327 final QName qualifiedName = entry.getKey();
328 final Object value = entry.getValue();
329 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
334 private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
335 if (qualifiedName != null) {
336 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
342 private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
343 final SchemaContext schemaContext) {
344 final URI validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext);
345 Module module = null;
346 if (mountPoint != null) {
347 module = mountPoint.getSchemaContext().findModules(validNamespace).iterator().next();
349 module = schemaContext.findModules(validNamespace).iterator().next();
351 if (module == null) {
352 LOG.info("Module for namespace {} was not found.", validNamespace);
358 private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
359 final SchemaContext schemaContext) {
361 if (mountPoint != null) {
362 validNamespace = findFirstModuleByName(mountPoint.getSchemaContext(), 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<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
418 choice -> choice.getCases().values());
419 for (final CaseSchemaNode caze : Iterables.concat(map)) {
420 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
424 private static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
425 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
426 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
427 || node instanceof AnyXmlSchemaNode;