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