Merge "Get Node API fix for attribute values with '/'"
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / repository / FragmentRepositoryCpsPathQueryImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-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.List;
25 import java.util.Map;
26 import javax.persistence.EntityManager;
27 import javax.persistence.PersistenceContext;
28 import javax.persistence.Query;
29 import javax.transaction.Transactional;
30 import lombok.RequiredArgsConstructor;
31 import lombok.extern.slf4j.Slf4j;
32 import org.onap.cps.cpspath.parser.CpsPathPrefixType;
33 import org.onap.cps.cpspath.parser.CpsPathQuery;
34 import org.onap.cps.spi.entities.FragmentEntity;
35 import org.onap.cps.utils.JsonObjectMapper;
36
37 @RequiredArgsConstructor
38 @Slf4j
39 public class FragmentRepositoryCpsPathQueryImpl implements FragmentRepositoryCpsPathQuery {
40
41     public static final String REGEX_ABSOLUTE_PATH_PREFIX = ".*\\/";
42     public static final String REGEX_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?$";
43
44     @PersistenceContext
45     private EntityManager entityManager;
46     private final JsonObjectMapper jsonObjectMapper;
47
48     @Override
49     @Transactional
50     public List<FragmentEntity> findByAnchorAndCpsPath(final int anchorId, final CpsPathQuery cpsPathQuery) {
51         final StringBuilder sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE anchor_id = :anchorId");
52         final Map<String, Object> queryParameters = new HashMap<>();
53         queryParameters.put("anchorId", anchorId);
54         sqlStringBuilder.append(" AND xpath ~ :xpathRegex");
55         final String xpathRegex = getXpathSqlRegex(cpsPathQuery);
56         queryParameters.put("xpathRegex", xpathRegex);
57         if (cpsPathQuery.hasLeafConditions()) {
58             sqlStringBuilder.append(" AND attributes @> :leafDataAsJson\\:\\:jsonb");
59             queryParameters.put("leafDataAsJson", jsonObjectMapper.asJsonString(
60                     cpsPathQuery.getLeavesData()));
61         }
62
63         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
64         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
65         setQueryParameters(query, queryParameters);
66         final List<FragmentEntity> fragmentEntities = query.getResultList();
67         log.debug("Fetched {} fragment entities by anchor and cps path.", fragmentEntities.size());
68         return fragmentEntities;
69     }
70
71     private static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery) {
72         final StringBuilder xpathRegexBuilder = new StringBuilder();
73         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
74             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
75         } else {
76             xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
77             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
78         }
79         xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
80         return xpathRegexBuilder.toString();
81     }
82
83     private static String escapeXpath(final String xpath) {
84         // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
85         return xpath.replace("[@", "\\[@");
86     }
87
88     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
89         try {
90             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
91         } catch (final NumberFormatException e) {
92             return null;
93         }
94     }
95
96     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder,
97                                                  final Map<String, Object> queryParameters) {
98         if (cpsPathQuery.hasTextFunctionCondition()) {
99             sqlStringBuilder.append(" AND (");
100             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
101             sqlStringBuilder
102                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
103             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
104             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
105             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
106             if (textValueAsInt != null) {
107                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
108                 sqlStringBuilder
109                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
110                 queryParameters.put("textValueAsInt", textValueAsInt);
111             }
112             sqlStringBuilder.append(")");
113         }
114     }
115
116     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
117         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
118             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
119         }
120     }
121
122 }