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
14 package org.onap.nbi.apis.servicecatalog;
17 import java.io.FileOutputStream;
18 import java.io.IOException;
19 import java.io.InputStream;
21 import java.nio.file.Files;
22 import java.nio.file.Path;
23 import java.nio.file.StandardCopyOption;
24 import java.util.LinkedHashMap;
25 import java.util.List;
27 import java.util.Map.Entry;
28 import javax.annotation.PostConstruct;
29 import org.apache.commons.io.IOUtils;
30 import org.onap.nbi.OnapComponentsUrlPaths;
31 import org.onap.nbi.exceptions.BackendFunctionalException;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34 import org.springframework.beans.factory.annotation.Autowired;
35 import org.springframework.beans.factory.annotation.Value;
36 import org.springframework.http.HttpEntity;
37 import org.springframework.http.HttpHeaders;
38 import org.springframework.http.HttpMethod;
39 import org.springframework.http.HttpStatus;
40 import org.springframework.http.MediaType;
41 import org.springframework.http.ResponseEntity;
42 import org.springframework.stereotype.Service;
43 import org.springframework.util.MultiValueMap;
44 import org.springframework.web.client.RestTemplate;
45 import org.springframework.web.util.UriComponentsBuilder;
52 public class SdcClient {
55 private RestTemplate restTemplate;
58 private String sdcHost;
60 @Value("${sdc.header.ecompInstanceId}")
61 private String ecompInstanceId;
63 @Value("${sdc.header.authorization}")
64 private String sdcHeaderAuthorization;
66 private static final String HEADER_ECOMP_INSTANCE_ID = "x-ecomp-instanceid";
67 private static final String HEADER_AUTHORIZATION = "Authorization";
69 private static final Logger LOGGER = LoggerFactory.getLogger(SdcClient.class);
73 private String sdcGetUrl;
74 private String sdcFindUrl;
75 private String sdcHealthCheck;
78 private void setUpAndLogSDCUrl() {
79 sdcGetUrl= new StringBuilder().append(sdcHost).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();
85 LOGGER.info("SDC GET url : "+sdcGetUrl);
86 LOGGER.info("SDC FIND url : "+ sdcFindUrl);
87 LOGGER.info("SDC HealthCheck : "+ sdcHealthCheck);
92 public Map callGet(String id) {
94 String callUrl = sdcGetUrl.replace("{id}", id);
95 UriComponentsBuilder callURLFormated = UriComponentsBuilder.fromHttpUrl(callUrl);
96 ResponseEntity<Object> response = callSdc(callURLFormated.build().encode().toUri());
97 return (LinkedHashMap) response.getBody();
101 public List<LinkedHashMap> callFind(MultiValueMap<String, String> parametersMap) {
103 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcFindUrl);
104 if (parametersMap != null) {
105 Map<String, String> stringStringMap = parametersMap.toSingleValueMap();
106 for (Entry<String, String> entry : stringStringMap.entrySet()) {
107 if (!entry.getKey().equals("fields")) {
108 callURI.queryParam(entry.getKey(), entry.getValue());
113 ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
114 return (List<LinkedHashMap>) response.getBody();
118 public LinkedHashMap callCheckConnectivity() {
120 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcHealthCheck);
121 ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
122 return (LinkedHashMap) response.getBody();
128 public File callGetWithAttachment(String toscaModelUrl) {
129 StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(toscaModelUrl);
131 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
133 File directory = new File("temptoscafile");
134 if (! directory.exists()){
138 String fileName = "temptoscafile/"+System.currentTimeMillis() + "tosca.csar";
139 ResponseEntity<byte[]> response = callSdcWithAttachment(callURI.build().encode().toUri());
140 File toscaFile = new File(fileName);
142 FileOutputStream toscaFileStream = new FileOutputStream(toscaFile);
143 if (response != null) {
144 IOUtils.write(response.getBody(), toscaFileStream);
146 toscaFileStream.close();
147 } catch (IOException e) {
148 LOGGER.error("cannot get TOSCA File for url " + toscaModelUrl, e);
154 public Path getServiceToscaModel(String uuid) throws IOException {
155 StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL)
156 .append("/").append(uuid).append(OnapComponentsUrlPaths.SDC_TOSCA_PATH);
158 UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
160 InputStream inputStream = (InputStream) callSdc(callURI.build().encode().toUri()).getBody();
162 return createTmpFile(inputStream);
165 private Path createTmpFile(InputStream csarInputStream) throws IOException {
166 Path csarFile = Files.createTempFile("csar", ".zip");
167 Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING);
169 LOGGER.debug("Tosca file was saved at: {} ", csarFile.toAbsolutePath());
174 private HttpEntity<String> buildRequestHeader() {
175 HttpHeaders httpHeaders = new HttpHeaders();
176 httpHeaders.setContentType(MediaType.APPLICATION_JSON);
177 httpHeaders.add(HEADER_ECOMP_INSTANCE_ID, ecompInstanceId);
178 httpHeaders.add(HEADER_AUTHORIZATION, sdcHeaderAuthorization);
179 return new HttpEntity<>("parameters", httpHeaders);
183 private ResponseEntity<Object> callSdc(URI callURI) {
184 ResponseEntity<Object> response =
185 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
187 if(LOGGER.isDebugEnabled()) {
188 LOGGER.debug("response body : {} ",response.getBody().toString());
190 LOGGER.info("response status : {}", response.getStatusCodeValue());
191 loggDebugIfResponseKo(callURI.toString(), response);
196 private ResponseEntity<byte[]> callSdcWithAttachment(URI callURI) {
198 ResponseEntity<byte[]> response =
199 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), byte[].class);
200 LOGGER.info("response status : " + response.getStatusCodeValue());
201 if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
202 LOGGER.warn("HTTP call SDC on {} returns {} ", callURI.toString() , response.getStatusCodeValue());
206 } catch (BackendFunctionalException e) {
207 LOGGER.error("HTTP call SDC on {} error : {}", callURI.toString() , e);
213 private void loggDebugIfResponseKo(String callURI, ResponseEntity<Object> response) {
214 if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
215 LOGGER.warn("HTTP call SDC on {} returns {} , {}", callURI , response.getStatusCodeValue() , response.getBody().toString());