Fix error handling for VSP usage check in VF
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / vendor-software-products-rest / vendor-software-products-rest-services / src / main / java / org / openecomp / sdcrests / vsp / rest / services / CatalogVspClientImpl.java
1 /*
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
8  *
9  *        http://www.apache.org/licenses/LICENSE-2.0
10  *  Unless required by applicable law or agreed to in writing, software
11  *  distributed under the License is distributed on an "AS IS" BASIS,
12  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *  See the License for the specific language governing permissions and
14  *  limitations under the License.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  *
19  *
20  */
21
22 package org.openecomp.sdcrests.vsp.rest.services;
23
24 import static javax.ws.rs.core.HttpHeaders.ACCEPT;
25 import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
26
27 import com.fasterxml.jackson.databind.ObjectMapper;
28 import java.util.Map;
29 import java.util.Optional;
30 import java.util.Properties;
31 import org.apache.http.HttpStatus;
32 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
33 import org.openecomp.sdc.common.CommonConfigurationManager;
34 import org.openecomp.sdc.common.api.Constants;
35 import org.openecomp.sdc.common.errors.CatalogRestClientException;
36 import org.openecomp.sdc.common.errors.Messages;
37 import org.openecomp.sdc.common.http.client.api.HttpRequest;
38 import org.openecomp.sdc.common.http.client.api.HttpResponse;
39 import org.openecomp.sdc.logging.api.Logger;
40 import org.openecomp.sdc.logging.api.LoggerFactory;
41 import org.openecomp.sdcrests.item.rest.services.catalog.notification.http.HttpConfiguration;
42 import org.openecomp.sdcrests.vsp.rest.CatalogVspClient;
43
44 public class CatalogVspClientImpl implements CatalogVspClient {
45
46     private static final Logger LOGGER = LoggerFactory.getLogger(CatalogVspClientImpl.class);
47     private static final String URL_GET_RESOURCE_BY_CSAR_UUID = "%s://%s:%s/sdc2/rest/v1/catalog/resources/csar/%s";
48     private static final String CONFIG_SECTION = "catalogNotificationsConfig";
49     private static final String VSP_USE_NOT_FOUND = "SVC4635";
50     public static final String NAME = "name";
51     public static final String SDC_2_REST_V_1_CATALOG_RESOURCES_CSAR_CSARUUID = "sdc2/rest/v1/catalog/resources/csar/{csaruuid}";
52
53     /**
54      * Returns the name of a VF which is using the provided VSP. It returns an empty optional in case the VSP is not used by any VF, or throws an
55      * exception if any error occurs during the process.
56      *
57      * @param vspId the id of the vsp
58      * @param user  the user to perform the action
59      */
60     @Override
61     public Optional<String> findNameOfVfUsingVsp(String vspId, String user) throws CatalogRestClientException {
62         HttpConfiguration httpConfig = getHttpConfiguration();
63         if (null == httpConfig) {
64             throw new CatalogRestClientException(
65                 ErrorMessagesFormatBuilder.getErrorWithParameters(Messages.DELETE_VSP_UNEXPECTED_ERROR_USED_BY_VF.getErrorMessage(),
66                     vspId, SDC_2_REST_V_1_CATALOG_RESOURCES_CSAR_CSARUUID));
67         }
68         final Properties headers = new Properties();
69         headers.put(Constants.USER_ID_HEADER, user);
70         headers.put(ACCEPT, APPLICATION_JSON);
71         String url = String.format(URL_GET_RESOURCE_BY_CSAR_UUID, httpConfig.getCatalogBeProtocol(),
72             httpConfig.getCatalogBeFqdn(), httpConfig.getCatalogBeHttpPort(), vspId);
73         final HttpResponse<String> httpResponse;
74         try {
75             httpResponse = HttpRequest.get(url, headers);
76         } catch (final Exception e) {
77             String formattedErrorMessage = ErrorMessagesFormatBuilder.getErrorWithParameters(
78                 Messages.DELETE_VSP_UNEXPECTED_ERROR_USED_BY_VF.getErrorMessage(),
79                 vspId, SDC_2_REST_V_1_CATALOG_RESOURCES_CSAR_CSARUUID);
80             LOGGER.error(formattedErrorMessage, e);
81             throw new CatalogRestClientException(formattedErrorMessage, e);
82         }
83         if (httpResponse.getStatusCode() != HttpStatus.SC_OK) {
84             if (httpResponse.getResponse().contains(VSP_USE_NOT_FOUND)) {
85                 LOGGER.debug("VSP usage in VF not found", httpResponse.getResponse());
86                 return Optional.empty();
87             }
88             throw new CatalogRestClientException(ErrorMessagesFormatBuilder.getErrorWithParameters(Messages.DELETE_VSP_UNEXPECTED_ERROR_USED_BY_VF
89                 .getErrorMessage(), vspId, SDC_2_REST_V_1_CATALOG_RESOURCES_CSAR_CSARUUID));
90         }
91         return Optional.of(getVspNameUsedInVf(httpResponse));
92     }
93
94     private String getVspNameUsedInVf(HttpResponse<String> httpResponse) {
95         try {
96             ObjectMapper mapper = new ObjectMapper();
97             Map<String, Object> respObject = mapper.readValue(httpResponse.getResponse(), Map.class);
98             return (String) respObject.get(NAME);
99         } catch (Exception e) {
100             throw new CatalogRestClientException("Could not parse find VSP usage response", e);
101         }
102     }
103
104     private HttpConfiguration getHttpConfiguration() throws CatalogRestClientException {
105         HttpConfiguration httpConfig;
106         try {
107             Object config = getEndpointConfiguration();
108             ObjectMapper mapper = new ObjectMapper();
109             httpConfig = mapper.convertValue(config, HttpConfiguration.class);
110         } catch (Exception e) {
111             LOGGER.error("Failed to load configuration. ", e);
112             throw new CatalogRestClientException("Failed to load configuration. ", e);
113         }
114         return httpConfig;
115     }
116
117     private static Object getEndpointConfiguration() {
118         final var commonConfigurationManager = CommonConfigurationManager.getInstance();
119         return commonConfigurationManager.getConfigValue(CONFIG_SECTION);
120     }
121 }