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;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.HashMap;
16 import java.util.List;
18 import java.util.Map.Entry;
19 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
20 import org.opendaylight.restconf.common.util.IdentityValuesDTO;
21 import org.opendaylight.restconf.common.util.IdentityValuesDTO.IdentityValue;
22 import org.opendaylight.restconf.common.util.IdentityValuesDTO.Predicate;
23 import org.opendaylight.restconf.common.util.RestUtil;
24 import org.opendaylight.yangtools.concepts.Codec;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
31 import org.opendaylight.yangtools.yang.data.api.codec.IdentityrefCodec;
32 import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
33 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
34 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
35 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.Module;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 public final class RestCodec {
55 private static final Logger LOG = LoggerFactory.getLogger(RestCodec.class);
60 public static Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
61 final DOMMountPoint mountPoint, final SchemaContext schemaContext) {
62 return new ObjectCodec(typeDefinition, mountPoint, schemaContext);
65 @SuppressWarnings("rawtypes")
66 public static final class ObjectCodec implements Codec<Object, Object> {
68 private static final Logger LOG = LoggerFactory.getLogger(ObjectCodec.class);
70 public static final Codec LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl();
71 private final Codec instanceIdentifier;
72 private final Codec identityrefCodec;
74 private final TypeDefinition<?> type;
76 private final SchemaContext schemaContext;
78 private ObjectCodec(final TypeDefinition<?> typeDefinition, final DOMMountPoint mountPoint,
79 final SchemaContext schemaContext) {
80 this.schemaContext = schemaContext;
81 this.type = RestUtil.resolveBaseTypeFrom(typeDefinition);
82 if (this.type instanceof IdentityrefTypeDefinition) {
83 this.identityrefCodec = new IdentityrefCodecImpl(mountPoint, schemaContext);
85 this.identityrefCodec = null;
87 if (this.type instanceof InstanceIdentifierTypeDefinition) {
88 this.instanceIdentifier = new InstanceIdentifierCodecImpl(mountPoint, schemaContext);
90 this.instanceIdentifier = null;
94 @SuppressWarnings("unchecked")
96 public Object deserialize(final Object input) {
98 if (this.type instanceof IdentityrefTypeDefinition) {
99 if (input instanceof IdentityValuesDTO) {
100 return this.identityrefCodec.deserialize(input);
102 if (LOG.isDebugEnabled()) {
104 "Value is not instance of IdentityrefTypeDefinition but is {}. "
105 + "Therefore NULL is used as translation of - {}",
106 input == null ? "null" : input.getClass(), String.valueOf(input));
109 } else if (this.type instanceof InstanceIdentifierTypeDefinition) {
110 if (input instanceof IdentityValuesDTO) {
111 return this.instanceIdentifier.deserialize(input);
113 final StringModuleInstanceIdentifierCodec codec =
114 new StringModuleInstanceIdentifierCodec(schemaContext);
115 return codec.deserialize((String) input);
118 final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> typeAwarecodec =
119 TypeDefinitionAwareCodec.from(this.type);
120 if (typeAwarecodec != null) {
121 if (input instanceof IdentityValuesDTO) {
122 return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
124 return typeAwarecodec.deserialize(String.valueOf(input));
126 LOG.debug("Codec for type \"" + this.type.getQName().getLocalName()
127 + "\" is not implemented yet.");
131 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
133 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
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 \"" + this.type.getQName().getLocalName()
157 + "\" is not implemented yet.");
162 } catch (final ClassCastException e) { // TODO remove this catch when everyone use codecs
164 "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
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).getKeyValues());
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;
251 public YangInstanceIdentifier deserialize(final IdentityValuesDTO data) {
252 final List<PathArgument> result = new ArrayList<>();
253 final IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
254 final Module module =
255 getModuleByNamespace(valueWithNamespace.getNamespace(), this.mountPoint, schemaContext);
256 if (module == null) {
257 LOG.info("Module by namespace '{}' of first node in instance-identifier was not found.",
258 valueWithNamespace.getNamespace());
259 LOG.info("Instance-identifier will be translated as NULL for data - {}",
260 String.valueOf(valueWithNamespace.getValue()));
264 DataNodeContainer parentContainer = module;
265 final List<IdentityValue> identities = data.getValuesWithNamespaces();
266 for (int i = 0; i < identities.size(); i++) {
267 final IdentityValue identityValue = identities.get(i);
269 resolveValidNamespace(identityValue.getNamespace(), this.mountPoint, schemaContext);
270 final DataSchemaNode node = findInstanceDataChildByNameAndNamespace(
271 parentContainer, identityValue.getValue(), validNamespace);
273 LOG.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
274 LOG.info("Instance-identifier will be translated as NULL for data - {}",
275 String.valueOf(identityValue.getValue()));
278 final QName qName = node.getQName();
279 PathArgument pathArgument = null;
280 if (identityValue.getPredicates().isEmpty()) {
281 pathArgument = new NodeIdentifier(qName);
283 if (node instanceof LeafListSchemaNode) { // predicate is value of leaf-list entry
284 final Predicate leafListPredicate = identityValue.getPredicates().get(0);
285 if (!leafListPredicate.isLeafList()) {
286 LOG.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
287 LOG.info("Instance-identifier will be translated as NULL for data - {}",
288 String.valueOf(identityValue.getValue()));
291 pathArgument = new NodeWithValue<>(qName, leafListPredicate.getValue());
292 } else if (node instanceof ListSchemaNode) { // predicates are keys of list
293 final DataNodeContainer listNode = (DataNodeContainer) node;
294 final Map<QName, Object> predicatesMap = new HashMap<>();
295 for (final Predicate predicate : identityValue.getPredicates()) {
296 validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), this.mountPoint,
298 final DataSchemaNode listKey = findInstanceDataChildByNameAndNamespace(listNode,
299 predicate.getName().getValue(), validNamespace);
300 predicatesMap.put(listKey.getQName(), predicate.getValue());
302 pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
304 LOG.info("Node {} is not List or Leaf-list.", node);
305 LOG.info("Instance-identifier will be translated as NULL for data - {}",
306 String.valueOf(identityValue.getValue()));
310 result.add(pathArgument);
311 if (i < identities.size() - 1) { // last element in instance-identifier can be other than
313 if (node instanceof DataNodeContainer) {
314 parentContainer = (DataNodeContainer) node;
316 LOG.info("Node {} isn't instance of DataNodeContainer", node);
317 LOG.info("Instance-identifier will be translated as NULL for data - {}",
318 String.valueOf(identityValue.getValue()));
324 return result.isEmpty() ? null : YangInstanceIdentifier.create(result);
327 private static List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
328 final List<Predicate> result = new ArrayList<>();
329 for (final Entry<QName, Object> entry : keyValues.entrySet()) {
330 final QName qualifiedName = entry.getKey();
331 final Object value = entry.getValue();
332 result.add(new Predicate(qNameToIdentityValue(qualifiedName), String.valueOf(value)));
337 private static IdentityValue qNameToIdentityValue(final QName qualifiedName) {
338 if (qualifiedName != null) {
339 return new IdentityValue(qualifiedName.getNamespace().toString(), qualifiedName.getLocalName());
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 " + validNamespace + " wasn't found.");
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 private static DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container,
386 final String name, final URI namespace) {
387 Preconditions.checkNotNull(namespace);
389 final Iterable<DataSchemaNode> result = Iterables.filter(findInstanceDataChildrenByName(container, name),
390 node -> namespace.equals(node.getQName().getNamespace()));
391 return Iterables.getFirst(result, null);
394 private static List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container,
396 Preconditions.checkNotNull(container);
397 Preconditions.checkNotNull(name);
399 final List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<>();
400 collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, 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;