Introduce YangTextSchemaSourceSet
[cps.git] / cps-service / src / main / java / org / onap / cps / utils / YangUtils.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.onap.cps.utils;
21
22 import static com.google.common.base.Preconditions.checkArgument;
23 import static org.opendaylight.yangtools.yang.common.YangConstants.RFC6020_YANG_FILE_EXTENSION;
24
25 import com.google.common.base.Charsets;
26 import com.google.common.io.Files;
27 import com.google.gson.stream.JsonReader;
28 import java.io.File;
29 import java.io.IOException;
30 import java.io.StringReader;
31 import java.util.Collection;
32 import java.util.Collections;
33 import java.util.List;
34 import java.util.logging.Logger;
35 import java.util.stream.Collectors;
36 import org.onap.cps.api.impl.Fragment;
37 import org.onap.cps.yang.YangTextSchemaSourceSet;
38 import org.onap.cps.yang.YangTextSchemaSourceSetBuilder;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
42 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
43 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
44 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
46 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
47 import org.opendaylight.yangtools.yang.data.api.schema.ValueNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
50 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
51 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
52 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
53 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
54 import org.opendaylight.yangtools.yang.model.api.Module;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.parser.api.YangParserException;
57 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
58
59 public class YangUtils {
60     private static final Logger LOGGER = Logger.getLogger(YangUtils.class.getName());
61
62     private YangUtils() {
63         throw new IllegalStateException("Utility class");
64     }
65
66     /**
67      * Parse a file containing yang modules.
68      *
69      * @param yangModelFiles list of files containing one or more yang modules. The file has to have a .yang extension.
70      * @return a SchemaContext representing the yang model
71      * @throws IOException         when the system as an IO issue
72      * @throws YangParserException when the file does not contain a valid yang structure
73      */
74     @Deprecated
75     public static YangTextSchemaSourceSet parseYangModelFiles(final List<File> yangModelFiles)
76             throws IOException, YangParserException, ReactorException {
77         final YangTextSchemaSourceSetBuilder yangModelsMapBuilder = new YangTextSchemaSourceSetBuilder();
78         for (final File file :yangModelFiles) {
79             final String fileNameWithExtension = file.getName();
80             checkArgument(fileNameWithExtension.endsWith(RFC6020_YANG_FILE_EXTENSION),
81                     "Filename %s does not end with '%s'", RFC6020_YANG_FILE_EXTENSION,
82                     fileNameWithExtension);
83             final String content = Files.asCharSource(file, Charsets.UTF_8).read();
84             yangModelsMapBuilder.put(fileNameWithExtension, content);
85         }
86         return yangModelsMapBuilder.build();
87     }
88
89     /**
90      * Parse a file containing json data for a certain model (schemaContext).
91      *
92      * @param jsonData      a string containing json data for the given model
93      * @param schemaContext the SchemaContext for the given data
94      * @return the NormalizedNode representing the json data
95      */
96     public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext)
97             throws IOException {
98         final JSONCodecFactory jsonCodecFactory = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
99                 .getShared(schemaContext);
100         final NormalizedNodeResult normalizedNodeResult = new NormalizedNodeResult();
101         final NormalizedNodeStreamWriter normalizedNodeStreamWriter = ImmutableNormalizedNodeStreamWriter
102                 .from(normalizedNodeResult);
103         try (final JsonParserStream jsonParserStream = JsonParserStream
104                 .create(normalizedNodeStreamWriter, jsonCodecFactory)) {
105             final JsonReader jsonReader = new JsonReader(new StringReader(jsonData));
106             jsonParserStream.parse(jsonReader);
107         }
108         return normalizedNodeResult.getResult();
109     }
110
111     /**
112      * Break a Normalized Node tree into fragments that can be stored by the persistence service.
113      *
114      * @param tree   the normalized node tree
115      * @param module the module applicable for the data in the normalized node
116      * @return the 'root' Fragment for the tree contain all relevant children etc.
117      */
118     public static Fragment fragmentNormalizedNode(
119             final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> tree,
120             final Module module) {
121         final QName[] nodeTypes = {tree.getNodeType()};
122         final String xpath = buildXpathId(tree.getIdentifier());
123         final Fragment rootFragment = Fragment.createRootFragment(module, nodeTypes, xpath);
124         fragmentNormalizedNode(rootFragment, tree);
125         return rootFragment;
126     }
127
128     private static void fragmentNormalizedNode(final Fragment currentFragment,
129                                                final NormalizedNode normalizedNode) {
130         if (normalizedNode instanceof DataContainerNode) {
131             inspectContainer(currentFragment, (DataContainerNode) normalizedNode);
132         } else if (normalizedNode instanceof MapNode) {
133             inspectKeyedList(currentFragment, (MapNode) normalizedNode);
134         } else if (normalizedNode instanceof ValueNode) {
135             inspectLeaf(currentFragment, (ValueNode) normalizedNode);
136         } else if (normalizedNode instanceof LeafSetNode) {
137             inspectLeafList(currentFragment, (LeafSetNode) normalizedNode);
138         } else {
139             LOGGER.warning("Cannot normalize " + normalizedNode.getClass());
140         }
141     }
142
143     private static void inspectLeaf(final Fragment currentFragment,
144                                     final ValueNode valueNode) {
145         final Object value = valueNode.getValue();
146         currentFragment.addLeafValue(valueNode.getNodeType().getLocalName(), value);
147     }
148
149     private static void inspectLeafList(final Fragment currentFragment,
150                                         final LeafSetNode leafSetNode) {
151         currentFragment.addLeafListName(leafSetNode.getNodeType().getLocalName());
152         for (final NormalizedNode value : (Collection<NormalizedNode>) leafSetNode.getValue()) {
153             fragmentNormalizedNode(currentFragment, value);
154         }
155     }
156
157     private static void inspectContainer(final Fragment currentFragment,
158                                          final DataContainerNode dataContainerNode) {
159         final Collection<NormalizedNode> leaves = (Collection) dataContainerNode.getValue();
160         for (final NormalizedNode leaf : leaves) {
161             fragmentNormalizedNode(currentFragment, leaf);
162         }
163     }
164
165     private static void inspectKeyedList(final Fragment currentFragment,
166                                          final MapNode mapNode) {
167         createNodeForEachListElement(currentFragment, mapNode);
168     }
169
170     private static void createNodeForEachListElement(final Fragment currentFragment, final MapNode mapNode) {
171         final Collection<MapEntryNode> mapEntryNodes = mapNode.getValue();
172         for (final MapEntryNode mapEntryNode : mapEntryNodes) {
173             final String xpathId = buildXpathId(mapEntryNode.getIdentifier());
174             final Fragment listElementFragment =
175                 currentFragment.createChildFragment(mapNode.getNodeType(), xpathId);
176             fragmentNormalizedNode(listElementFragment, mapEntryNode);
177         }
178     }
179
180     private static String buildXpathId(final YangInstanceIdentifier.PathArgument nodeIdentifier) {
181         final StringBuilder xpathIdBuilder = new StringBuilder();
182         xpathIdBuilder.append("/").append(nodeIdentifier.getNodeType().getLocalName());
183
184         if (nodeIdentifier instanceof NodeIdentifierWithPredicates) {
185             xpathIdBuilder.append(getKeyAttributesStatement((NodeIdentifierWithPredicates) nodeIdentifier));
186         }
187         return xpathIdBuilder.toString();
188     }
189
190     private static String getKeyAttributesStatement(final NodeIdentifierWithPredicates nodeIdentifier) {
191         final List<String> keyAttributes = nodeIdentifier.entrySet().stream().map(
192             entry -> {
193                 final String name = entry.getKey().getLocalName();
194                 final String value = String.valueOf(entry.getValue()).replace("'", "\\'");
195                 return String.format("@%s='%s'", name, value);
196             }
197         ).collect(Collectors.toList());
198
199         if (keyAttributes.isEmpty()) {
200             return "";
201         } else {
202             Collections.sort(keyAttributes);
203             return "[" + String.join(" and ", keyAttributes) + "]";
204         }
205     }
206 }