Merge "Add contains condition support to cps-path"
[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_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?";
46     private static final String REGEX_DESCENDANT_PATH_POSTFIX = "(\\/.*)?";
47     private static final String REGEX_END_OF_INPUT = "$";
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     private Query getQuery(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder,
82                            final Map<String, Object> queryParameters) {
83         final String xpathRegex = getXpathSqlRegex(cpsPathQuery, false);
84         queryParameters.put("xpathRegex", xpathRegex);
85         final List<String> queryBooleanOperatorsType = cpsPathQuery.getBooleanOperatorsType();
86         if (cpsPathQuery.hasLeafConditions()) {
87             sqlStringBuilder.append(" AND (");
88             final Queue<String> booleanOperatorsQueue = (queryBooleanOperatorsType == null) ? null : new LinkedList<>(
89                     queryBooleanOperatorsType);
90             cpsPathQuery.getLeavesData().entrySet().forEach(entry -> {
91                 sqlStringBuilder.append(" attributes @> ");
92                 sqlStringBuilder.append("'" + jsonObjectMapper.asJsonString(entry) + "'");
93                 if (!(booleanOperatorsQueue == null || booleanOperatorsQueue.isEmpty())) {
94                     sqlStringBuilder.append(" " + booleanOperatorsQueue.poll() + " ");
95                 }
96             });
97             sqlStringBuilder.append(")");
98         }
99         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
100         addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
101         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
102         setQueryParameters(query, queryParameters);
103         return query;
104     }
105
106     /**
107      * Create a regular expression (string) for xpath based on the given cps path query.
108      *
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
112      */
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()));
117         } else {
118             xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
119             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
120         }
121         xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
122         if (includeDescendants) {
123             xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_POSTFIX);
124         }
125         xpathRegexBuilder.append(REGEX_END_OF_INPUT);
126         return xpathRegexBuilder.toString();
127     }
128
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("[@", "\\[@");
132     }
133
134     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
135         try {
136             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
137         } catch (final NumberFormatException e) {
138             return null;
139         }
140     }
141
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)");
148             sqlStringBuilder
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)");
155                 sqlStringBuilder
156                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
157                 queryParameters.put("textValueAsInt", textValueAsInt);
158             }
159             sqlStringBuilder.append(")");
160         }
161     }
162
163     private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
164                                                      final StringBuilder sqlStringBuilder,
165                                                      final Map<String, Object> queryParameters) {
166         if (cpsPathQuery.hasContainsFunctionCondition()) {
167             sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
168             queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
169             queryParameters.put("containsValue", cpsPathQuery.getContainsFunctionConditionValue());
170         }
171     }
172
173     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
174         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
175             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
176         }
177     }
178
179 }