fddedcad273bf7dc38cb0ca0d17347d3f9cb907a
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / repository / FragmentRepositoryCpsPathQueryImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 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 com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import javax.persistence.EntityManager;
29 import javax.persistence.PersistenceContext;
30 import javax.persistence.Query;
31 import org.onap.cps.cpspath.parser.CpsPathPrefixType;
32 import org.onap.cps.cpspath.parser.CpsPathQuery;
33 import org.onap.cps.spi.entities.FragmentEntity;
34
35 public class FragmentRepositoryCpsPathQueryImpl implements FragmentRepositoryCpsPathQuery {
36
37     public static final String SIMILAR_TO_ABSOLUTE_PATH_PREFIX = "%/";
38     public static final String SIMILAR_TO_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[[^/]*])?";
39
40     @PersistenceContext
41     private EntityManager entityManager;
42
43     private static final Gson GSON = new GsonBuilder().create();
44
45     @Override
46     public List<FragmentEntity> findByAnchorAndCpsPath(final int anchorId, final CpsPathQuery cpsPathQuery) {
47         final var sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE anchor_id = :anchorId");
48         final Map<String, Object> queryParameters = new HashMap<>();
49         queryParameters.put("anchorId", anchorId);
50         sqlStringBuilder.append(" AND xpath SIMILAR TO :xpathRegex");
51         final String xpathRegex = getSimilarToXpathSqlRegex(cpsPathQuery);
52         queryParameters.put("xpathRegex", xpathRegex);
53         if (cpsPathQuery.hasLeafConditions()) {
54             sqlStringBuilder.append(" AND attributes @> :leafDataAsJson\\:\\:jsonb");
55             queryParameters.put("leafDataAsJson", GSON.toJson(cpsPathQuery.getLeavesData()));
56         }
57
58         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
59         final var query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
60         setQueryParameters(query, queryParameters);
61         return query.getResultList();
62     }
63
64     private static String getSimilarToXpathSqlRegex(final CpsPathQuery cpsPathQuery) {
65         final var xpathRegexBuilder = new StringBuilder();
66         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
67             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
68         } else {
69             xpathRegexBuilder.append(SIMILAR_TO_ABSOLUTE_PATH_PREFIX);
70             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
71         }
72         xpathRegexBuilder.append(SIMILAR_TO_OPTIONAL_LIST_INDEX_POSTFIX);
73         return xpathRegexBuilder.toString();
74     }
75
76     private static String escapeXpath(final String xpath) {
77         // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
78         return xpath.replace("[@", "\\[@");
79     }
80
81     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
82         try {
83             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
84         } catch (final NumberFormatException e) {
85             return null;
86         }
87     }
88
89     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder,
90                                                  final Map<String, Object> queryParameters) {
91         if (cpsPathQuery.hasTextFunctionCondition()) {
92             sqlStringBuilder.append(" AND (");
93             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
94             sqlStringBuilder
95                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
96             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
97             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
98             final var textValueAsInt = getTextValueAsInt(cpsPathQuery);
99             if (textValueAsInt != null) {
100                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
101                 sqlStringBuilder
102                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
103                 queryParameters.put("textValueAsInt", textValueAsInt);
104             }
105             sqlStringBuilder.append(")");
106         }
107     }
108
109     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
110         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
111             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
112         }
113     }
114
115 }