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.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import javax.persistence.EntityManager;
28 import javax.persistence.PersistenceContext;
29 import javax.persistence.Query;
30 import javax.transaction.Transactional;
31 import lombok.RequiredArgsConstructor;
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 public class FragmentRepositoryCpsPathQueryImpl implements FragmentRepositoryCpsPathQuery {
39
40     public static final String REGEX_ABSOLUTE_PATH_PREFIX = ".*\\/";
41     public static final String REGEX_OPTIONAL_LIST_INDEX_POSTFIX = "(\\[@(?!.*\\[).*?])?$";
42
43     @PersistenceContext
44     private EntityManager entityManager;
45     private final JsonObjectMapper jsonObjectMapper;
46
47     @Override
48     @Transactional
49     public List<FragmentEntity> findByAnchorAndCpsPath(final int anchorId, final CpsPathQuery cpsPathQuery) {
50         final StringBuilder sqlStringBuilder = new StringBuilder("SELECT * FROM FRAGMENT WHERE anchor_id = :anchorId");
51         final Map<String, Object> queryParameters = new HashMap<>();
52         queryParameters.put("anchorId", anchorId);
53         sqlStringBuilder.append(" AND xpath ~ :xpathRegex");
54         final String xpathRegex = getXpathSqlRegex(cpsPathQuery);
55         queryParameters.put("xpathRegex", xpathRegex);
56         if (cpsPathQuery.hasLeafConditions()) {
57             sqlStringBuilder.append(" AND attributes @> :leafDataAsJson\\:\\:jsonb");
58             queryParameters.put("leafDataAsJson", jsonObjectMapper.asJsonString(
59                     cpsPathQuery.getLeavesData()));
60         }
61
62         addTextFunctionCondition(cpsPathQuery, sqlStringBuilder, queryParameters);
63         final Query query = entityManager.createNativeQuery(sqlStringBuilder.toString(), FragmentEntity.class);
64         setQueryParameters(query, queryParameters);
65         return getFragmentEntitiesAsStream(query);
66     }
67
68     private List<FragmentEntity> getFragmentEntitiesAsStream(final Query query) {
69         final List<FragmentEntity> fragmentEntities = new ArrayList<>();
70         query.getResultStream().forEach(fragmentEntity -> {
71             fragmentEntities.add((FragmentEntity) fragmentEntity);
72             entityManager.detach(fragmentEntity);
73         });
74
75         return fragmentEntities;
76     }
77
78     private static String getXpathSqlRegex(final CpsPathQuery cpsPathQuery) {
79         final StringBuilder xpathRegexBuilder = new StringBuilder();
80         if (CpsPathPrefixType.ABSOLUTE.equals(cpsPathQuery.getCpsPathPrefixType())) {
81             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getXpathPrefix()));
82         } else {
83             xpathRegexBuilder.append(REGEX_ABSOLUTE_PATH_PREFIX);
84             xpathRegexBuilder.append(escapeXpath(cpsPathQuery.getDescendantName()));
85         }
86         xpathRegexBuilder.append(REGEX_OPTIONAL_LIST_INDEX_POSTFIX);
87         return xpathRegexBuilder.toString();
88     }
89
90     private static String escapeXpath(final String xpath) {
91         // See https://jira.onap.org/browse/CPS-500 for limitations of this basic escape mechanism
92         return xpath.replace("[@", "\\[@");
93     }
94
95     private static Integer getTextValueAsInt(final CpsPathQuery cpsPathQuery) {
96         try {
97             return Integer.parseInt(cpsPathQuery.getTextFunctionConditionValue());
98         } catch (final NumberFormatException e) {
99             return null;
100         }
101     }
102
103     private static void addTextFunctionCondition(final CpsPathQuery cpsPathQuery, final StringBuilder sqlStringBuilder,
104                                                  final Map<String, Object> queryParameters) {
105         if (cpsPathQuery.hasTextFunctionCondition()) {
106             sqlStringBuilder.append(" AND (");
107             sqlStringBuilder.append("attributes @> jsonb_build_object(:textLeafName, :textValue)");
108             sqlStringBuilder
109                 .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValue))");
110             queryParameters.put("textLeafName", cpsPathQuery.getTextFunctionConditionLeafName());
111             queryParameters.put("textValue", cpsPathQuery.getTextFunctionConditionValue());
112             final Integer textValueAsInt = getTextValueAsInt(cpsPathQuery);
113             if (textValueAsInt != null) {
114                 sqlStringBuilder.append(" OR attributes @> jsonb_build_object(:textLeafName, :textValueAsInt)");
115                 sqlStringBuilder
116                     .append(" OR attributes @> jsonb_build_object(:textLeafName, json_build_array(:textValueAsInt))");
117                 queryParameters.put("textValueAsInt", textValueAsInt);
118             }
119             sqlStringBuilder.append(")");
120         }
121     }
122
123     private static void setQueryParameters(final Query query, final Map<String, Object> queryParameters) {
124         for (final Map.Entry<String, Object> queryParameter : queryParameters.entrySet()) {
125             query.setParameter(queryParameter.getKey(), queryParameter.getValue());
126         }
127     }
128
129 }