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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.cps.utils;
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;
51 @NoArgsConstructor(access = AccessLevel.PRIVATE)
52 public class YangUtils {
54 private static final String XPATH_DELIMITER_REGEX = "\\/";
55 private static final String XPATH_NODE_KEY_ATTRIBUTES_REGEX = "\\[.+";
58 * Parses jsonData into NormalizedNode according to given schema context.
60 * @param jsonData json data as string
61 * @param schemaContext schema context describing associated data model
62 * @return the NormalizedNode object
64 @SuppressWarnings("squid:S1452") // Generic type <? ,?> is returned by external librray, opendaylight.yangtools
65 public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext) {
66 return parseJsonData(jsonData, schemaContext, Optional.empty());
70 * Parses jsonData into NormalizedNode according to given schema context.
72 * @param jsonData json data fragment as string
73 * @param schemaContext schema context describing associated data model
74 * @param parentNodeXpath the xpath referencing the parent node current data fragment belong to
75 * @return the NormalizedNode object
77 @SuppressWarnings("squid:S1452") // Generic type <? ,?> is returned by external librray, opendaylight.yangtools
78 public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
79 final String parentNodeXpath) {
80 final var parentSchemaNode = getDataSchemaNodeByXpath(parentNodeXpath, schemaContext);
81 return parseJsonData(jsonData, schemaContext, Optional.of(parentSchemaNode));
84 private static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
85 final Optional<DataSchemaNode> optionalParentSchemaNode) {
86 final var jsonCodecFactory = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
87 .getShared((EffectiveModelContext) schemaContext);
88 final var normalizedNodeResult = new NormalizedNodeResult();
89 final var normalizedNodeStreamWriter = ImmutableNormalizedNodeStreamWriter
90 .from(normalizedNodeResult);
92 try (final JsonParserStream jsonParserStream = optionalParentSchemaNode.isPresent()
93 ? JsonParserStream.create(normalizedNodeStreamWriter, jsonCodecFactory, optionalParentSchemaNode.get())
94 : JsonParserStream.create(normalizedNodeStreamWriter, jsonCodecFactory)
96 final var jsonReader = new JsonReader(new StringReader(jsonData));
97 jsonParserStream.parse(jsonReader);
99 } catch (final IOException | JsonSyntaxException exception) {
100 throw new DataValidationException(
101 "Failed to parse json data: " + jsonData, exception.getMessage(), exception);
102 } catch (final IllegalStateException illegalStateException) {
103 throw new DataValidationException(
104 "Failed to parse json data. Unsupported xpath or json data:" + jsonData, illegalStateException
105 .getMessage(), illegalStateException);
107 return normalizedNodeResult.getResult();
111 * Create an xpath form a Yang Tools NodeIdentifier (i.e. PathArgument).
113 * @param nodeIdentifier the NodeIdentifier
116 public static String buildXpath(final YangInstanceIdentifier.PathArgument nodeIdentifier) {
117 final var xpathBuilder = new StringBuilder();
118 xpathBuilder.append("/").append(nodeIdentifier.getNodeType().getLocalName());
120 if (nodeIdentifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
121 xpathBuilder.append(getKeyAttributesStatement(
122 (YangInstanceIdentifier.NodeIdentifierWithPredicates) nodeIdentifier));
124 return xpathBuilder.toString();
127 private static String getKeyAttributesStatement(
128 final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifier) {
129 final List<String> keyAttributes = nodeIdentifier.entrySet().stream().map(
131 final String name = entry.getKey().getLocalName();
132 final String value = String.valueOf(entry.getValue()).replace("'", "\\'");
133 return String.format("@%s='%s'", name, value);
135 ).collect(Collectors.toList());
137 if (keyAttributes.isEmpty()) {
140 Collections.sort(keyAttributes);
141 return "[" + String.join(" and ", keyAttributes) + "]";
145 private static DataSchemaNode getDataSchemaNodeByXpath(final String parentNodeXpath,
146 final SchemaContext schemaContext) {
147 final String[] xpathNodeIdSequence = xpathToNodeIdSequence(parentNodeXpath);
148 return findDataSchemaNodeByXpathNodeIdSequence(xpathNodeIdSequence, schemaContext.getChildNodes());
151 private static String[] xpathToNodeIdSequence(final String xpath) {
152 final String[] xpathNodeIdSequence = Arrays.stream(xpath.split(XPATH_DELIMITER_REGEX))
153 .map(identifier -> identifier.replaceFirst(XPATH_NODE_KEY_ATTRIBUTES_REGEX, ""))
154 .filter(identifier -> !identifier.isEmpty())
155 .toArray(String[]::new);
156 if (xpathNodeIdSequence.length < 1) {
157 throw new DataValidationException("Invalid xpath.", "Xpath contains no node identifiers.");
159 return xpathNodeIdSequence;
162 private static DataSchemaNode findDataSchemaNodeByXpathNodeIdSequence(final String[] xpathNodeIdSequence,
163 final Collection<? extends DataSchemaNode> dataSchemaNodes) {
164 final String currentXpathNodeId = xpathNodeIdSequence[0];
165 final DataSchemaNode currentDataSchemaNode = dataSchemaNodes.stream()
166 .filter(dataSchemaNode -> currentXpathNodeId.equals(dataSchemaNode.getQName().getLocalName()))
167 .findFirst().orElseThrow(() -> schemaNodeNotFoundException(currentXpathNodeId));
168 if (xpathNodeIdSequence.length <= 1) {
169 return currentDataSchemaNode;
171 if (currentDataSchemaNode instanceof DataNodeContainer) {
172 return findDataSchemaNodeByXpathNodeIdSequence(
173 getNextLevelXpathNodeIdSequence(xpathNodeIdSequence),
174 ((DataNodeContainer) currentDataSchemaNode).getChildNodes());
176 throw schemaNodeNotFoundException(xpathNodeIdSequence[1]);
179 private static String[] getNextLevelXpathNodeIdSequence(final String[] xpathNodeIdSequence) {
180 final var nextXpathNodeIdSequence = new String[xpathNodeIdSequence.length - 1];
181 System.arraycopy(xpathNodeIdSequence, 1, nextXpathNodeIdSequence, 0, nextXpathNodeIdSequence.length);
182 return nextXpathNodeIdSequence;
185 private static DataValidationException schemaNodeNotFoundException(final String schemaNodeIdentifier) {
186 return new DataValidationException("Invalid xpath.",
187 String.format("No schema node was found for xpath identifier '%s'.", schemaNodeIdentifier));