2 * ============LICENSE_START=======================================================
3 * Copyright (C) 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
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.cps.spi.repository;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.List;
29 import java.util.UUID;
30 import java.util.stream.Collectors;
31 import javax.persistence.EntityManager;
32 import javax.persistence.PersistenceContext;
33 import lombok.AllArgsConstructor;
34 import lombok.SneakyThrows;
35 import lombok.extern.slf4j.Slf4j;
36 import org.onap.cps.spi.CpsDataPersistenceService;
37 import org.onap.cps.spi.FetchDescendantsOption;
38 import org.onap.cps.spi.model.CmHandleQueryParameters;
39 import org.onap.cps.spi.model.DataNode;
40 import org.onap.cps.spi.model.ModuleReference;
41 import org.springframework.transaction.annotation.Transactional;
46 public class ModuleReferenceRepositoryImpl implements ModuleReferenceQuery {
49 private EntityManager entityManager;
51 private final CpsDataPersistenceService cpsDataPersistenceService;
55 public Collection<ModuleReference> identifyNewModuleReferences(
56 final Collection<ModuleReference> moduleReferencesToCheck) {
58 if (moduleReferencesToCheck == null || moduleReferencesToCheck.isEmpty()) {
59 return Collections.emptyList();
62 final String tempTableName = "moduleReferencesToCheckTemp"
63 + UUID.randomUUID().toString().replace("-", "");
65 createTemporaryTable(tempTableName);
66 insertDataIntoTable(tempTableName, moduleReferencesToCheck);
68 return identifyNewModuleReferencesForCmHandle(tempTableName);
72 * Query and return cm handles that match the given query parameters.
74 * @param cmHandleQueryParameters the cm handle query parameters
75 * @return collection of cm handle ids
78 public Set<String> queryCmHandles(final CmHandleQueryParameters cmHandleQueryParameters) {
80 if (cmHandleQueryParameters.getPublicProperties().entrySet().isEmpty()) {
81 return getAllCmHandles();
84 final Collection<DataNode> amalgamatedQueryResult = new ArrayList<>();
85 int queryConditionCounter = 0;
86 for (final Map.Entry<String, String> entry : cmHandleQueryParameters.getPublicProperties().entrySet()) {
87 final StringBuilder cmHandlePath = new StringBuilder();
88 cmHandlePath.append("//public-properties[@name='").append(entry.getKey()).append("' ");
89 cmHandlePath.append("and @value='").append(entry.getValue()).append("']");
90 cmHandlePath.append("/ancestor::cm-handles");
92 final Collection<DataNode> singleConditionQueryResult =
93 cpsDataPersistenceService.queryDataNodes("NCMP-Admin",
94 "ncmp-dmi-registry", String.valueOf(cmHandlePath), FetchDescendantsOption.OMIT_DESCENDANTS);
95 if (++queryConditionCounter == 1) {
96 amalgamatedQueryResult.addAll(singleConditionQueryResult);
98 amalgamatedQueryResult.retainAll(singleConditionQueryResult);
101 if (amalgamatedQueryResult.isEmpty()) {
106 return extractCmHandleIds(amalgamatedQueryResult);
109 private Set<String> getAllCmHandles() {
110 final Collection<DataNode> cmHandles = cpsDataPersistenceService.queryDataNodes("NCMP-Admin",
111 "ncmp-dmi-registry", "//public-properties/ancestor::cm-handles",
112 FetchDescendantsOption.OMIT_DESCENDANTS);
113 return extractCmHandleIds(cmHandles);
116 private Set<String> extractCmHandleIds(final Collection<DataNode> cmHandles) {
117 return cmHandles.stream().map(cmHandle -> cmHandle.getLeaves().get("id").toString())
118 .collect(Collectors.toSet());
121 private void createTemporaryTable(final String tempTableName) {
122 final StringBuilder sqlStringBuilder = new StringBuilder("CREATE TEMPORARY TABLE " + tempTableName + "(");
123 sqlStringBuilder.append(" id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,");
124 sqlStringBuilder.append(" module_name varchar NOT NULL,");
125 sqlStringBuilder.append(" revision varchar NOT NULL");
126 sqlStringBuilder.append(");");
128 entityManager.createNativeQuery(sqlStringBuilder.toString()).executeUpdate();
131 private void insertDataIntoTable(final String tempTableName, final Collection<ModuleReference> moduleReferences) {
132 final StringBuilder sqlStringBuilder = new StringBuilder("INSERT INTO " + tempTableName);
133 sqlStringBuilder.append(" (module_name, revision) ");
134 sqlStringBuilder.append(" VALUES ");
136 for (final ModuleReference moduleReference : moduleReferences) {
137 sqlStringBuilder.append("('");
138 sqlStringBuilder.append(moduleReference.getModuleName());
139 sqlStringBuilder.append("', '");
140 sqlStringBuilder.append(moduleReference.getRevision());
141 sqlStringBuilder.append("'),");
144 // replace last ',' with ';'
145 sqlStringBuilder.replace(sqlStringBuilder.length() - 1, sqlStringBuilder.length(), ";");
147 entityManager.createNativeQuery(sqlStringBuilder.toString()).executeUpdate();
150 private Collection<ModuleReference> identifyNewModuleReferencesForCmHandle(final String tempTableName) {
151 final String sql = String.format(
152 "SELECT %1$s.module_name, %1$s.revision"
153 + " FROM %1$s LEFT JOIN yang_resource"
154 + " ON yang_resource.module_name=%1$s.module_name"
155 + " AND yang_resource.revision=%1$s.revision"
156 + " WHERE yang_resource.module_name IS NULL;", tempTableName);
158 final List<Object[]> resultsAsObjects =
159 (List<Object[]>) entityManager.createNativeQuery(sql).getResultList();
161 final List<ModuleReference> resultsAsModuleReferences = new ArrayList<>(resultsAsObjects.size());
162 for (final Object[] row : resultsAsObjects) {
163 resultsAsModuleReferences.add(new ModuleReference((String) row[0], (String) row[1]));
166 return resultsAsModuleReferences;