Replace gson mapper with jackson mapper
[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 lombok.RequiredArgsConstructor;
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
35 @RequiredArgsConstructor
36 public class FragmentRepositoryCpsPathQueryImpl implements FragmentRepositoryCpsPathQuery {
37
38     public static final String SIMILAR_TO_ABSOLUTE_PATH_PREFIX = "%/";
39     public static final String SIMILAR_TO_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[[^/]*])?";
40
41     @PersistenceContext
42     private EntityManager entityManager;
43     private final JsonObjectMapper jsonObjectMapper;
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", jsonObjectMapper.asJsonString(
56                     cpsPathQuery.getLeavesData()));
57         }
58
59         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
60         final var query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
61         setQueryParameters(query, queryParameters);
62         return query.getResultList();
63     }
64
65     private static String getSimilarToXpathSqlRegex(final CpsPathQuery cpsPathQuery) {
66         final var xpathRegexBuilder = new StringBuilder();
67         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
68             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
69         } else {
70             xpathRegexBuilder.append(SIMILAR_TO_ABSOLUTE_PATH_PREFIX);
71             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
72         }
73         xpathRegexBuilder.append(SIMILAR_TO_OPTIONAL_LIST_INDEX_POSTFIX);
74         return xpathRegexBuilder.toString();
75     }
76
77     private static String escapeXpath(final String xpath) {
78         // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
79         return xpath.replace("[@", "\\[@");
80     }
81
82     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
83         try {
84             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
85         } catch (final NumberFormatException e) {
86             return null;
87         }
88     }
89
90     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder,
91                                                  final Map<String, Object> queryParameters) {
92         if (cpsPathQuery.hasTextFunctionCondition()) {
93             sqlStringBuilder.append(" AND (");
94             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
95             sqlStringBuilder
96                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
97             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
98             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
99             final var textValueAsInt = getTextValueAsInt(cpsPathQuery);
100             if (textValueAsInt != null) {
101                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
102                 sqlStringBuilder
103                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
104                 queryParameters.put("textValueAsInt", textValueAsInt);
105             }
106             sqlStringBuilder.append(")");
107         }
108     }
109
110     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
111         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
112             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
113         }
114     }
115
116 }