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.SchemaContext;
50 @NoArgsConstructor(access = AccessLevel.PRIVATE)
51 public class YangUtils {
53 private static final String XPATH_DELIMITER_REGEX = "\\/";
54 private static final String XPATH_NODE_KEY_ATTRIBUTES_REGEX = "\\[.+";
57 * Parses jsonData into NormalizedNode according to given schema context.
59 * @param jsonData json data as string
60 * @param schemaContext schema context describing associated data model
61 * @return the NormalizedNode object
63 @SuppressWarnings("squid:S1452") // Generic type <? ,?> is returned by external librray, opendaylight.yangtools
64 public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext) {
65 return parseJsonData(jsonData, schemaContext, Optional.empty());
69 * Parses jsonData into NormalizedNode according to given schema context.
71 * @param jsonData json data fragment as string
72 * @param schemaContext schema context describing associated data model
73 * @param parentNodeXpath the xpath referencing the parent node current data fragment belong to
74 * @return the NormalizedNode object
76 @SuppressWarnings("squid:S1452") // Generic type <? ,?> is returned by external librray, opendaylight.yangtools
77 public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
78 final String parentNodeXpath) {
79 final var parentSchemaNode = getDataSchemaNodeByXpath(parentNodeXpath, schemaContext);
80 return parseJsonData(jsonData, schemaContext, Optional.of(parentSchemaNode));
83 private static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
84 final Optional<DataSchemaNode> optionalParentSchemaNode) {
85 final var jsonCodecFactory = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
86 .getShared(schemaContext);
87 final var normalizedNodeResult = new NormalizedNodeResult();
88 final var normalizedNodeStreamWriter = ImmutableNormalizedNodeStreamWriter
89 .from(normalizedNodeResult);
91 try (final JsonParserStream jsonParserStream = optionalParentSchemaNode.isPresent()
92 ? JsonParserStream.create(normalizedNodeStreamWriter, jsonCodecFactory, optionalParentSchemaNode.get())
93 : JsonParserStream.create(normalizedNodeStreamWriter, jsonCodecFactory)
95 final var jsonReader = new JsonReader(new StringReader(jsonData));
96 jsonParserStream.parse(jsonReader);
98 } catch (final IOException | JsonSyntaxException exception) {
99 throw new DataValidationException(
100 "Failed to parse json data: " + jsonData, exception.getMessage(), exception);
101 } catch (final IllegalStateException illegalStateException) {
102 throw new DataValidationException(
103 "Failed to parse json data. Unsupported xpath or json data:" + jsonData, illegalStateException
104 .getMessage(), illegalStateException);
106 return normalizedNodeResult.getResult();
110 * Create an xpath form a Yang Tools NodeIdentifier (i.e. PathArgument).
112 * @param nodeIdentifier the NodeIdentifier
115 public static String buildXpath(final YangInstanceIdentifier.PathArgument nodeIdentifier) {
116 final var xpathBuilder = new StringBuilder();
117 xpathBuilder.append("/").append(nodeIdentifier.getNodeType().getLocalName());
119 if (nodeIdentifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
120 xpathBuilder.append(getKeyAttributesStatement(
121 (YangInstanceIdentifier.NodeIdentifierWithPredicates) nodeIdentifier));
123 return xpathBuilder.toString();
126 private static String getKeyAttributesStatement(
127 final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifier) {
128 final List<String> keyAttributes = nodeIdentifier.entrySet().stream().map(
130 final String name = entry.getKey().getLocalName();
131 final String value = String.valueOf(entry.getValue()).replace("'", "\\'");
132 return String.format("@%s='%s'", name, value);
134 ).collect(Collectors.toList());
136 if (keyAttributes.isEmpty()) {
139 Collections.sort(keyAttributes);
140 return "[" + String.join(" and ", keyAttributes) + "]";
144 private static DataSchemaNode getDataSchemaNodeByXpath(final String parentNodeXpath,
145 final SchemaContext schemaContext) {
146 final String[] xpathNodeIdSequence = xpathToNodeIdSequence(parentNodeXpath);
147 return findDataSchemaNodeByXpathNodeIdSequence(xpathNodeIdSequence, schemaContext.getChildNodes());
150 private static String[] xpathToNodeIdSequence(final String xpath) {
151 final String[] xpathNodeIdSequence = Arrays.stream(xpath.split(XPATH_DELIMITER_REGEX))
152 .map(identifier -> identifier.replaceFirst(XPATH_NODE_KEY_ATTRIBUTES_REGEX, ""))
153 .filter(identifier -> !identifier.isEmpty())
154 .toArray(String[]::new);
155 if (xpathNodeIdSequence.length < 1) {
156 throw new DataValidationException("Invalid xpath.", "Xpath contains no node identifiers.");
158 return xpathNodeIdSequence;
161 private static DataSchemaNode findDataSchemaNodeByXpathNodeIdSequence(final String[] xpathNodeIdSequence,
162 final Collection<? extends DataSchemaNode> dataSchemaNodes) {
163 final String currentXpathNodeId = xpathNodeIdSequence[0];
164 final DataSchemaNode currentDataSchemaNode = dataSchemaNodes.stream()
165 .filter(dataSchemaNode -> currentXpathNodeId.equals(dataSchemaNode.getQName().getLocalName()))
166 .findFirst().orElseThrow(() -> schemaNodeNotFoundException(currentXpathNodeId));
167 if (xpathNodeIdSequence.length <= 1) {
168 return currentDataSchemaNode;
170 if (currentDataSchemaNode instanceof DataNodeContainer) {
171 return findDataSchemaNodeByXpathNodeIdSequence(
172 getNextLevelXpathNodeIdSequence(xpathNodeIdSequence),
173 ((DataNodeContainer) currentDataSchemaNode).getChildNodes());
175 throw schemaNodeNotFoundException(xpathNodeIdSequence[1]);
178 private static String[] getNextLevelXpathNodeIdSequence(final String[] xpathNodeIdSequence) {
179 final var nextXpathNodeIdSequence = new String[xpathNodeIdSequence.length - 1];
180 System.arraycopy(xpathNodeIdSequence, 1, nextXpathNodeIdSequence, 0, nextXpathNodeIdSequence.length);
181 return nextXpathNodeIdSequence;
184 private static DataValidationException schemaNodeNotFoundException(final String schemaNodeIdentifier) {
185 return new DataValidationException("Invalid xpath.",
186 String.format("No schema node was found for xpath identifier '%s'.", schemaNodeIdentifier));