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