2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2022-2023 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.AnchorEntity;
37 import org.onap.cps.spi.entities.DataspaceEntity;
38 import org.onap.cps.spi.entities.FragmentEntity;
39 import org.onap.cps.utils.JsonObjectMapper;
40 import org.springframework.stereotype.Component;
42 @RequiredArgsConstructor
45 public class FragmentQueryBuilder {
46 private static final String REGEX_ABSOLUTE_PATH_PREFIX = "^";
47 private static final String REGEX_DESCENDANT_PATH_PREFIX = "^.*\\/";
48 private static final String REGEX_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?$";
49 private static final AnchorEntity ACROSS_ALL_ANCHORS = null;
52 private EntityManager entityManager;
54 private final JsonObjectMapper jsonObjectMapper;
57 * Create a sql query to retrieve by anchor(id) and cps path.
59 * @param anchorEntity the anchor
60 * @param cpsPathQuery the cps path query to be transformed into a sql query
61 * @return a executable query object
63 public Query getQueryForAnchorAndCpsPath(final AnchorEntity anchorEntity, final CpsPathQuery cpsPathQuery) {
64 return getQueryForDataspaceOrAnchorAndCpsPath(anchorEntity.getDataspace(), anchorEntity, cpsPathQuery);
68 * Create a sql query to retrieve by cps path.
70 * @param dataspaceEntity the dataspace
71 * @param cpsPathQuery the cps path query to be transformed into a sql query
72 * @return a executable query object
74 public Query getQueryForDataspaceAndCpsPath(final DataspaceEntity dataspaceEntity,
75 final CpsPathQuery cpsPathQuery) {
76 return getQueryForDataspaceOrAnchorAndCpsPath(dataspaceEntity, ACROSS_ALL_ANCHORS, cpsPathQuery);
79 private static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery) {
80 final StringBuilder xpathRegexBuilder = getRegexStringBuilderWithPrefix(cpsPathQuery);
81 xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
82 return xpathRegexBuilder.toString();
85 private Query getQueryForDataspaceOrAnchorAndCpsPath(final DataspaceEntity dataspaceEntity,
86 final AnchorEntity anchorEntity,
87 final CpsPathQuery cpsPathQuery) {
88 final StringBuilder sqlStringBuilder = new StringBuilder();
89 final Map<String, Object> queryParameters = new HashMap<>();
91 sqlStringBuilder.append("SELECT * FROM fragment WHERE ");
92 addDataspaceOrAnchor(sqlStringBuilder, queryParameters, dataspaceEntity, anchorEntity);
93 addXpathSearch(cpsPathQuery, sqlStringBuilder, queryParameters);
94 addLeafConditions(cpsPathQuery, sqlStringBuilder);
95 addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
96 addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
98 final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
99 setQueryParameters(query, queryParameters);
103 private static void addDataspaceOrAnchor(final StringBuilder sqlStringBuilder,
104 final Map<String, Object> queryParameters,
105 final DataspaceEntity dataspaceEntity,
106 final AnchorEntity anchorEntity) {
107 if (anchorEntity == ACROSS_ALL_ANCHORS) {
108 sqlStringBuilder.append("dataspace_id = :dataspaceId");
109 queryParameters.put("dataspaceId", dataspaceEntity.getId());
111 sqlStringBuilder.append("anchor_id = :anchorId");
112 queryParameters.put("anchorId", anchorEntity.getId());
116 private static void addXpathSearch(final CpsPathQuery cpsPathQuery,
117 final StringBuilder sqlStringBuilder,
118 final Map<String, Object> queryParameters) {
119 sqlStringBuilder.append(" AND xpath ~ :xpathRegex");
120 final String xpathRegex = getXpathSqlRegex(cpsPathQuery);
121 queryParameters.put("xpathRegex", xpathRegex);
124 private static StringBuilder getRegexStringBuilderWithPrefix(final CpsPathQuery cpsPathQuery) {
125 final StringBuilder xpathRegexBuilder = new StringBuilder();
126 if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
127 xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
128 xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
129 return xpathRegexBuilder;
131 xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_PREFIX);
132 xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
133 return xpathRegexBuilder;
136 private static String escapeXpath(final String xpath) {
137 // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
138 return xpath.replace("[@", "\\[@");
141 private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
143 return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
144 } catch (final NumberFormatException e) {
149 private void addLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
150 if (cpsPathQuery.hasLeafConditions()) {
151 sqlStringBuilder.append(" AND (");
152 final List<String> queryBooleanOperatorsType = cpsPathQuery.getBooleanOperatorsType();
153 final Queue<String> booleanOperatorsQueue = (queryBooleanOperatorsType == null) ? null : new LinkedList<>(
154 queryBooleanOperatorsType);
155 cpsPathQuery.getLeavesData().entrySet().forEach(entry -> {
156 sqlStringBuilder.append(" attributes @> ");
157 sqlStringBuilder.append("'");
158 sqlStringBuilder.append(jsonObjectMapper.asJsonString(entry));
159 sqlStringBuilder.append("'");
160 if (!(booleanOperatorsQueue == null || booleanOperatorsQueue.isEmpty())) {
161 sqlStringBuilder.append(" ");
162 sqlStringBuilder.append(booleanOperatorsQueue.poll());
163 sqlStringBuilder.append(" ");
166 sqlStringBuilder.append(")");
170 private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
171 final StringBuilder sqlStringBuilder,
172 final Map<String, Object> queryParameters) {
173 if (cpsPathQuery.hasTextFunctionCondition()) {
174 sqlStringBuilder.append(" AND (");
175 sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
177 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
178 queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
179 queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
180 final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
181 if (textValueAsInt != null) {
182 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
184 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
185 queryParameters.put("textValueAsInt", textValueAsInt);
187 sqlStringBuilder.append(")");
191 private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
192 final StringBuilder sqlStringBuilder,
193 final Map<String, Object> queryParameters) {
194 if (cpsPathQuery.hasContainsFunctionCondition()) {
195 sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
196 queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
197 queryParameters.put("containsValue", cpsPathQuery.getContainsFunctionConditionValue());
201 private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
202 for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
203 query.setParameter(queryParameter.getKey(), queryParameter.getValue());