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;
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;
37 @RequiredArgsConstructor
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 = "$";
47 private EntityManager entityManager;
49 private final JsonObjectMapper jsonObjectMapper;
52 * Create a sql query to retrieve by anchor(id) and cps path.
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
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()));
71 addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
72 final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
73 setQueryParameters(query, queryParameters);
78 * Create a sql query to retrieve by cps path.
80 * @param cpsPathQuery the cps path query to be transformed into a sql query
81 * @return a executable query object
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()));
94 addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
95 final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
96 setQueryParameters(query, queryParameters);
101 * Create a regular expression (string) for xpath based on the given cps path query.
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
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()));
112 xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
113 xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
115 xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
116 if (includeDescendants) {
117 xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_POSTFIX);
119 xpathRegexBuilder.append(REGEX_END_OF_INPUT);
120 return xpathRegexBuilder.toString();
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("[@", "\\[@");
128 private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
130 return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
131 } catch (final NumberFormatException e) {
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)");
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)");
150 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
151 queryParameters.put("textValueAsInt", textValueAsInt);
153 sqlStringBuilder.append(")");
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());