733378ecba059df399d08dba49dc4a5318e88a62
[cps.git] / cps-service / src / main / java / org / onap / cps / utils / YangUtils.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Nordix Foundation
4  *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
5  *  Modifications Copyright (C) 2021 Pantheon.tech
6  *  ================================================================================
7  *  Licensed under the Apache License, Version 2.0 (the "License");
8  *  you may not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *        http://www.apache.org/licenses/LICENSE-2.0
12  *  Unless required by applicable law or agreed to in writing, software
13  *  distributed under the License is distributed on an "AS IS" BASIS,
14  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  *  See the License for the specific language governing permissions and
16  *  limitations under the License.
17  *
18  *  SPDX-License-Identifier: Apache-2.0
19  *  ============LICENSE_END=========================================================
20  */
21
22 package org.onap.cps.utils;
23
24 import com.google.gson.stream.JsonReader;
25 import java.io.IOException;
26 import java.io.StringReader;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.List;
31 import java.util.Optional;
32 import java.util.stream.Collectors;
33 import lombok.AccessLevel;
34 import lombok.NoArgsConstructor;
35 import lombok.extern.slf4j.Slf4j;
36 import org.onap.cps.spi.exceptions.DataValidationException;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
40 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
41 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
42 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
43 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
44 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
45 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48
49 @Slf4j
50 @NoArgsConstructor(access = AccessLevel.PRIVATE)
51 public class YangUtils {
52
53     private static final String XPATH_DELIMITER_REGEX = "\\/";
54     private static final String XPATH_NODE_KEY_ATTRIBUTES_REGEX = "\\[.+";
55
56     /**
57      * Parses jsonData into NormalizedNode according to given schema context.
58      *
59      * @param jsonData      json data as string
60      * @param schemaContext schema context describing associated data model
61      * @return the NormalizedNode object
62      */
63     public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext) {
64         return parseJsonData(jsonData, schemaContext, Optional.empty());
65     }
66
67     /**
68      * Parses jsonData into NormalizedNode according to given schema context.
69      *
70      * @param jsonData        json data fragment as string
71      * @param schemaContext   schema context describing associated data model
72      * @param parentNodeXpath the xpath referencing the parent node current data fragment belong to
73      * @return the NormalizedNode object
74      */
75     public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
76         final String parentNodeXpath) {
77         final DataSchemaNode parentSchemaNode = getDataSchemaNodeByXpath(parentNodeXpath, schemaContext);
78         return parseJsonData(jsonData, schemaContext, Optional.of(parentSchemaNode));
79     }
80
81     private static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
82         final Optional<DataSchemaNode> optionalParentSchemaNode) {
83         final JSONCodecFactory jsonCodecFactory = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
84             .getShared(schemaContext);
85         final NormalizedNodeResult normalizedNodeResult = new NormalizedNodeResult();
86         final NormalizedNodeStreamWriter normalizedNodeStreamWriter = ImmutableNormalizedNodeStreamWriter
87             .from(normalizedNodeResult);
88
89         try (final JsonParserStream jsonParserStream = optionalParentSchemaNode.isPresent()
90             ? JsonParserStream.create(normalizedNodeStreamWriter, jsonCodecFactory, optionalParentSchemaNode.get())
91             : JsonParserStream.create(normalizedNodeStreamWriter, jsonCodecFactory)
92         ) {
93             final JsonReader jsonReader = new JsonReader(new StringReader(jsonData));
94             jsonParserStream.parse(jsonReader);
95
96         } catch (final IOException | IllegalStateException e) {
97             throw new DataValidationException("Failed to parse json data.", String
98                 .format("Exception occurred on parsing string %s.", jsonData), e);
99         }
100         return normalizedNodeResult.getResult();
101     }
102
103     /**
104      * Create an xpath form a Yang Tools NodeIdentifier (i.e. PathArgument).
105      *
106      * @param nodeIdentifier the NodeIdentifier
107      * @return an xpath
108      */
109     public static String buildXpath(final YangInstanceIdentifier.PathArgument nodeIdentifier) {
110         final StringBuilder xpathBuilder = new StringBuilder();
111         xpathBuilder.append("/").append(nodeIdentifier.getNodeType().getLocalName());
112
113         if (nodeIdentifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
114             xpathBuilder.append(getKeyAttributesStatement(
115                 (YangInstanceIdentifier.NodeIdentifierWithPredicates) nodeIdentifier));
116         }
117         return xpathBuilder.toString();
118     }
119
120     private static String getKeyAttributesStatement(
121         final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifier) {
122         final List<String> keyAttributes = nodeIdentifier.entrySet().stream().map(
123             entry -> {
124                 final String name = entry.getKey().getLocalName();
125                 final String value = String.valueOf(entry.getValue()).replace("'", "\\'");
126                 return String.format("@%s='%s'", name, value);
127             }
128         ).collect(Collectors.toList());
129
130         if (keyAttributes.isEmpty()) {
131             return "";
132         } else {
133             Collections.sort(keyAttributes);
134             return "[" + String.join(" and ", keyAttributes) + "]";
135         }
136     }
137
138     private static DataSchemaNode getDataSchemaNodeByXpath(final String parentNodeXpath,
139         final SchemaContext schemaContext) {
140         final String[] xpathNodeIdSequence = xpathToNodeIdSequence(parentNodeXpath);
141         return findDataSchemaNodeByXpathNodeIdSequence(xpathNodeIdSequence, schemaContext.getChildNodes());
142     }
143
144     private static String[] xpathToNodeIdSequence(final String xpath) {
145         final String[] xpathNodeIdSequence = Arrays.stream(xpath.split(XPATH_DELIMITER_REGEX))
146             .map(identifier -> identifier.replaceFirst(XPATH_NODE_KEY_ATTRIBUTES_REGEX, ""))
147             .filter(identifier -> !identifier.isEmpty())
148             .toArray(String[]::new);
149         if (xpathNodeIdSequence.length < 1) {
150             throw new DataValidationException("Invalid xpath.", "Xpath contains no node identifiers.");
151         }
152         return xpathNodeIdSequence;
153     }
154
155     private static DataSchemaNode findDataSchemaNodeByXpathNodeIdSequence(final String[] xpathNodeIdSequence,
156         final Collection<? extends DataSchemaNode> dataSchemaNodes) {
157         final String currentXpathNodeId = xpathNodeIdSequence[0];
158         final DataSchemaNode currentDataSchemaNode = dataSchemaNodes.stream()
159             .filter(dataSchemaNode -> currentXpathNodeId.equals(dataSchemaNode.getQName().getLocalName()))
160             .findFirst().orElseThrow(() -> schemaNodeNotFoundException(currentXpathNodeId));
161         if (xpathNodeIdSequence.length <= 1) {
162             return currentDataSchemaNode;
163         }
164         if (currentDataSchemaNode instanceof DataNodeContainer) {
165             return findDataSchemaNodeByXpathNodeIdSequence(
166                 getNextLevelXpathNodeIdSequence(xpathNodeIdSequence),
167                 ((DataNodeContainer) currentDataSchemaNode).getChildNodes());
168         }
169         throw schemaNodeNotFoundException(xpathNodeIdSequence[1]);
170     }
171
172     private static String[] getNextLevelXpathNodeIdSequence(final String[] xpathNodeIdSequence) {
173         final String[] nextXpathNodeIdSequence = new String[xpathNodeIdSequence.length - 1];
174         System.arraycopy(xpathNodeIdSequence, 1, nextXpathNodeIdSequence, 0, nextXpathNodeIdSequence.length);
175         return nextXpathNodeIdSequence;
176     }
177
178     private static DataValidationException schemaNodeNotFoundException(final String schemaNodeIdentifier) {
179         return new DataValidationException("Invalid xpath.",
180             String.format("No schema node was found for xpath identifier '%s'.", schemaNodeIdentifier));
181     }
182 }