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.apache.commons.collections4.CollectionUtils;
35 import org.onap.cps.cpspath.parser.CpsPathPrefixType;
36 import org.onap.cps.cpspath.parser.CpsPathQuery;
37 import org.onap.cps.spi.entities.FragmentEntity;
38 import org.onap.cps.utils.JsonObjectMapper;
39 import org.springframework.stereotype.Component;
41 @RequiredArgsConstructor
44 public class FragmentQueryBuilder {
45 private static final String REGEX_ABSOLUTE_PATH_PREFIX = ".*\\/";
46 private static final String REGEX_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?";
47 private static final String REGEX_DESCENDANT_PATH_POSTFIX = "(\\/.*)?";
48 private static final String REGEX_END_OF_INPUT = "$";
51 private EntityManager entityManager;
53 private final JsonObjectMapper jsonObjectMapper;
56 * Create a sql query to retrieve by anchor(id) and cps path.
58 * @param anchorId the id of the anchor
59 * @param cpsPathQuery the cps path query to be transformed into a sql query
60 * @return a executable query object
62 public Query getQueryForAnchorAndCpsPath(final int anchorId, final CpsPathQuery cpsPathQuery) {
63 final StringBuilder sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE anchor_id = :anchorId");
64 final Map<String, Object> queryParameters = new HashMap<>();
65 queryParameters.put("anchorId", anchorId);
66 sqlStringBuilder.append(" AND xpath ~ :xpathRegex");
67 return getQuery(cpsPathQuery, sqlStringBuilder, queryParameters);
71 * Create a sql query to retrieve by cps path.
73 * @param cpsPathQuery the cps path query to be transformed into a sql query
74 * @return a executable query object
76 public Query getQueryForCpsPath(final CpsPathQuery cpsPathQuery) {
77 final StringBuilder sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE xpath ~ :xpathRegex");
78 final Map<String, Object> queryParameters = new HashMap<>();
79 return getQuery(cpsPathQuery, sqlStringBuilder, queryParameters);
82 private Query getQuery(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder,
83 final Map<String, Object> queryParameters) {
84 final String xpathRegex = getXpathSqlRegex(cpsPathQuery, false);
85 queryParameters.put("xpathRegex", xpathRegex);
86 final List<String> queryBooleanOperatorsType = cpsPathQuery.getBooleanOperatorsType();
87 if (cpsPathQuery.hasLeafConditions()) {
88 sqlStringBuilder.append(" AND (");
89 final Queue<String> booleanOperatorsQueue = (queryBooleanOperatorsType == null) ? null : new LinkedList<>(
90 queryBooleanOperatorsType);
91 cpsPathQuery.getLeavesData().entrySet().forEach(entry -> {
92 sqlStringBuilder.append(" attributes @> ");
93 sqlStringBuilder.append("'" + jsonObjectMapper.asJsonString(entry) + "'");
94 if (!CollectionUtils.isEmpty(booleanOperatorsQueue)) {
95 sqlStringBuilder.append(" " + booleanOperatorsQueue.poll() + " ");
98 sqlStringBuilder.append(")");
100 addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
101 final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
102 setQueryParameters(query, queryParameters);
107 * Create a regular expression (string) for xpath based on the given cps path query.
109 * @param cpsPathQuery the cps path query to determine the required regular expression
110 * @param includeDescendants include descendants yes or no
111 * @return a string representing the required regular expression
113 public static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery, final boolean includeDescendants) {
114 final StringBuilder xpathRegexBuilder = new StringBuilder();
115 if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
116 xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
118 xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
119 xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
121 xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
122 if (includeDescendants) {
123 xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_POSTFIX);
125 xpathRegexBuilder.append(REGEX_END_OF_INPUT);
126 return xpathRegexBuilder.toString();
129 private static String escapeXpath(final String xpath) {
130 // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
131 return xpath.replace("[@", "\\[@");
134 private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
136 return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
137 } catch (final NumberFormatException e) {
142 private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
143 final StringBuilder sqlStringBuilder,
144 final Map<String, Object> queryParameters) {
145 if (cpsPathQuery.hasTextFunctionCondition()) {
146 sqlStringBuilder.append(" AND (");
147 sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
149 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
150 queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
151 queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
152 final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
153 if (textValueAsInt != null) {
154 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
156 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
157 queryParameters.put("textValueAsInt", textValueAsInt);
159 sqlStringBuilder.append(")");
163 private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
164 for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
165 query.setParameter(queryParameter.getKey(), queryParameter.getValue());