Fix AnyXml node handling
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / schema / InstanceIdToNodes.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.data.impl.schema;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.FluentIterable;
13 import java.util.Collections;
14 import java.util.List;
15 import java.util.Map.Entry;
16 import javax.xml.transform.dom.DOMSource;
17 import org.opendaylight.yangtools.concepts.Identifiable;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
20 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
23 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
24 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
25 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
27 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.AttributesBuilder;
28 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
29 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
30 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
32 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
33 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
34 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
41
42 /**
43  * Base strategy for converting an instance identifier into a normalized node structure.
44  * Use provided static methods for generic YangInstanceIdentifier -> NormalizedNode translation in ImmutableNodes.
45  */
46 abstract class InstanceIdToNodes<T extends PathArgument> implements Identifiable<T> {
47
48     private final T identifier;
49
50     @Override
51     public final T getIdentifier() {
52         return identifier;
53     }
54
55     protected InstanceIdToNodes(final T identifier) {
56         this.identifier = identifier;
57     }
58
59     /**
60      * Build a strategy for the next path argument
61      *
62      * @param child child identifier
63      * @return transformation strategy for a specific child
64      */
65     abstract InstanceIdToNodes<?> getChild(final PathArgument child);
66
67     /**
68      *
69      * Convert instance identifier into a NormalizedNode structure
70      *
71      * @param instanceId Instance identifier to transform into NormalizedNodes
72      * @param deepestChild Optional normalized node to be inserted as the last child
73      * @param operation Optional modify operation to be set on the last child
74      * @return NormalizedNode structure corresponding to submitted instance ID
75      */
76     abstract NormalizedNode<?, ?> create(YangInstanceIdentifier instanceId, Optional<NormalizedNode<?, ?>> deepestChild, Optional<Entry<QName,ModifyAction>> operation);
77
78     abstract boolean isMixin();
79
80     public void addModifyOpIfPresent(final Optional<Entry<QName,ModifyAction>> operation, final AttributesBuilder<?> builder) {
81         if (operation.isPresent()) {
82             builder.withAttributes(Collections.singletonMap(operation.get().getKey(), modifyOperationToXmlString(operation.get().getValue())));
83         }
84     }
85
86     public static String modifyOperationToXmlString(final ModifyAction operation) {
87         return operation.name().toLowerCase();
88     }
89
90     private final static class UnkeyedListMixinNormalization extends InstanceIdToCompositeNodes<NodeIdentifier> {
91
92         private final UnkeyedListItemNormalization innerNode;
93
94         public UnkeyedListMixinNormalization(final ListSchemaNode list) {
95             super(NodeIdentifier.create(list.getQName()));
96             this.innerNode = new UnkeyedListItemNormalization(list);
97         }
98
99         @Override
100         protected CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> createBuilder(final PathArgument compositeNode) {
101             return Builders.unkeyedListBuilder().withNodeIdentifier(getIdentifier());
102         }
103
104         @Override
105         public InstanceIdToNodes<?> getChild(final PathArgument child) {
106             if (child.getNodeType().equals(getIdentifier().getNodeType())) {
107                 return innerNode;
108             }
109             return null;
110         }
111
112         @Override
113         boolean isMixin() {
114             return true;
115         }
116     }
117
118     private static class AnyXmlNormalization extends InstanceIdToNodes<NodeIdentifier> {
119
120         protected AnyXmlNormalization(final AnyXmlSchemaNode schema) {
121             super(NodeIdentifier.create(schema.getQName()));
122         }
123
124         @Override
125         public InstanceIdToNodes<?> getChild(final PathArgument child) {
126             return null;
127         }
128
129         @Override
130         public NormalizedNode<?, ?> create(final YangInstanceIdentifier instanceId,
131                 final Optional<NormalizedNode<?, ?>> deepestChild,
132                 final Optional<Entry<QName,ModifyAction>> operation) {
133             if (deepestChild.isPresent()) {
134                 final NormalizedNode<?, ?> child = deepestChild.get();
135                 Preconditions.checkState(child instanceof AnyXmlNode);
136
137                 final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder =
138                         Builders.anyXmlBuilder().withNodeIdentifier(getIdentifier()).withValue(((AnyXmlNode) child).getValue());
139                 addModifyOpIfPresent(operation, anyXmlBuilder);
140                 return anyXmlBuilder.build();
141             }
142
143             final NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> builder =
144                     Builders.anyXmlBuilder().withNodeIdentifier(getIdentifier());
145             addModifyOpIfPresent(operation, builder);
146             return builder.build();
147         }
148
149         @Override
150         boolean isMixin() {
151             return false;
152         }
153     }
154
155     private static Optional<DataSchemaNode> findChildSchemaNode(final DataNodeContainer parent, final QName child) {
156         DataSchemaNode potential = parent.getDataChildByName(child);
157         if (potential == null) {
158             final Iterable<ChoiceSchemaNode> choices = FluentIterable.from(parent.getChildNodes()).filter(ChoiceSchemaNode.class);
159             potential = findChoice(choices, child);
160         }
161         return Optional.fromNullable(potential);
162     }
163
164     static InstanceIdToNodes<?> fromSchemaAndQNameChecked(final DataNodeContainer schema, final QName child) {
165         final Optional<DataSchemaNode> potential = findChildSchemaNode(schema, child);
166         Preconditions.checkArgument(potential.isPresent(),
167                 "Supplied QName %s is not valid according to schema %s, potential children nodes: %s", child, schema, schema.getChildNodes());
168
169         final DataSchemaNode result = potential.get();
170         // We try to look up if this node was added by augmentation
171         if (schema instanceof DataSchemaNode && result.isAugmenting()) {
172             return fromAugmentation(schema, (AugmentationTarget) schema, result);
173         }
174         return fromDataSchemaNode(result);
175     }
176
177     private static ChoiceSchemaNode findChoice(final Iterable<ChoiceSchemaNode> choices, final QName child) {
178         ChoiceSchemaNode foundChoice = null;
179         choiceLoop:
180         for (final ChoiceSchemaNode choice : choices) {
181             for (final ChoiceCaseNode caze : choice.getCases()) {
182                 if (findChildSchemaNode(caze, child).isPresent()) {
183                     foundChoice = choice;
184                     break choiceLoop;
185                 }
186             }
187         }
188         return foundChoice;
189     }
190
191     /**
192      * Returns a SchemaPathUtil for provided child node
193      * <p/>
194      * If supplied child is added by Augmentation this operation returns
195      * a SchemaPathUtil for augmentation,
196      * otherwise returns a SchemaPathUtil for child as
197      * call for {@link #fromDataSchemaNode(org.opendaylight.yangtools.yang.model.api.DataSchemaNode)}.
198      */
199     private static InstanceIdToNodes<?> fromAugmentation(final DataNodeContainer parent,
200                                                           final AugmentationTarget parentAug, final DataSchemaNode child) {
201         AugmentationSchema augmentation = null;
202         for (final AugmentationSchema aug : parentAug.getAvailableAugmentations()) {
203             final DataSchemaNode potential = aug.getDataChildByName(child.getQName());
204             if (potential != null) {
205                 augmentation = aug;
206                 break;
207             }
208
209         }
210         if (augmentation != null) {
211             return new InstanceIdToCompositeNodes.AugmentationNormalization(augmentation, parent);
212         }
213         return fromDataSchemaNode(child);
214     }
215
216     static InstanceIdToNodes<?> fromDataSchemaNode(final DataSchemaNode potential) {
217         if (potential instanceof ContainerSchemaNode) {
218             return new InstanceIdToCompositeNodes.ContainerTransformation((ContainerSchemaNode) potential);
219         } else if (potential instanceof ListSchemaNode) {
220             return fromListSchemaNode((ListSchemaNode) potential);
221         } else if (potential instanceof LeafSchemaNode) {
222             return new InstanceIdToSimpleNodes.LeafNormalization((LeafSchemaNode) potential);
223         } else if (potential instanceof ChoiceSchemaNode) {
224             return new InstanceIdToCompositeNodes.ChoiceNodeNormalization((ChoiceSchemaNode) potential);
225         } else if (potential instanceof LeafListSchemaNode) {
226             return fromLeafListSchemaNode((LeafListSchemaNode) potential);
227         } else if (potential instanceof AnyXmlSchemaNode) {
228             return new AnyXmlNormalization((AnyXmlSchemaNode) potential);
229         }
230         return null;
231     }
232
233     private static InstanceIdToNodes<?> fromListSchemaNode(final ListSchemaNode potential) {
234         final List<QName> keyDefinition = potential.getKeyDefinition();
235         if (keyDefinition == null || keyDefinition.isEmpty()) {
236             return new UnkeyedListMixinNormalization(potential);
237         }
238         if (potential.isUserOrdered()) {
239             return new InstanceIdToCompositeNodes.OrderedMapMixinNormalization(potential);
240         }
241         return new InstanceIdToCompositeNodes.UnorderedMapMixinNormalization(potential);
242     }
243
244     private static InstanceIdToNodes<?> fromLeafListSchemaNode(final LeafListSchemaNode potential) {
245         if (potential.isUserOrdered()) {
246             return new InstanceIdToCompositeNodes.OrderedLeafListMixinNormalization(potential);
247         }
248         return new InstanceIdToCompositeNodes.UnorderedLeafListMixinNormalization(potential);
249     }
250
251
252 }