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.Codec;
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 public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
64 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
65 return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
68 @SuppressWarnings("rawtypes")
69 public static final class ObjectCodec implements Codec<Object, Object> {
71 private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
73 public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
74 private final Codec instanceIdentifier;
75 private final Codec identityrefCodec;
77 private final TypeDefinition<?> type;
79 private final SchemaContext schemaContext;
81 private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
82 final SchemaContext schemaContext) {
83 this.schemaContext = schemaContext;
84 this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
85 if (this.type instanceof IdentityrefTypeDefinition) {
86 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
88 this.identityrefCodec = null;
90 if (this.type instanceof InstanceIdentifierTypeDefinition) {
91 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
93 this.instanceIdentifier = null;
97 @SuppressWarnings("unchecked")
99 public Object deserialize(final Object input) {
101 if (this.type instanceof IdentityrefTypeDefinition) {
102 if (input instanceof IdentityValuesDTO) {
103 return this.identityrefCodec.deserialize(input);
105 if (LOG.isDebugEnabled()) {
107 "Value is not instance of IdentityrefTypeDefinition but is {}. "
108 + "Therefore NULL is used as translation of - {}",
109 input == null ? "null" : input.getClass(), String.valueOf(input));
112 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
113 if (input instanceof IdentityValuesDTO) {
114 return this.instanceIdentifier.deserialize(input);
116 final StringModuleInstanceIdentifierCodec codec =
117 new StringModuleInstanceIdentifierCodec(schemaContext);
118 return codec.deserialize((String) input);
121 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
122 TypeDefinitionAwareCodec.from(this.type);
123 if (typeAwarecodec != null) {
124 if (input instanceof IdentityValuesDTO) {
125 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
127 return typeAwarecodec.deserialize(String.valueOf(input));
129 LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
133 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
134 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
139 @SuppressWarnings("unchecked")
141 public Object serialize(final Object input) {
143 if (this.type instanceof IdentityrefTypeDefinition) {
144 return this.identityrefCodec.serialize(input);
145 } else if (this.type instanceof LeafrefTypeDefinition) {
146 return LEAFREF_DEFAULT_CODEC.serialize(input);
147 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
148 return this.instanceIdentifier.serialize(input);
150 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
151 TypeDefinitionAwareCodec.from(this.type);
152 if (typeAwarecodec != null) {
153 return typeAwarecodec.serialize(input);
155 if (LOG.isDebugEnabled()) {
156 LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
161 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
162 LOG.error("ClassCastException was thrown when codec is invoked with parameter {}", input, e);
168 public static class IdentityrefCodecImpl implements IdentityrefCodec<IdentityValuesDTO> {
170 private static final Logger LOG = LoggerFactory.getLogger(IdentityrefCodecImpl.class);
172 private final DOMMountPoint mountPoint;
174 private final SchemaContext schemaContext;
176 public IdentityrefCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
177 this.mountPoint = mountPoint;
178 this.schemaContext = schemaContext;
182 public IdentityValuesDTO serialize(final QName data) {
183 return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), null, null);
187 public QName deserialize(final IdentityValuesDTO data) {
188 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
189 final Module module =
190 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
191 if (module == null) {
192 LOG.info("Module was not found for namespace {}", valueWithNamespace.getNamespace());
193 LOG.info("Idenetityref will be translated as NULL for data - {}", String.valueOf(valueWithNamespace));
197 return QName.create(module.getNamespace(), module.getRevision(), valueWithNamespace.getValue());
202 public static class LeafrefCodecImpl implements LeafrefCodec<String> {
205 public String serialize(final Object data) {
206 return String.valueOf(data);
210 public Object deserialize(final String data) {
216 public static class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec<IdentityValuesDTO> {
217 private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
218 private final DOMMountPoint mountPoint;
219 private final SchemaContext schemaContext;
221 public InstanceIdentifierCodecImpl(final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
222 this.mountPoint = mountPoint;
223 this.schemaContext = schemaContext;
227 public IdentityValuesDTO serialize(final YangInstanceIdentifier data) {
228 final IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
229 for (final PathArgument pathArgument : data.getPathArguments()) {
230 final IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
231 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
232 final List<Predicate> predicates =
233 keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument).entrySet());
234 identityValue.setPredicates(predicates);
235 } else if (pathArgument instanceof NodeWithValue && identityValue != null) {
236 final List<Predicate> predicates = new ArrayList<>();
237 final String value = String.valueOf(((NodeWithValue<?>) pathArgument).getValue());
238 predicates.add(new Predicate(null, value));
239 identityValue.setPredicates(predicates);
241 identityValuesDTO.add(identityValue);
243 return identityValuesDTO;
246 @SuppressFBWarnings(value = {"NP_PARAMETER_MUST_BE_NONNULL_BUT_MARKED_AS_NULLABLE",
247 "RCN_REDUNDANT_NULLCHECK_OF_NONNULL_VALUE"}, justification = "Unrecognised NullableDecl")
249 public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
250 final List<PathArgument> result = new ArrayList<>();
251 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
252 final Module module =
253 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
254 if (module == null) {
255 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
256 valueWithNamespace.getNamespace());
257 LOG.info("Instance-identifier will be translated as NULL for data - {}",
258 String.valueOf(valueWithNamespace.getValue()));
262 DataNodeContainer parentContainer = module;
263 final List<IdentityValue> identities = data.getValuesWithNamespaces();
264 for (int i = 0; i < identities.size(); i++) {
265 final IdentityValue identityValue = identities.get(i);
267 resolveValidNamespace(identityValue.getNamespace(), this.mountPoint, schemaContext);
268 final DataSchemaNode node = findInstanceDataChildByNameAndNamespace(
269 parentContainer, identityValue.getValue(), validNamespace);
271 LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
272 LOG.info("Instance-identifier will be translated as NULL for data - {}",
273 String.valueOf(identityValue.getValue()));
276 final QName qName = node.getQName();
277 PathArgument pathArgument = null;
278 if (identityValue.getPredicates().isEmpty()) {
279 pathArgument = new NodeIdentifier(qName);
281 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
282 final Predicate leafListPredicate = identityValue.getPredicates().get(0);
283 if (!leafListPredicate.isLeafList()) {
284 LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
285 LOG.info("Instance-identifier will be translated as NULL for data - {}",
286 String.valueOf(identityValue.getValue()));
289 pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
290 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
291 final DataNodeContainer listNode = (DataNodeContainer) node;
292 final Map<QName, Object> predicatesMap = new HashMap<>();
293 for (final Predicate predicate : identityValue.getPredicates()) {
294 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
296 final DataSchemaNode listKey = findInstanceDataChildByNameAndNamespace(listNode,
297 predicate.getName().getValue(), validNamespace);
298 predicatesMap.put(listKey.getQName(), predicate.getValue());
300 pathArgument = NodeIdentifierWithPredicates.of(qName, predicatesMap);
302 LOG.info("Node {} is not List or Leaf-list.", node);
303 LOG.info("Instance-identifier will be translated as NULL for data - {}",
304 String.valueOf(identityValue.getValue()));
308 result.add(pathArgument);
309 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
311 if (node instanceof DataNodeContainer) {
312 parentContainer = (DataNodeContainer) node;
314 LOG.info("Node {} isn't instance of DataNodeContainer", node);
315 LOG.info("Instance-identifier will be translated as NULL for data - {}",
316 String.valueOf(identityValue.getValue()));
322 return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
325 private static List<Predicate> keyValuesToPredicateList(final Set<Entry<QName, Object>> keyValues) {
326 final List<Predicate> result = new ArrayList<>();
327 for (final Entry<QName, Object> entry : keyValues) {
328 final QName qualifiedName = entry.getKey();
329 final Object value = entry.getValue();
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 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
344 justification = "https://github.com/spotbugs/spotbugs/issues/811")
345 private static Module getModuleByNamespace(final String namespace, final DOMMountPoint mountPoint,
346 final SchemaContext schemaContext) {
347 final URI validNamespace = resolveValidNamespace(namespace, mountPoint, schemaContext);
348 Module module = null;
349 if (mountPoint != null) {
350 module = mountPoint.getSchemaContext().findModules(validNamespace).iterator().next();
352 module = schemaContext.findModules(validNamespace).iterator().next();
354 if (module == null) {
355 LOG.info("Module for namespace {} was not found.", validNamespace);
361 private static URI resolveValidNamespace(final String namespace, final DOMMountPoint mountPoint,
362 final SchemaContext schemaContext) {
364 if (mountPoint != null) {
365 validNamespace = findFirstModuleByName(mountPoint.getSchemaContext(), namespace);
367 validNamespace = findFirstModuleByName(schemaContext, namespace);
369 if (validNamespace == null) {
370 validNamespace = URI.create(namespace);
373 return validNamespace;
376 private static URI findFirstModuleByName(final SchemaContext schemaContext, final String name) {
377 for (final Module module : schemaContext.getModules()) {
378 if (module.getName().equals(name)) {
379 return module.getNamespace();
385 @SuppressFBWarnings(value = "UPM_UNCALLED_PRIVATE_METHOD",
386 justification = "https://github.com/spotbugs/spotbugs/issues/811")
387 private static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
388 final String name, final URI namespace) {
389 requireNonNull(namespace);
391 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
392 node -> namespace.equals(node.getQName().getNamespace()));
393 return Iterables.getFirst(result, null);
396 private static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
398 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
399 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, requireNonNull(container),
400 requireNonNull(name));
401 return instantiatedDataNodeContainers;
404 private static void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
405 final DataNodeContainer container, final String name) {
407 final Iterable<DataSchemaNode> nodes =
408 Iterables.filter(container.getChildNodes(), node -> name.equals(node.getQName().getLocalName()));
410 // Can't combine this loop with the filter above because the filter is
411 // lazily-applied by Iterables.filter.
412 for (final DataSchemaNode potentialNode : nodes) {
413 if (isInstantiatedDataSchema(potentialNode)) {
414 potentialSchemaNodes.add(potentialNode);
418 final Iterable<ChoiceSchemaNode> choiceNodes =
419 Iterables.filter(container.getChildNodes(), ChoiceSchemaNode.class);
420 final Iterable<Collection<CaseSchemaNode>> map = Iterables.transform(choiceNodes,
421 choice -> choice.getCases().values());
422 for (final CaseSchemaNode caze : Iterables.concat(map)) {
423 collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
427 private static boolean isInstantiatedDataSchema(final DataSchemaNode node) {
428 return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
429 || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
430 || node instanceof AnyXmlSchemaNode;