Merge "Add Adrian O Sulivan as committer"
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / servicecatalog / SdcClient.java
1 /**
2  * Copyright (c) 2018 Orange
3  *
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
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
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
12  * the License.
13  */
14 package org.onap.nbi.apis.servicecatalog;
15
16 import java.io.File;
17 import java.io.FileOutputStream;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.net.URI;
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;
26 import java.util.Map;
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.ResponseEntity;
41 import org.springframework.stereotype.Service;
42 import org.springframework.util.MultiValueMap;
43 import org.springframework.web.client.RestTemplate;
44 import org.springframework.web.util.UriComponentsBuilder;
45
46 /**
47  * @author user
48  *
49  */
50 @Service
51 public class SdcClient {
52
53     @Autowired
54     private RestTemplate restTemplate;
55
56     @Value("${sdc.host}")
57     private String sdcHost;
58
59     @Value("${sdc.header.ecompInstanceId}")
60     private String ecompInstanceId;
61
62     @Value("${sdc.header.authorization}")
63     private String sdcHeaderAuthorization;
64
65     private static final String HEADER_ECOMP_INSTANCE_ID = "x-ecomp-instanceid";
66     private static final String HEADER_AUTHORIZATION = "Authorization";
67
68     private static final Logger LOGGER = LoggerFactory.getLogger(SdcClient.class);
69
70
71
72     private String sdcGetUrl;
73     private String sdcFindUrl;
74     private String sdcHealthCheck;
75
76     @PostConstruct
77     private void setUpAndLogSDCUrl() {
78         sdcGetUrl= new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL+"/{id}"+OnapComponentsUrlPaths.SDC_GET_PATH).toString();
79         sdcFindUrl = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL).toString();
80         sdcHealthCheck = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_HEALTH_CHECK).toString();
81
82
83
84         LOGGER.info("SDC GET url :  "+sdcGetUrl);
85         LOGGER.info("SDC FIND url :  "+ sdcFindUrl);
86         LOGGER.info("SDC HealthCheck :  "+ sdcHealthCheck);
87
88     }
89
90
91     public Map callGet(String id) {
92
93         String callUrl = sdcGetUrl.replace("{id}", id);
94         UriComponentsBuilder callURLFormated = UriComponentsBuilder.fromHttpUrl(callUrl);
95
96         ResponseEntity<Object> response = callSdc(callURLFormated.build().encode().toUri());
97         return (LinkedHashMap) response.getBody();
98
99     }
100
101     public List<LinkedHashMap> callFind(MultiValueMap<String, String> parametersMap) {
102
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());
109                 }
110             }
111         }
112
113         ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
114         return (List<LinkedHashMap>) response.getBody();
115
116     }
117
118     public LinkedHashMap callCheckConnectivity() {
119
120         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcHealthCheck);
121         ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
122         return (LinkedHashMap) response.getBody();
123
124     }
125
126
127
128     public File callGetWithAttachment(String toscaModelUrl) {
129         StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(toscaModelUrl);
130
131         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
132
133
134         String fileName = System.currentTimeMillis() + "tosca.csar";
135         ResponseEntity<byte[]> response = callSdcWithAttachment(callURI.build().encode().toUri());
136         File toscaFile = new File(fileName);
137         try {
138             FileOutputStream toscaFileStream = new FileOutputStream(toscaFile);
139             if (response != null) {
140                 IOUtils.write(response.getBody(), toscaFileStream);
141             }
142             toscaFileStream.close();
143         } catch (IOException e) {
144             LOGGER.error("cannot get TOSCA File for url " + toscaModelUrl, e);
145         }
146         return toscaFile;
147
148     }
149     
150     public Path getServiceToscaModel(String uuid) throws IOException {
151         StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL)
152                 .append("/").append(uuid).append(OnapComponentsUrlPaths.SDC_TOSCA_PATH);
153
154         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
155
156         InputStream inputStream = (InputStream) callSdc(callURI.build().encode().toUri()).getBody();
157
158         return createTmpFile(inputStream);
159     }
160     
161     private Path createTmpFile(InputStream csarInputStream) throws IOException {
162         Path csarFile = Files.createTempFile("csar", ".zip");
163         Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING);
164
165         LOGGER.debug("Tosca file was saved at: {} ", csarFile.toAbsolutePath());
166
167         return csarFile;
168     }
169
170     private HttpEntity<String> buildRequestHeader() {
171         HttpHeaders httpHeaders = new HttpHeaders();
172         httpHeaders.add(HEADER_ECOMP_INSTANCE_ID, ecompInstanceId);
173         httpHeaders.add(HEADER_AUTHORIZATION, sdcHeaderAuthorization);
174         return new HttpEntity<>("parameters", httpHeaders);
175     }
176
177
178     private ResponseEntity<Object> callSdc(URI callURI) {
179         ResponseEntity<Object> response =
180                 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
181         if(LOGGER.isDebugEnabled()) {
182             LOGGER.debug("response body : {} ",response.getBody().toString());
183         }
184         LOGGER.info("response status : {}", response.getStatusCodeValue());
185         loggDebugIfResponseKo(callURI.toString(), response);
186         return response;
187     }
188
189
190     private ResponseEntity<byte[]> callSdcWithAttachment(URI callURI) {
191         try {
192             ResponseEntity<byte[]> response =
193                     restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), byte[].class);
194             LOGGER.info("response status : " + response.getStatusCodeValue());
195             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
196                 LOGGER.warn("HTTP call SDC on {} returns {} ", callURI.toString() , response.getStatusCodeValue());
197             }
198             return response;
199
200         } catch (BackendFunctionalException e) {
201             LOGGER.error("HTTP call SDC on {} error : {}", callURI.toString() , e);
202             return null;
203         }
204     }
205
206
207     private void loggDebugIfResponseKo(String callURI, ResponseEntity<Object> response) {
208         if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
209             LOGGER.warn("HTTP call SDC on {} returns {} , {}", callURI , response.getStatusCodeValue() , response.getBody().toString());
210         }
211     }
212 }
213
214