Merge "[NCMP] Consume & Forward to client topic"
[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  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  *  SPDX-License-Identifier: Apache-2.0
18  *  ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.spi.repository;
22
23 import java.util.HashMap;
24 import java.util.Map;
25 import javax.persistence.EntityManager;
26 import javax.persistence.PersistenceContext;
27 import javax.persistence.Query;
28 import lombok.RequiredArgsConstructor;
29 import lombok.extern.slf4j.Slf4j;
30 import org.onap.cps.cpspath.parser.CpsPathPrefixType;
31 import org.onap.cps.cpspath.parser.CpsPathQuery;
32 import org.onap.cps.spi.entities.FragmentEntity;
33 import org.onap.cps.utils.JsonObjectMapper;
34 import org.springframework.stereotype.Component;
35
36 @RequiredArgsConstructor
37 @Slf4j
38 @Component
39 public class FragmentQueryBuilder {
40     private static final String REGEX_ABSOLUTE_PATH_PREFIX = ".*\\/";
41     private static final String REGEX_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?";
42     private static final String REGEX_DESCENDANT_PATH_POSTFIX = "(\\/.*)?";
43     private static final String REGEX_END_OF_INPUT = "$";
44
45     @PersistenceContext
46     private EntityManager entityManager;
47
48     private final JsonObjectMapper jsonObjectMapper;
49
50     /**
51      * Create a sql query to retrieve by anchor(id) and cps path.
52      *
53      * @param anchorId the id of the anchor
54      * @param cpsPathQuery the cps path query to be transformed into a sql query
55      * @return a executable query object
56      */
57     public Query getQueryForAnchorAndCpsPath(final int anchorId, final CpsPathQuery cpsPathQuery) {
58         final StringBuilder sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE anchor_id = :anchorId");
59         final Map<String, Object> queryParameters = new HashMap<>();
60         queryParameters.put("anchorId", anchorId);
61         sqlStringBuilder.append(" AND xpath ~ :xpathRegex");
62         final String xpathRegex = getXpathSqlRegex(cpsPathQuery, false);
63         queryParameters.put("xpathRegex", xpathRegex);
64         if (cpsPathQuery.hasLeafConditions()) {
65             sqlStringBuilder.append(" AND attributes @> :leafDataAsJson\\:\\:jsonb");
66             queryParameters.put("leafDataAsJson", jsonObjectMapper.asJsonString(
67                 cpsPathQuery.getLeavesData()));
68         }
69
70         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
71         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
72         setQueryParameters(query, queryParameters);
73         return query;
74     }
75
76     /**
77      * Create a regular expression (string) for xpath based on the given cps path query.
78      *
79      * @param cpsPathQuery  the cps path query to determine the required regular expression
80      * @param includeDescendants include descendants yes or no
81      * @return a string representing the required regular expression
82      */
83     public static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery, final boolean includeDescendants) {
84         final StringBuilder xpathRegexBuilder = new StringBuilder();
85         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
86             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
87         } else {
88             xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
89             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
90         }
91         xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
92         if (includeDescendants) {
93             xpathRegexBuilder.append(REGEX_DESCENDANT_PATH_POSTFIX);
94         }
95         xpathRegexBuilder.append(REGEX_END_OF_INPUT);
96         return xpathRegexBuilder.toString();
97     }
98
99     private static String escapeXpath(final String xpath) {
100         // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
101         return xpath.replace("[@", "\\[@");
102     }
103
104     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
105         try {
106             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
107         } catch (final NumberFormatException e) {
108             return null;
109         }
110     }
111
112     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery,
113                                                  final StringBuilder sqlStringBuilder,
114                                                  final Map<String, Object> queryParameters) {
115         if (cpsPathQuery.hasTextFunctionCondition()) {
116             sqlStringBuilder.append(" AND (");
117             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
118             sqlStringBuilder
119                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
120             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
121             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
122             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
123             if (textValueAsInt != null) {
124                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
125                 sqlStringBuilder
126                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
127                 queryParameters.put("textValueAsInt", textValueAsInt);
128             }
129             sqlStringBuilder.append(")");
130         }
131     }
132
133     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
134         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
135             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
136         }
137     }
138
139 }