Fix for quickfind with descendants incl. list entries
[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.LinkedList;
26 import java.util.List;
27 import java.util.Map;
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;
39
40 @RequiredArgsConstructor
41 @Slf4j
42 @Component
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 = "(\\[@.*?])?(\\/.*)?$";
48
49     @PersistenceContext
50     private EntityManager entityManager;
51
52     private final JsonObjectMapper jsonObjectMapper;
53
54     /**
55      * Create a sql query to retrieve by anchor(id) and cps path.
56      *
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
60      */
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);
67     }
68
69     /**
70      * Create a sql query to retrieve by cps path.
71      *
72      * @param cpsPathQuery the cps path query to be transformed into a sql query
73      * @return a executable query object
74      */
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);
79     }
80
81     /**
82      * Create a regular expression (string) for matching xpaths based on the given cps path query.
83      *
84      * @param cpsPathQuery the cps path query to determine the required regular expression
85      * @return a string representing the required regular expression
86      */
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();
91     }
92
93     /**
94      * Create a regular expression (string) for matching xpaths with (all) descendants
95      * based on the given cps path query.
96      *
97      * @param cpsPathQuery the cps path query to determine the required regular expression
98      * @return a string representing the required regular expression
99      */
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();
104     }
105
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() + " ");
120                 }
121             });
122             sqlStringBuilder.append(")");
123         }
124         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
125         addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
126         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
127         setQueryParameters(query, queryParameters);
128         return query;
129     }
130
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;
137         }
138         xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_PREFIX);
139         xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
140         return xpathRegexBuilder;
141     }
142
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("[@", "\\[@");
146     }
147
148     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
149         try {
150             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
151         } catch (final NumberFormatException e) {
152             return null;
153         }
154     }
155
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)");
162             sqlStringBuilder
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)");
169                 sqlStringBuilder
170                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
171                 queryParameters.put("textValueAsInt", textValueAsInt);
172             }
173             sqlStringBuilder.append(")");
174         }
175     }
176
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());
184         }
185     }
186
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());
190         }
191     }
192
193 }