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
10 * 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.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.cps.spi.repository;
24 import java.util.HashMap;
25 import java.util.LinkedList;
26 import java.util.List;
28 import java.util.Queue;
29 import javax.persistence.EntityManager;
30 import javax.persistence.PersistenceContext;
31 import javax.persistence.Query;
32 import lombok.RequiredArgsConstructor;
33 import lombok.extern.slf4j.Slf4j;
34 import org.onap.cps.cpspath.parser.CpsPathPrefixType;
35 import org.onap.cps.cpspath.parser.CpsPathQuery;
36 import org.onap.cps.spi.entities.FragmentEntity;
37 import org.onap.cps.utils.JsonObjectMapper;
38 import org.springframework.stereotype.Component;
40 @RequiredArgsConstructor
43 public class FragmentQueryBuilder {
44 private static final String REGEX_ABSOLUTE_PATH_PREFIX = "^";
45 private static final String REGEX_DESCENDANT_PATH_PREFIX = "^.*\\/";
46 private static final String REGEX_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?$";
47 private static final String REGEX_FOR_QUICK_FIND_WITH_DESCENDANTS = "(\\[@.*?])?(\\/.*)?$";
50 private EntityManager entityManager;
52 private final JsonObjectMapper jsonObjectMapper;
55 * Create a sql query to retrieve by anchor(id) and cps path.
57 * @param anchorId the id of the anchor
58 * @param cpsPathQuery the cps path query to be transformed into a sql query
59 * @return a executable query object
61 public Query getQueryForAnchorAndCpsPath(final int anchorId, final CpsPathQuery cpsPathQuery) {
62 final StringBuilder sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE anchor_id = :anchorId");
63 final Map<String, Object> queryParameters = new HashMap<>();
64 queryParameters.put("anchorId", anchorId);
65 sqlStringBuilder.append(" AND xpath ~ :xpathRegex");
66 return getQuery(cpsPathQuery, sqlStringBuilder, queryParameters);
70 * Create a sql query to retrieve by cps path.
72 * @param cpsPathQuery the cps path query to be transformed into a sql query
73 * @return a executable query object
75 public Query getQueryForCpsPath(final CpsPathQuery cpsPathQuery) {
76 final StringBuilder sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE xpath ~ :xpathRegex");
77 final Map<String, Object> queryParameters = new HashMap<>();
78 return getQuery(cpsPathQuery, sqlStringBuilder, queryParameters);
82 * Create a regular expression (string) for matching xpaths based on the given cps path query.
84 * @param cpsPathQuery the cps path query to determine the required regular expression
85 * @return a string representing the required regular expression
87 public static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery) {
88 final StringBuilder xpathRegexBuilder = getRegexStringBuilderWithPrefix(cpsPathQuery);
89 xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
90 return xpathRegexBuilder.toString();
94 * Create a regular expression (string) for matching xpaths with (all) descendants
95 * based on the given cps path query.
97 * @param cpsPathQuery the cps path query to determine the required regular expression
98 * @return a string representing the required regular expression
100 public static String getXpathSqlRegexForQuickFindWithDescendants(final CpsPathQuery cpsPathQuery) {
101 final StringBuilder xpathRegexBuilder = getRegexStringBuilderWithPrefix(cpsPathQuery);
102 xpathRegexBuilder.append(REGEX_FOR_QUICK_FIND_WITH_DESCENDANTS);
103 return xpathRegexBuilder.toString();
106 private Query getQuery(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder,
107 final Map<String, Object> queryParameters) {
108 final String xpathRegex = getXpathSqlRegex(cpsPathQuery);
109 queryParameters.put("xpathRegex", xpathRegex);
110 final List<String> queryBooleanOperatorsType = cpsPathQuery.getBooleanOperatorsType();
111 if (cpsPathQuery.hasLeafConditions()) {
112 sqlStringBuilder.append(" AND (");
113 final Queue<String> booleanOperatorsQueue = (queryBooleanOperatorsType == null) ? null : new LinkedList<>(
114 queryBooleanOperatorsType);
115 cpsPathQuery.getLeavesData().entrySet().forEach(entry -> {
116 sqlStringBuilder.append(" attributes @> ");
117 sqlStringBuilder.append("'" + jsonObjectMapper.asJsonString(entry) + "'");
118 if (!(booleanOperatorsQueue == null || booleanOperatorsQueue.isEmpty())) {
119 sqlStringBuilder.append(" " + booleanOperatorsQueue.poll() + " ");
122 sqlStringBuilder.append(")");
124 addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
125 addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
126 final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
127 setQueryParameters(query, queryParameters);
131 private static StringBuilder getRegexStringBuilderWithPrefix(final CpsPathQuery cpsPathQuery) {
132 final StringBuilder xpathRegexBuilder = new StringBuilder();
133 if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
134 xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
135 xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
136 return xpathRegexBuilder;
138 xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_PREFIX);
139 xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
140 return xpathRegexBuilder;
143 private static String escapeXpath(final String xpath) {
144 // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
145 return xpath.replace("[@", "\\[@");
148 private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
150 return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
151 } catch (final NumberFormatException e) {
156 private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
157 final StringBuilder sqlStringBuilder,
158 final Map<String, Object> queryParameters) {
159 if (cpsPathQuery.hasTextFunctionCondition()) {
160 sqlStringBuilder.append(" AND (");
161 sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
163 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
164 queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
165 queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
166 final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
167 if (textValueAsInt != null) {
168 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
170 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
171 queryParameters.put("textValueAsInt", textValueAsInt);
173 sqlStringBuilder.append(")");
177 private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
178 final StringBuilder sqlStringBuilder,
179 final Map<String, Object> queryParameters) {
180 if (cpsPathQuery.hasContainsFunctionCondition()) {
181 sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
182 queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
183 queryParameters.put("containsValue", cpsPathQuery.getContainsFunctionConditionValue());
187 private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
188 for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
189 query.setParameter(queryParameter.getKey(), queryParameter.getValue());