1244d54afbd3075a6c417a560a91d264614a3bf0
[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  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.utils;
22
23 import com.google.gson.stream.JsonReader;
24 import java.io.IOException;
25 import java.io.StringReader;
26 import java.util.Collections;
27 import java.util.List;
28 import java.util.stream.Collectors;
29 import lombok.extern.slf4j.Slf4j;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
33 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactory;
34 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
35 import org.opendaylight.yangtools.yang.data.codec.gson.JsonParserStream;
36 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
37 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39
40 @Slf4j
41 public class YangUtils {
42
43
44     private YangUtils() {
45         // Private constructor fo security reasons
46     }
47
48     /**
49      * Parse a string containing json data for a certain model (schemaContext).
50      *
51      * @param jsonData      a string containing json data for the given model
52      * @param schemaContext the SchemaContext for the given data
53      * @return the NormalizedNode representing the json data
54      */
55     public static NormalizedNode parseJsonData(final String jsonData, final SchemaContext schemaContext)
56             throws IOException {
57         final JSONCodecFactory jsonCodecFactory = JSONCodecFactorySupplier.DRAFT_LHOTKA_NETMOD_YANG_JSON_02
58                 .getShared(schemaContext);
59         final NormalizedNodeResult normalizedNodeResult = new NormalizedNodeResult();
60         final NormalizedNodeStreamWriter normalizedNodeStreamWriter = ImmutableNormalizedNodeStreamWriter
61                 .from(normalizedNodeResult);
62         try (final JsonParserStream jsonParserStream = JsonParserStream
63                 .create(normalizedNodeStreamWriter, jsonCodecFactory)) {
64             final JsonReader jsonReader = new JsonReader(new StringReader(jsonData));
65             jsonParserStream.parse(jsonReader);
66         }
67         return normalizedNodeResult.getResult();
68     }
69
70     /**
71      * Create an xpath form a Yang Tools NodeIdentifier (i.e. PathArgument).
72      * @param nodeIdentifier the NodeIdentifier
73      * @return an xpath
74      */
75     public static String buildXpath(final YangInstanceIdentifier.PathArgument nodeIdentifier) {
76         final StringBuilder xpathBuilder = new StringBuilder();
77         xpathBuilder.append("/").append(nodeIdentifier.getNodeType().getLocalName());
78
79         if (nodeIdentifier instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
80             xpathBuilder.append(getKeyAttributesStatement(
81                     (YangInstanceIdentifier.NodeIdentifierWithPredicates) nodeIdentifier));
82         }
83         return xpathBuilder.toString();
84     }
85
86     private static String getKeyAttributesStatement(
87             final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeIdentifier) {
88         final List<String> keyAttributes = nodeIdentifier.entrySet().stream().map(
89             entry -> {
90                 final String name = entry.getKey().getLocalName();
91                 final String value = String.valueOf(entry.getValue()).replace("'", "\\'");
92                 return String.format("@%s='%s'", name, value);
93             }
94         ).collect(Collectors.toList());
95
96         if (keyAttributes.isEmpty()) {
97             return "";
98         } else {
99             Collections.sort(keyAttributes);
100             return "[" + String.join(" and ", keyAttributes) + "]";
101         }
102     }
103 }