Merge "Subscription Creation: NCMP to Client CloudEvent transformation"
[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.springframework.stereotype.Component;
41
42 @RequiredArgsConstructor
43 @Slf4j
44 @Component
45 public class FragmentQueryBuilder {
46     private static final AnchorEntity ACROSS_ALL_ANCHORS = null;
47
48     @PersistenceContext
49     private EntityManager entityManager;
50
51     /**
52      * Create a sql query to retrieve by anchor(id) and cps path.
53      *
54      * @param anchorEntity the anchor
55      * @param cpsPathQuery the cps path query to be transformed into a sql query
56      * @return a executable query object
57      */
58     public Query getQueryForAnchorAndCpsPath(final AnchorEntity anchorEntity, final CpsPathQuery cpsPathQuery) {
59         return getQueryForDataspaceOrAnchorAndCpsPath(anchorEntity.getDataspace(), anchorEntity, cpsPathQuery);
60     }
61
62     /**
63      * Create a sql query to retrieve by cps path.
64      *
65      * @param dataspaceEntity the dataspace
66      * @param cpsPathQuery the cps path query to be transformed into a sql query
67      * @return a executable query object
68      */
69     public Query getQueryForDataspaceAndCpsPath(final DataspaceEntity dataspaceEntity,
70                                                 final CpsPathQuery cpsPathQuery) {
71         return getQueryForDataspaceOrAnchorAndCpsPath(dataspaceEntity, ACROSS_ALL_ANCHORS, cpsPathQuery);
72     }
73
74     private Query getQueryForDataspaceOrAnchorAndCpsPath(final DataspaceEntity dataspaceEntity,
75                                                          final AnchorEntity anchorEntity,
76                                                          final CpsPathQuery cpsPathQuery) {
77         final StringBuilder sqlStringBuilder = new StringBuilder();
78         final Map<String, Object> queryParameters = new HashMap<>();
79
80         if (anchorEntity == ACROSS_ALL_ANCHORS) {
81             sqlStringBuilder.append("SELECT fragment.* FROM fragment JOIN anchor ON anchor.id = fragment.anchor_id"
82                 + " WHERE dataspace_id = :dataspaceId");
83             queryParameters.put("dataspaceId", dataspaceEntity.getId());
84         } else {
85             sqlStringBuilder.append("SELECT * FROM fragment WHERE anchor_id = :anchorId");
86             queryParameters.put("anchorId", anchorEntity.getId());
87         }
88         addXpathSearch(cpsPathQuery, sqlStringBuilder, queryParameters);
89         addLeafConditions(cpsPathQuery, sqlStringBuilder);
90         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
91         addContainsFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
92
93         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
94         setQueryParameters(query, queryParameters);
95         return query;
96     }
97
98     private static void addXpathSearch(final CpsPathQuery cpsPathQuery,
99                                        final StringBuilder sqlStringBuilder,
100                                        final Map<String, Object> queryParameters) {
101         sqlStringBuilder.append(" AND (xpath LIKE :escapedXpath OR "
102                 + "(xpath LIKE :escapedXpath||'[@%]' AND xpath NOT LIKE :escapedXpath||'[@%]/%[@%]'))");
103         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
104             queryParameters.put("escapedXpath", EscapeUtils.escapeForSqlLike(cpsPathQuery.getXpathPrefix()));
105         } else {
106             queryParameters.put("escapedXpath", "%/" + EscapeUtils.escapeForSqlLike(cpsPathQuery.getDescendantName()));
107         }
108     }
109
110     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
111         try {
112             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
113         } catch (final NumberFormatException e) {
114             return null;
115         }
116     }
117
118     private void addLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
119         if (cpsPathQuery.hasLeafConditions()) {
120             queryLeafConditions(cpsPathQuery, sqlStringBuilder);
121         }
122     }
123
124     private void queryLeafConditions(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder) {
125         sqlStringBuilder.append(" AND (");
126         final Queue<String> booleanOperatorsQueue = new LinkedList<>(cpsPathQuery.getBooleanOperators());
127         final Queue<String> comparativeOperatorQueue = new LinkedList<>(cpsPathQuery.getComparativeOperators());
128         cpsPathQuery.getLeavesData().forEach(leaf -> {
129             final String nextComparativeOperator = comparativeOperatorQueue.poll();
130             if (leaf.getValue() instanceof Integer) {
131                 sqlStringBuilder.append("(attributes ->> '").append(leaf.getName()).append("')\\:\\:int");
132                 sqlStringBuilder.append(nextComparativeOperator);
133                 sqlStringBuilder.append(leaf.getValue());
134             } else {
135                 if ("=".equals(nextComparativeOperator)) {
136                     final String leafValueAsText = leaf.getValue().toString();
137                     sqlStringBuilder.append("attributes ->> '").append(leaf.getName()).append("'");
138                     sqlStringBuilder.append(" = '");
139                     sqlStringBuilder.append(EscapeUtils.escapeForSqlStringLiteral(leafValueAsText));
140                     sqlStringBuilder.append("'");
141                 } else {
142                     throw new CpsPathException(" can use only " + nextComparativeOperator + " with integer ");
143                 }
144             }
145             if (!booleanOperatorsQueue.isEmpty()) {
146                 sqlStringBuilder.append(" ");
147                 sqlStringBuilder.append(booleanOperatorsQueue.poll());
148                 sqlStringBuilder.append(" ");
149             }
150         });
151         sqlStringBuilder.append(")");
152     }
153
154     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
155                                                  final StringBuilder sqlStringBuilder,
156                                                  final Map<String, Object> queryParameters) {
157         if (cpsPathQuery.hasTextFunctionCondition()) {
158             sqlStringBuilder.append(" AND (");
159             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
160             sqlStringBuilder
161                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
162             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
163             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
164             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
165             if (textValueAsInt != null) {
166                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
167                 sqlStringBuilder
168                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
169                 queryParameters.put("textValueAsInt", textValueAsInt);
170             }
171             sqlStringBuilder.append(")");
172         }
173     }
174
175     private static void addContainsFunctionCondition(final CpsPathQuery cpsPathQuery,
176                                                      final StringBuilder sqlStringBuilder,
177                                                      final Map<String, Object> queryParameters) {
178         if (cpsPathQuery.hasContainsFunctionCondition()) {
179             sqlStringBuilder.append(" AND attributes ->> :containsLeafName LIKE CONCAT('%',:containsValue,'%') ");
180             queryParameters.put("containsLeafName", cpsPathQuery.getContainsFunctionConditionLeafName());
181             queryParameters.put("containsValue",
182                     EscapeUtils.escapeForSqlLike(cpsPathQuery.getContainsFunctionConditionValue()));
183         }
184     }
185
186     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
187         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
188             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
189         }
190     }
191
192 }