ab9c02e888f9dfa1d2ec8e68326b2b64883e04af
[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.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;
40
41 @RequiredArgsConstructor
42 @Slf4j
43 @Component
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 = "$";
49
50     @PersistenceContext
51     private EntityManager entityManager;
52
53     private final JsonObjectMapper jsonObjectMapper;
54
55     /**
56      * Create a sql query to retrieve by anchor(id) and cps path.
57      *
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
61      */
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);
68     }
69
70     /**
71      * Create a sql query to retrieve by cps path.
72      *
73      * @param cpsPathQuery the cps path query to be transformed into a sql query
74      * @return a executable query object
75      */
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);
80     }
81
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() + " ");
96                 }
97             });
98             sqlStringBuilder.append(")");
99         }
100         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
101         addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
102         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
103         setQueryParameters(query, queryParameters);
104         return query;
105     }
106
107     /**
108      * Create a regular expression (string) for xpath based on the given cps path query.
109      *
110      * @param cpsPathQuery  the cps path query to determine the required regular expression
111      * @param includeDescendants include descendants yes or no
112      * @return a string representing the required regular expression
113      */
114     public static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery, final boolean includeDescendants) {
115         final StringBuilder xpathRegexBuilder = new StringBuilder();
116         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
117             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
118         } else {
119             xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
120             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
121         }
122         xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
123         if (includeDescendants) {
124             xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_POSTFIX);
125         }
126         xpathRegexBuilder.append(REGEX_END_OF_INPUT);
127         return xpathRegexBuilder.toString();
128     }
129
130     private static String escapeXpath(final String xpath) {
131         // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
132         return xpath.replace("[@", "\\[@");
133     }
134
135     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
136         try {
137             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
138         } catch (final NumberFormatException e) {
139             return null;
140         }
141     }
142
143     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
144                                                  final StringBuilder sqlStringBuilder,
145                                                  final Map<String, Object> queryParameters) {
146         if (cpsPathQuery.hasTextFunctionCondition()) {
147             sqlStringBuilder.append(" AND (");
148             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
149             sqlStringBuilder
150                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
151             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
152             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
153             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
154             if (textValueAsInt != null) {
155                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
156                 sqlStringBuilder
157                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
158                 queryParameters.put("textValueAsInt", textValueAsInt);
159             }
160             sqlStringBuilder.append(")");
161         }
162     }
163
164     private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
165                                                      final StringBuilder sqlStringBuilder,
166                                                      final Map<String, Object> queryParameters) {
167         if (cpsPathQuery.hasContainsFunctionCondition()) {
168             sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
169             queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
170             queryParameters.put("containsValue", cpsPathQuery.getContainsFunctionConditionValue());
171         }
172     }
173
174     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
175         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
176             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
177         }
178     }
179
180 }