Format Java code with respect to ONAP Code Style
[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
15 package org.onap.nbi.apis.servicecatalog;
16
17 import java.io.File;
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.net.URI;
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;
27 import java.util.Map;
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;
47
48 /**
49  * @author user
50  *
51  */
52 @Service
53 public class SdcClient {
54
55     @Autowired
56     private RestTemplate restTemplate;
57
58     @Value("${sdc.host}")
59     private String sdcHost;
60
61     @Value("${sdc.header.ecompInstanceId}")
62     private String ecompInstanceId;
63
64     @Value("${sdc.header.authorization}")
65     private String sdcHeaderAuthorization;
66
67     private static final String HEADER_ECOMP_INSTANCE_ID = "x-ecomp-instanceid";
68     private static final String HEADER_AUTHORIZATION = "Authorization";
69
70     private static final Logger LOGGER = LoggerFactory.getLogger(SdcClient.class);
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)
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();
82
83         LOGGER.info("SDC GET url :  " + sdcGetUrl);
84         LOGGER.info("SDC FIND url :  " + sdcFindUrl);
85         LOGGER.info("SDC HealthCheck :  " + sdcHealthCheck);
86
87     }
88
89     public Map callGet(String id) {
90
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();
95
96     }
97
98     public List<LinkedHashMap> callFind(MultiValueMap<String, String> parametersMap) {
99
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());
106                 }
107             }
108         }
109
110         ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
111         return (List<LinkedHashMap>) response.getBody();
112
113     }
114
115     public LinkedHashMap callCheckConnectivity() {
116
117         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcHealthCheck);
118         ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
119         return (LinkedHashMap) response.getBody();
120
121     }
122
123     public File callGetWithAttachment(String toscaModelUrl) {
124         StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(toscaModelUrl);
125
126         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
127
128         File directory = new File("temptoscafile");
129         if (!directory.exists()) {
130             directory.mkdir();
131         }
132
133         String fileName = "temptoscafile/" + System.currentTimeMillis() + "tosca.csar";
134         ResponseEntity<byte[]> response = callSdcWithAttachment(callURI.build().encode().toUri());
135         File toscaFile = new File(fileName);
136         try {
137             FileOutputStream toscaFileStream = new FileOutputStream(toscaFile);
138             if (response != null) {
139                 IOUtils.write(response.getBody(), toscaFileStream);
140             }
141             toscaFileStream.close();
142         } catch (IOException e) {
143             LOGGER.error("cannot get TOSCA File for url " + toscaModelUrl, e);
144         }
145         return toscaFile;
146
147     }
148
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);
152
153         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
154
155         InputStream inputStream = (InputStream) callSdc(callURI.build().encode().toUri()).getBody();
156
157         return createTmpFile(inputStream);
158     }
159
160     private Path createTmpFile(InputStream csarInputStream) throws IOException {
161         Path csarFile = Files.createTempFile("csar", ".zip");
162         Files.copy(csarInputStream, csarFile, StandardCopyOption.REPLACE_EXISTING);
163
164         LOGGER.debug("Tosca file was saved at: {} ", csarFile.toAbsolutePath());
165
166         return csarFile;
167     }
168
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);
175     }
176
177     private ResponseEntity<Object> callSdc(URI callURI) {
178         ResponseEntity<Object> response =
179                 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
180
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     private ResponseEntity<byte[]> callSdcWithAttachment(URI callURI) {
190         try {
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());
196             }
197             return response;
198
199         } catch (BackendFunctionalException e) {
200             LOGGER.error("HTTP call SDC on {} error : {}", callURI.toString(), e);
201             return null;
202         }
203     }
204
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());
209         }
210     }
211 }