b5c14a0721cf1d540e28550e0cc663ac61254681
[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. 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.JsonSyntaxException;
25 import com.google.gson.stream.JsonReader;
26 import java.io.IOException;
27 import java.io.StringReader;
28 import java.util.Arrays;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.List;
32 import java.util.Optional;
33 import java.util.stream.Collectors;
34 import lombok.AccessLevel;
35 import lombok.NoArgsConstructor;
36 import lombok.extern.slf4j.Slf4j;
37 import org.onap.cps.spi.exceptions.DataValidationException;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
40 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
41 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
42 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
43 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47
48 @Slf4j
49 @NoArgsConstructor(access = AccessLevel.PRIVATE)
50 public class YangUtils {
51
52     private static final String XPATH_DELIMITER_REGEX = "\\/";
53     private static final String XPATH_NODE_KEY_ATTRIBUTES_REGEX = "\\[.+";
54
55     /**
56      * Parses jsonData into NormalizedNode according to given schema context.
57      *
58      * @param jsonData      json data as string
59      * @param schemaContext schema context describing associated data model
60      * @return the NormalizedNode object
61      */
62     @SuppressWarnings("squid:S1452")  // Generic type <? ,?> is returned by external librray, opendaylight.yangtools
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     @SuppressWarnings("squid:S1452")  // Generic type <? ,?> is returned by external librray, opendaylight.yangtools
76     public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
77         final String parentNodeXpath) {
78         final var parentSchemaNode = getDataSchemaNodeByXpath(parentNodeXpath, schemaContext);
79         return parseJsonData(jsonData, schemaContext, Optional.of(parentSchemaNode));
80     }
81
82     private static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
83         final Optional<DataSchemaNode> optionalParentSchemaNode) {
84         final var jsonCodecFactory = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
85             .getShared(schemaContext);
86         final var normalizedNodeResult = new NormalizedNodeResult();
87         final var normalizedNodeStreamWriter = ImmutableNormalizedNodeStreamWriter
88             .from(normalizedNodeResult);
89
90         try (final JsonParserStream jsonParserStream = optionalParentSchemaNode.isPresent()
91             ? JsonParserStream.create(normalizedNodeStreamWriter, jsonCodecFactory, optionalParentSchemaNode.get())
92             : JsonParserStream.create(normalizedNodeStreamWriter, jsonCodecFactory)
93         ) {
94             final var jsonReader = new JsonReader(new StringReader(jsonData));
95             jsonParserStream.parse(jsonReader);
96
97         } catch (final IOException | JsonSyntaxException exception) {
98             throw new DataValidationException(
99                 "Failed to parse json data: " + jsonData, exception.getMessage(), exception);
100         } catch (final IllegalStateException illegalStateException) {
101             throw new DataValidationException(
102                 "Failed to parse json data. Unsupported xpath or json data:" + jsonData, illegalStateException
103                 .getMessage(), illegalStateException);
104         }
105         return normalizedNodeResult.getResult();
106     }
107
108     /**
109      * Create an xpath form a Yang Tools NodeIdentifier (i.e. PathArgument).
110      *
111      * @param nodeIdentifier the NodeIdentifier
112      * @return an xpath
113      */
114     public static String buildXpath(final YangInstanceIdentifier.PathArgument nodeIdentifier) {
115         final var xpathBuilder = new StringBuilder();
116         xpathBuilder.append("/").append(nodeIdentifier.getNodeType().getLocalName());
117
118         if (nodeIdentifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
119             xpathBuilder.append(getKeyAttributesStatement(
120                 (YangInstanceIdentifier.NodeIdentifierWithPredicates) nodeIdentifier));
121         }
122         return xpathBuilder.toString();
123     }
124
125     private static String getKeyAttributesStatement(
126         final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifier) {
127         final List<String> keyAttributes = nodeIdentifier.entrySet().stream().map(
128             entry -> {
129                 final String name = entry.getKey().getLocalName();
130                 final String value = String.valueOf(entry.getValue()).replace("'", "\\'");
131                 return String.format("@%s='%s'", name, value);
132             }
133         ).collect(Collectors.toList());
134
135         if (keyAttributes.isEmpty()) {
136             return "";
137         } else {
138             Collections.sort(keyAttributes);
139             return "[" + String.join(" and ", keyAttributes) + "]";
140         }
141     }
142
143     private static DataSchemaNode getDataSchemaNodeByXpath(final String parentNodeXpath,
144         final SchemaContext schemaContext) {
145         final String[] xpathNodeIdSequence = xpathToNodeIdSequence(parentNodeXpath);
146         return findDataSchemaNodeByXpathNodeIdSequence(xpathNodeIdSequence, schemaContext.getChildNodes());
147     }
148
149     private static String[] xpathToNodeIdSequence(final String xpath) {
150         final String[] xpathNodeIdSequence = Arrays.stream(xpath.split(XPATH_DELIMITER_REGEX))
151             .map(identifier -> identifier.replaceFirst(XPATH_NODE_KEY_ATTRIBUTES_REGEX, ""))
152             .filter(identifier -> !identifier.isEmpty())
153             .toArray(String[]::new);
154         if (xpathNodeIdSequence.length < 1) {
155             throw new DataValidationException("Invalid xpath.", "Xpath contains no node identifiers.");
156         }
157         return xpathNodeIdSequence;
158     }
159
160     private static DataSchemaNode findDataSchemaNodeByXpathNodeIdSequence(final String[] xpathNodeIdSequence,
161         final Collection<? extends DataSchemaNode> dataSchemaNodes) {
162         final String currentXpathNodeId = xpathNodeIdSequence[0];
163         final DataSchemaNode currentDataSchemaNode = dataSchemaNodes.stream()
164             .filter(dataSchemaNode -> currentXpathNodeId.equals(dataSchemaNode.getQName().getLocalName()))
165             .findFirst().orElseThrow(() -> schemaNodeNotFoundException(currentXpathNodeId));
166         if (xpathNodeIdSequence.length <= 1) {
167             return currentDataSchemaNode;
168         }
169         if (currentDataSchemaNode instanceof DataNodeContainer) {
170             return findDataSchemaNodeByXpathNodeIdSequence(
171                 getNextLevelXpathNodeIdSequence(xpathNodeIdSequence),
172                 ((DataNodeContainer) currentDataSchemaNode).getChildNodes());
173         }
174         throw schemaNodeNotFoundException(xpathNodeIdSequence[1]);
175     }
176
177     private static String[] getNextLevelXpathNodeIdSequence(final String[] xpathNodeIdSequence) {
178         final var nextXpathNodeIdSequence = new String[xpathNodeIdSequence.length - 1];
179         System.arraycopy(xpathNodeIdSequence, 1, nextXpathNodeIdSequence, 0, nextXpathNodeIdSequence.length);
180         return nextXpathNodeIdSequence;
181     }
182
183     private static DataValidationException schemaNodeNotFoundException(final String schemaNodeIdentifier) {
184         return new DataValidationException("Invalid xpath.",
185             String.format("No schema node was found for xpath identifier '%s'.", schemaNodeIdentifier));
186     }
187 }