c2315959318d953b3e5368417d720a6f118249ce
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / repository / FragmentQueryBuilder.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Nordix Foundation
4  *  Modifications Copyright (C) 2023 TechMahindra Ltd.
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  *
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.spi.repository;
23
24 import java.util.HashMap;
25 import java.util.Map;
26 import javax.persistence.EntityManager;
27 import javax.persistence.PersistenceContext;
28 import javax.persistence.Query;
29 import lombok.RequiredArgsConstructor;
30 import lombok.extern.slf4j.Slf4j;
31 import org.onap.cps.cpspath.parser.CpsPathPrefixType;
32 import org.onap.cps.cpspath.parser.CpsPathQuery;
33 import org.onap.cps.spi.entities.FragmentEntity;
34 import org.onap.cps.utils.JsonObjectMapper;
35 import org.springframework.stereotype.Component;
36
37 @RequiredArgsConstructor
38 @Slf4j
39 @Component
40 public class FragmentQueryBuilder {
41     private static final String REGEX_ABSOLUTE_PATH_PREFIX = ".*\\/";
42     private static final String REGEX_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?";
43     private static final String REGEX_DESCENDANT_PATH_POSTFIX = "(\\/.*)?";
44     private static final String REGEX_END_OF_INPUT = "$";
45
46     @PersistenceContext
47     private EntityManager entityManager;
48
49     private final JsonObjectMapper jsonObjectMapper;
50
51     /**
52      * Create a sql query to retrieve by anchor(id) and cps path.
53      *
54      * @param anchorId the id of the anchor
55      * @param cpsPathQuery the cps path query to be transformed into a sql query
56      * @return a executable query object
57      */
58     public Query getQueryForAnchorAndCpsPath(final int anchorId, final CpsPathQuery cpsPathQuery) {
59         final StringBuilder sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE anchor_id = :anchorId");
60         final Map<String, Object> queryParameters = new HashMap<>();
61         queryParameters.put("anchorId", anchorId);
62         sqlStringBuilder.append(" AND xpath ~ :xpathRegex");
63         final String xpathRegex = getXpathSqlRegex(cpsPathQuery, false);
64         queryParameters.put("xpathRegex", xpathRegex);
65         if (cpsPathQuery.hasLeafConditions()) {
66             sqlStringBuilder.append(" AND attributes @> :leafDataAsJson\\:\\:jsonb");
67             queryParameters.put("leafDataAsJson", jsonObjectMapper.asJsonString(
68                 cpsPathQuery.getLeavesData()));
69         }
70
71         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
72         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
73         setQueryParameters(query, queryParameters);
74         return query;
75     }
76
77     /**
78      * Create a sql query to retrieve by cps path.
79      *
80      * @param cpsPathQuery the cps path query to be transformed into a sql query
81      * @return a executable query object
82      */
83     public Query getQueryForCpsPath(final CpsPathQuery cpsPathQuery) {
84         final StringBuilder sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE xpath ~ :xpathRegex");
85         final Map<String, Object> queryParameters = new HashMap<>();
86         final String xpathRegex = getXpathSqlRegex(cpsPathQuery, false);
87         queryParameters.put("xpathRegex", xpathRegex);
88         if (cpsPathQuery.hasLeafConditions()) {
89             sqlStringBuilder.append(" AND attributes @> :leafDataAsJson\\:\\:jsonb");
90             queryParameters.put("leafDataAsJson", jsonObjectMapper.asJsonString(
91                     cpsPathQuery.getLeavesData()));
92         }
93
94         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
95         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
96         setQueryParameters(query, queryParameters);
97         return query;
98     }
99
100     /**
101      * Create a regular expression (string) for xpath based on the given cps path query.
102      *
103      * @param cpsPathQuery  the cps path query to determine the required regular expression
104      * @param includeDescendants include descendants yes or no
105      * @return a string representing the required regular expression
106      */
107     public static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery, final boolean includeDescendants) {
108         final StringBuilder xpathRegexBuilder = new StringBuilder();
109         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
110             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
111         } else {
112             xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
113             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
114         }
115         xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
116         if (includeDescendants) {
117             xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_POSTFIX);
118         }
119         xpathRegexBuilder.append(REGEX_END_OF_INPUT);
120         return xpathRegexBuilder.toString();
121     }
122
123     private static String escapeXpath(final String xpath) {
124         // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
125         return xpath.replace("[@", "\\[@");
126     }
127
128     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
129         try {
130             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
131         } catch (final NumberFormatException e) {
132             return null;
133         }
134     }
135
136     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
137                                                  final StringBuilder sqlStringBuilder,
138                                                  final Map<String, Object> queryParameters) {
139         if (cpsPathQuery.hasTextFunctionCondition()) {
140             sqlStringBuilder.append(" AND (");
141             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
142             sqlStringBuilder
143                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
144             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
145             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
146             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
147             if (textValueAsInt != null) {
148                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
149                 sqlStringBuilder
150                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
151                 queryParameters.put("textValueAsInt", textValueAsInt);
152             }
153             sqlStringBuilder.append(")");
154         }
155     }
156
157     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
158         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
159             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
160         }
161     }
162
163 }