e1fc3c3cdb200b3c79a2e72b4d96abd03ca0572c
[controller.git] / opendaylight / md-sal / sal-common-impl / src / main / java / org / opendaylight / controller / md / sal / common / impl / util / compat / DataNormalizer.java
1 /*
2  * Copyright (c) 2014 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.controller.md.sal.common.impl.util.compat;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11
12 import java.util.AbstractMap;
13 import java.util.ArrayList;
14 import java.util.Iterator;
15 import java.util.Map;
16
17 import org.opendaylight.yangtools.yang.common.QName;
18 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
19 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.AugmentationIdentifier;
21 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
22 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
23 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
24 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
25 import org.opendaylight.yangtools.yang.data.api.Node;
26 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
27 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
28 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
31 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
32 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
33 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
35
36 import com.google.common.base.Preconditions;
37 import com.google.common.base.Predicate;
38 import com.google.common.collect.FluentIterable;
39 import com.google.common.collect.ImmutableList;
40 import com.google.common.collect.Iterables;
41
42 public class DataNormalizer {
43
44     private final DataNormalizationOperation<?> operation;
45
46     public DataNormalizer(final SchemaContext ctx) {
47         operation = DataNormalizationOperation.from(ctx);
48     }
49
50     public InstanceIdentifier toNormalized(final InstanceIdentifier legacy) {
51         ImmutableList.Builder<PathArgument> normalizedArgs = ImmutableList.builder();
52
53         DataNormalizationOperation<?> currentOp = operation;
54         Iterator<PathArgument> arguments = legacy.getPath().iterator();
55
56         try {
57             while ( arguments.hasNext() ) {
58                 PathArgument legacyArg = arguments.next();
59                 currentOp = currentOp.getChild(legacyArg);
60                 checkArgument(currentOp != null, "Legacy Instance Identifier %s is not correct. Normalized Instance Identifier so far %s",legacy,normalizedArgs.build());
61                 while (currentOp.isMixin()) {
62                     normalizedArgs.add(currentOp.getIdentifier());
63                     currentOp = currentOp.getChild(legacyArg.getNodeType());
64                 }
65                 if(arguments.hasNext() || (!currentOp.isKeyedEntry() || legacyArg instanceof NodeIdentifierWithPredicates || legacyArg instanceof NodeWithValue)) {
66                     normalizedArgs.add(legacyArg);
67                 }
68             }
69         } catch (DataNormalizationException e) {
70             throw new IllegalArgumentException(String.format("Failed to normalize path %s", legacy), e);
71         }
72
73         return new InstanceIdentifier(normalizedArgs.build());
74     }
75
76     public Map.Entry<InstanceIdentifier,NormalizedNode<?, ?>> toNormalized(final Map.Entry<InstanceIdentifier,CompositeNode> legacy) {
77         return toNormalized(legacy.getKey(), legacy.getValue());
78     }
79
80     public Map.Entry<InstanceIdentifier,NormalizedNode<?, ?>> toNormalized(final InstanceIdentifier legacyPath, final CompositeNode legacyData) {
81
82         InstanceIdentifier normalizedPath = toNormalized(legacyPath);
83
84         DataNormalizationOperation<?> currentOp = operation;
85         for (PathArgument arg : normalizedPath.getPath()) {
86             try {
87                 currentOp = currentOp.getChild(arg);
88             } catch (DataNormalizationException e) {
89                 throw new IllegalArgumentException(String.format("Failed to validate normalized path %s", normalizedPath), e);
90             }
91         }
92
93         // Write Augmentation data resolution
94         if (legacyData.getChildren().size() == 1) {
95             final DataNormalizationOperation<?> potentialOp;
96
97             try {
98                 final QName childType = legacyData.getChildren().get(0).getNodeType();
99                 potentialOp = currentOp.getChild(childType);
100             } catch (DataNormalizationException e) {
101                 throw new IllegalArgumentException(String.format("Failed to get child operation for %s", legacyData), e);
102             }
103
104             if(potentialOp.getIdentifier() instanceof AugmentationIdentifier) {
105                 currentOp = potentialOp;
106                 ArrayList<PathArgument> reworkedArgs = new ArrayList<>(normalizedPath.getPath());
107                 reworkedArgs.add(potentialOp.getIdentifier());
108                 normalizedPath = new InstanceIdentifier(reworkedArgs);
109             }
110         }
111
112         Preconditions.checkArgument(currentOp != null,
113                 "Instance Identifier %s does not reference correct schema Node.", normalizedPath);
114         return new AbstractMap.SimpleEntry<InstanceIdentifier,NormalizedNode<?, ?>>(normalizedPath,currentOp.normalize(legacyData));
115     }
116
117     public InstanceIdentifier toLegacy(final InstanceIdentifier normalized) {
118         ImmutableList.Builder<PathArgument> legacyArgs = ImmutableList.builder();
119         PathArgument previous = null;
120         for (PathArgument normalizedArg : normalized.getPath()) {
121             if (normalizedArg instanceof NodeIdentifier) {
122                 if (previous != null) {
123                     legacyArgs.add(previous);
124                 }
125                 previous = normalizedArg;
126             } else if (normalizedArg instanceof NodeIdentifierWithPredicates) {
127                 // We skip previous node, which was mixin.
128                 previous = normalizedArg;
129             } else if (normalizedArg instanceof AugmentationIdentifier) {
130                 // We ignore argument
131             }
132             // FIXME : Add option for reading choice
133         }
134         if (previous != null) {
135             legacyArgs.add(previous);
136         }
137         return new InstanceIdentifier(legacyArgs.build());
138     }
139
140     public CompositeNode toLegacy(final InstanceIdentifier normalizedPath, final NormalizedNode<?, ?> normalizedData) {
141         // Preconditions.checkArgument(normalizedData instanceof
142         // DataContainerNode<?>,"Node object %s, %s should be of type DataContainerNode",normalizedPath,normalizedData);
143         if (normalizedData instanceof DataContainerNode<?>) {
144             return toLegacyFromDataContainer((DataContainerNode<?>) normalizedData);
145         }
146         return null;
147     }
148
149     public static Node<?> toLegacy(final NormalizedNode<?, ?> node) {
150         if (node instanceof MixinNode) {
151             /**
152              * Direct reading of MixinNodes is not supported,
153              * since it is not possible in legacy APIs create pointer
154              * to Mixin Nodes.
155              *
156              */
157             return null;
158         }
159
160         if (node instanceof DataContainerNode<?>) {
161             return toLegacyFromDataContainer((DataContainerNode<?>) node);
162         }
163         return toLegacySimple(node);
164
165     }
166
167     private static SimpleNode<?> toLegacySimple(final NormalizedNode<?, ?> node) {
168         return new SimpleNodeTOImpl<Object>(node.getNodeType(), null, node.getValue());
169     }
170
171     @SuppressWarnings({ "unchecked", "rawtypes" })
172     private static CompositeNode toLegacyFromDataContainer(final DataContainerNode<?> node) {
173         CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
174         builder.setQName(node.getNodeType());
175         for (NormalizedNode<?, ?> child : node.getValue()) {
176             if (child instanceof MixinNode && child instanceof NormalizedNodeContainer<?, ?, ?>) {
177                 builder.addAll(toLegacyNodesFromMixin((NormalizedNodeContainer) child));
178             } else {
179                 addToBuilder(builder, toLegacy(child));
180             }
181         }
182         return builder.toInstance();
183     }
184
185     private static void addToBuilder(final CompositeNodeBuilder<ImmutableCompositeNode> builder, final Node<?> legacy) {
186         if (legacy != null) {
187             builder.add(legacy);
188         }
189     }
190
191     @SuppressWarnings({ "rawtypes", "unchecked" })
192     private static Iterable<Node<?>> toLegacyNodesFromMixin(
193             final NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>> mixin) {
194         ArrayList<Node<?>> ret = new ArrayList<>();
195         for (NormalizedNode<?, ?> child : mixin.getValue()) {
196             if(child instanceof MixinNode && child instanceof NormalizedNodeContainer<?, ?, ?>) {
197                 Iterables.addAll(ret,toLegacyNodesFromMixin((NormalizedNodeContainer) child));
198             } else {
199                 ret.add(toLegacy(child));
200             }
201         }
202         return FluentIterable.from(ret).filter(new Predicate<Node<?>>() {
203
204             @Override
205             public boolean apply(final Node<?> input) {
206                 return input != null;
207             }
208         });
209     }
210
211     public DataNormalizationOperation<?> getRootOperation() {
212         return operation;
213     }
214
215 }