Handle special characters in CpsPath queries (CPS-1760 #2)
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / repository / FragmentQueryBuilder.java
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2022-2023 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.Map;
27 import java.util.Queue;
28 import javax.persistence.EntityManager;
29 import javax.persistence.PersistenceContext;
30 import javax.persistence.Query;
31 import lombok.RequiredArgsConstructor;
32 import lombok.extern.slf4j.Slf4j;
33 import org.onap.cps.cpspath.parser.CpsPathPrefixType;
34 import org.onap.cps.cpspath.parser.CpsPathQuery;
35 import org.onap.cps.spi.entities.AnchorEntity;
36 import org.onap.cps.spi.entities.DataspaceEntity;
37 import org.onap.cps.spi.entities.FragmentEntity;
38 import org.onap.cps.spi.exceptions.CpsPathException;
39 import org.onap.cps.spi.utils.EscapeUtils;
40 import org.onap.cps.utils.JsonObjectMapper;
41 import org.springframework.stereotype.Component;
42
43 @RequiredArgsConstructor
44 @Slf4j
45 @Component
46 public class FragmentQueryBuilder {
47     private static final AnchorEntity ACROSS_ALL_ANCHORS = null;
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 anchorEntity 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 AnchorEntity anchorEntity, final CpsPathQuery cpsPathQuery) {
62         return getQueryForDataspaceOrAnchorAndCpsPath(anchorEntity.getDataspace(), anchorEntity, cpsPathQuery);
63     }
64
65     /**
66      * Create a sql query to retrieve by cps path.
67      *
68      * @param dataspaceEntity the dataspace
69      * @param cpsPathQuery the cps path query to be transformed into a sql query
70      * @return a executable query object
71      */
72     public Query getQueryForDataspaceAndCpsPath(final DataspaceEntity dataspaceEntity,
73                                                 final CpsPathQuery cpsPathQuery) {
74         return getQueryForDataspaceOrAnchorAndCpsPath(dataspaceEntity, ACROSS_ALL_ANCHORS, cpsPathQuery);
75     }
76
77     private Query getQueryForDataspaceOrAnchorAndCpsPath(final DataspaceEntity dataspaceEntity,
78                                                          final AnchorEntity anchorEntity,
79                                                          final CpsPathQuery cpsPathQuery) {
80         final StringBuilder sqlStringBuilder = new StringBuilder();
81         final Map<String, Object> queryParameters = new HashMap<>();
82
83         if (anchorEntity == ACROSS_ALL_ANCHORS) {
84             sqlStringBuilder.append("SELECT fragment.* FROM fragment JOIN anchor ON anchor.id = fragment.anchor_id"
85                 + " WHERE dataspace_id = :dataspaceId");
86             queryParameters.put("dataspaceId", dataspaceEntity.getId());
87         } else {
88             sqlStringBuilder.append("SELECT * FROM fragment WHERE anchor_id = :anchorId");
89             queryParameters.put("anchorId", anchorEntity.getId());
90         }
91         addXpathSearch(cpsPathQuery, sqlStringBuilder, queryParameters);
92         addLeafConditions(cpsPathQuery, sqlStringBuilder);
93         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
94         addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
95
96         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
97         setQueryParameters(query, queryParameters);
98         return query;
99     }
100
101     private static void addXpathSearch(final CpsPathQuery cpsPathQuery,
102                                        final StringBuilder sqlStringBuilder,
103                                        final Map<String, Object> queryParameters) {
104         sqlStringBuilder.append(" AND (xpath LIKE :escapedXpath OR "
105                 + "(xpath LIKE :escapedXpath||'[@%]' AND xpath NOT LIKE :escapedXpath||'[@%]/%[@%]'))");
106         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
107             queryParameters.put("escapedXpath", EscapeUtils.escapeForSqlLike(cpsPathQuery.getXpathPrefix()));
108         } else {
109             queryParameters.put("escapedXpath", "%/" + EscapeUtils.escapeForSqlLike(cpsPathQuery.getDescendantName()));
110         }
111     }
112
113     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
114         try {
115             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
116         } catch (final NumberFormatException e) {
117             return null;
118         }
119     }
120
121     private void addLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
122         if (cpsPathQuery.hasLeafConditions()) {
123             queryLeafConditions(cpsPathQuery, sqlStringBuilder);
124         }
125     }
126
127     private void queryLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
128         sqlStringBuilder.append(" AND (");
129         final Queue<String> booleanOperatorsQueue = new LinkedList<>(cpsPathQuery.getBooleanOperators());
130         final Queue<String> comparativeOperatorQueue = new LinkedList<>(cpsPathQuery.getComparativeOperators());
131         cpsPathQuery.getLeavesData().entrySet().forEach(entry -> {
132             final String nextComparativeOperator = comparativeOperatorQueue.poll();
133             if (entry.getValue() instanceof Integer) {
134                 sqlStringBuilder.append("(attributes ->> ");
135                 sqlStringBuilder.append("'").append(entry.getKey()).append("')\\:\\:int");
136                 sqlStringBuilder.append(" ").append(nextComparativeOperator).append(" ");
137                 sqlStringBuilder.append("'").append(jsonObjectMapper.asJsonString(entry.getValue())).append("'");
138             } else {
139                 if ("=".equals(nextComparativeOperator)) {
140                     sqlStringBuilder.append(" attributes @> ");
141                     sqlStringBuilder.append("'");
142                     sqlStringBuilder.append(jsonObjectMapper.asJsonString(entry));
143                     sqlStringBuilder.append("'");
144                 } else {
145                     throw new CpsPathException(" can use only " + nextComparativeOperator + " with integer ");
146                 }
147             }
148             if (!booleanOperatorsQueue.isEmpty()) {
149                 sqlStringBuilder.append(" ");
150                 sqlStringBuilder.append(booleanOperatorsQueue.poll());
151                 sqlStringBuilder.append(" ");
152             }
153         });
154         sqlStringBuilder.append(")");
155     }
156
157     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
158                                                  final StringBuilder sqlStringBuilder,
159                                                  final Map<String, Object> queryParameters) {
160         if (cpsPathQuery.hasTextFunctionCondition()) {
161             sqlStringBuilder.append(" AND (");
162             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
163             sqlStringBuilder
164                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
165             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
166             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
167             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
168             if (textValueAsInt != null) {
169                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
170                 sqlStringBuilder
171                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
172                 queryParameters.put("textValueAsInt", textValueAsInt);
173             }
174             sqlStringBuilder.append(")");
175         }
176     }
177
178     private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
179                                                      final StringBuilder sqlStringBuilder,
180                                                      final Map<String, Object> queryParameters) {
181         if (cpsPathQuery.hasContainsFunctionCondition()) {
182             sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
183             queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
184             queryParameters.put("containsValue",
185                     EscapeUtils.escapeForSqlLike(cpsPathQuery.getContainsFunctionConditionValue()));
186         }
187     }
188
189     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
190         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
191             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
192         }
193     }
194
195 }