Internal Server Error when creating the same data node twice
[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.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.api.schema.stream.NormalizedNodeStreamWriter;
41 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
42 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
43 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
44 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
45 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
46 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
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
57     /**
58      * Parses jsonData into NormalizedNode according to given schema context.
59      *
60      * @param jsonData      json data as string
61      * @param schemaContext schema context describing associated data model
62      * @return the NormalizedNode object
63      */
64     public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext) {
65         return parseJsonData(jsonData, schemaContext, Optional.empty());
66     }
67
68     /**
69      * Parses jsonData into NormalizedNode according to given schema context.
70      *
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
75      */
76     public static NormalizedNode<?, ?> parseJsonData(final String jsonData, final SchemaContext schemaContext,
77         final String parentNodeXpath) {
78         final DataSchemaNode 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 JSONCodecFactory jsonCodecFactory = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
85             .getShared(schemaContext);
86         final NormalizedNodeResult normalizedNodeResult = new NormalizedNodeResult();
87         final NormalizedNodeStreamWriter 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 JsonReader jsonReader = new JsonReader(new StringReader(jsonData));
95             jsonParserStream.parse(jsonReader);
96
97         } catch (final IOException | IllegalStateException | JsonSyntaxException exception) {
98             throw new DataValidationException("Failed to parse json data.", String
99                 .format("Exception occurred on parsing string %s.", jsonData), exception);
100         }
101         return normalizedNodeResult.getResult();
102     }
103
104     /**
105      * Create an xpath form a Yang Tools NodeIdentifier (i.e. PathArgument).
106      *
107      * @param nodeIdentifier the NodeIdentifier
108      * @return an xpath
109      */
110     public static String buildXpath(final YangInstanceIdentifier.PathArgument nodeIdentifier) {
111         final StringBuilder xpathBuilder = new StringBuilder();
112         xpathBuilder.append("/").append(nodeIdentifier.getNodeType().getLocalName());
113
114         if (nodeIdentifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
115             xpathBuilder.append(getKeyAttributesStatement(
116                 (YangInstanceIdentifier.NodeIdentifierWithPredicates) nodeIdentifier));
117         }
118         return xpathBuilder.toString();
119     }
120
121     private static String getKeyAttributesStatement(
122         final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifier) {
123         final List<String> keyAttributes = nodeIdentifier.entrySet().stream().map(
124             entry -> {
125                 final String name = entry.getKey().getLocalName();
126                 final String value = String.valueOf(entry.getValue()).replace("'", "\\'");
127                 return String.format("@%s='%s'", name, value);
128             }
129         ).collect(Collectors.toList());
130
131         if (keyAttributes.isEmpty()) {
132             return "";
133         } else {
134             Collections.sort(keyAttributes);
135             return "[" + String.join(" and ", keyAttributes) + "]";
136         }
137     }
138
139     private static DataSchemaNode getDataSchemaNodeByXpath(final String parentNodeXpath,
140         final SchemaContext schemaContext) {
141         final String[] xpathNodeIdSequence = xpathToNodeIdSequence(parentNodeXpath);
142         return findDataSchemaNodeByXpathNodeIdSequence(xpathNodeIdSequence, schemaContext.getChildNodes());
143     }
144
145     private static String[] xpathToNodeIdSequence(final String xpath) {
146         final String[] xpathNodeIdSequence = Arrays.stream(xpath.split(XPATH_DELIMITER_REGEX))
147             .map(identifier -> identifier.replaceFirst(XPATH_NODE_KEY_ATTRIBUTES_REGEX, ""))
148             .filter(identifier -> !identifier.isEmpty())
149             .toArray(String[]::new);
150         if (xpathNodeIdSequence.length < 1) {
151             throw new DataValidationException("Invalid xpath.", "Xpath contains no node identifiers.");
152         }
153         return xpathNodeIdSequence;
154     }
155
156     private static DataSchemaNode findDataSchemaNodeByXpathNodeIdSequence(final String[] xpathNodeIdSequence,
157         final Collection<? extends DataSchemaNode> dataSchemaNodes) {
158         final String currentXpathNodeId = xpathNodeIdSequence[0];
159         final DataSchemaNode currentDataSchemaNode = dataSchemaNodes.stream()
160             .filter(dataSchemaNode -> currentXpathNodeId.equals(dataSchemaNode.getQName().getLocalName()))
161             .findFirst().orElseThrow(() -> schemaNodeNotFoundException(currentXpathNodeId));
162         if (xpathNodeIdSequence.length <= 1) {
163             return currentDataSchemaNode;
164         }
165         if (currentDataSchemaNode instanceof DataNodeContainer) {
166             return findDataSchemaNodeByXpathNodeIdSequence(
167                 getNextLevelXpathNodeIdSequence(xpathNodeIdSequence),
168                 ((DataNodeContainer) currentDataSchemaNode).getChildNodes());
169         }
170         throw schemaNodeNotFoundException(xpathNodeIdSequence[1]);
171     }
172
173     private static String[] getNextLevelXpathNodeIdSequence(final String[] xpathNodeIdSequence) {
174         final String[] nextXpathNodeIdSequence = new String[xpathNodeIdSequence.length - 1];
175         System.arraycopy(xpathNodeIdSequence, 1, nextXpathNodeIdSequence, 0, nextXpathNodeIdSequence.length);
176         return nextXpathNodeIdSequence;
177     }
178
179     private static DataValidationException schemaNodeNotFoundException(final String schemaNodeIdentifier) {
180         return new DataValidationException("Invalid xpath.",
181             String.format("No schema node was found for xpath identifier '%s'.", schemaNodeIdentifier));
182     }
183 }