2 * Copyright (c) 2018 Orange
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
15 package org.onap.nbi.apis.servicecatalog;
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
22 import java.nio.file.Files;
23 import java.nio.file.Path;
24 import java.nio.file.StandardCopyOption;
25 import java.util.LinkedHashMap;
26 import java.util.List;
28 import java.util.Map.Entry;
29 import javax.annotation.PostConstruct;
30 import org.apache.commons.io.IOUtils;
31 import org.onap.nbi.OnapComponentsUrlPaths;
32 import org.onap.nbi.exceptions.BackendFunctionalException;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.beans.factory.annotation.Value;
37 import org.springframework.http.HttpEntity;
38 import org.springframework.http.HttpHeaders;
39 import org.springframework.http.HttpMethod;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.http.MediaType;
42 import org.springframework.http.ResponseEntity;
43 import org.springframework.stereotype.Service;
44 import org.springframework.util.MultiValueMap;
45 import org.springframework.web.client.RestTemplate;
46 import org.springframework.web.util.UriComponentsBuilder;
53 public class SdcClient {
56 private RestTemplate restTemplate;
59 private String sdcHost;
61 @Value("${sdc.header.ecompInstanceId}")
62 private String ecompInstanceId;
64 @Value("${sdc.header.authorization}")
65 private String sdcHeaderAuthorization;
67 private static final String HEADER_ECOMP_INSTANCE_ID = "x-ecomp-instanceid";
68 private static final String HEADER_AUTHORIZATION = "Authorization";
70 private static final Logger LOGGER = LoggerFactory.getLogger(SdcClient.class);
72 private String sdcGetUrl;
73 private String sdcFindUrl;
74 private String sdcHealthCheck;
77 private void setUpAndLogSDCUrl() {
78 sdcGetUrl = new StringBuilder().append(sdcHost)
79 .append(OnapComponentsUrlPaths.SDC_ROOT_URL + "/{id}" + OnapComponentsUrlPaths.SDC_GET_PATH).toString();
80 sdcFindUrl = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL).toString();
81 sdcHealthCheck = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_HEALTH_CHECK).toString();
83 LOGGER.info("SDC GET url : " + sdcGetUrl);
84 LOGGER.info("SDC FIND url : " + sdcFindUrl);
85 LOGGER.info("SDC HealthCheck : " + sdcHealthCheck);
89 public Map callGet(String id) {
91 String callUrl = sdcGetUrl.replace("{id}", id);
92 UriComponentsBuilder callURLFormated = UriComponentsBuilder.fromHttpUrl(callUrl);
93 ResponseEntity<Object> response = callSdc(callURLFormated.build().encode().toUri());
94 return (LinkedHashMap) response.getBody();
98 public List<LinkedHashMap> callFind(MultiValueMap<String, String> parametersMap) {
100 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcFindUrl);
101 if (parametersMap != null) {
102 Map<String, String> stringStringMap = parametersMap.toSingleValueMap();
103 for (Entry<String, String> entry : stringStringMap.entrySet()) {
104 if (!entry.getKey().equals("fields")) {
105 callURI.queryParam(entry.getKey(), entry.getValue());
110 ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
111 return (List<LinkedHashMap>) response.getBody();
115 public LinkedHashMap callCheckConnectivity() {
117 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcHealthCheck);
118 ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
119 return (LinkedHashMap) response.getBody();
123 public File callGetWithAttachment(String toscaModelUrl) {
124 StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(toscaModelUrl);
126 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
128 File directory = new File("temptoscafile");
129 if (!directory.exists()) {
133 String fileName = "temptoscafile/" + System.currentTimeMillis() + "tosca.csar";
134 ResponseEntity<byte[]> response = callSdcWithAttachment(callURI.build().encode().toUri());
135 File toscaFile = new File(fileName);
137 FileOutputStream toscaFileStream = new FileOutputStream(toscaFile);
138 if (response != null) {
139 IOUtils.write(response.getBody(), toscaFileStream);
141 toscaFileStream.close();
142 } catch (IOException e) {
143 LOGGER.error("cannot get TOSCA File for url " + toscaModelUrl, e);
149 public Path getServiceToscaModel(String uuid) throws IOException {
150 StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL)
151 .append("/").append(uuid).append(OnapComponentsUrlPaths.SDC_TOSCA_PATH);
153 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
155 InputStream inputStream = (InputStream) callSdc(callURI.build().encode().toUri()).getBody();
157 return createTmpFile(inputStream);
160 private Path createTmpFile(InputStream csarInputStream) throws IOException {
161 Path csarFile = Files.createTempFile("csar", ".zip");
162 Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING);
164 LOGGER.debug("Tosca file was saved at: {} ", csarFile.toAbsolutePath());
169 private HttpEntity<String> buildRequestHeader() {
170 HttpHeaders httpHeaders = new HttpHeaders();
171 httpHeaders.setContentType(MediaType.APPLICATION_JSON);
172 httpHeaders.add(HEADER_ECOMP_INSTANCE_ID, ecompInstanceId);
173 httpHeaders.add(HEADER_AUTHORIZATION, sdcHeaderAuthorization);
174 return new HttpEntity<>("parameters", httpHeaders);
177 private ResponseEntity<Object> callSdc(URI callURI) {
178 ResponseEntity<Object> response =
179 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
181 if (LOGGER.isDebugEnabled()) {
182 LOGGER.debug("response body : {} ", response.getBody().toString());
184 LOGGER.info("response status : {}", response.getStatusCodeValue());
185 loggDebugIfResponseKo(callURI.toString(), response);
189 private ResponseEntity<byte[]> callSdcWithAttachment(URI callURI) {
191 ResponseEntity<byte[]> response =
192 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), byte[].class);
193 LOGGER.info("response status : " + response.getStatusCodeValue());
194 if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
195 LOGGER.warn("HTTP call SDC on {} returns {} ", callURI.toString(), response.getStatusCodeValue());
199 } catch (BackendFunctionalException e) {
200 LOGGER.error("HTTP call SDC on {} error : {}", callURI.toString(), e);
205 private void loggDebugIfResponseKo(String callURI, ResponseEntity<Object> response) {
206 if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
207 LOGGER.warn("HTTP call SDC on {} returns {} , {}", callURI, response.getStatusCodeValue(),
208 response.getBody().toString());