a4b8febf2ad680f6086f2f3969aa8a954218399a
[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.net.URI;
20 import java.util.LinkedHashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import org.apache.commons.io.IOUtils;
25 import org.onap.nbi.OnapComponentsUrlPaths;
26 import org.onap.nbi.exceptions.BackendFunctionalException;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29 import org.springframework.beans.factory.annotation.Autowired;
30 import org.springframework.beans.factory.annotation.Value;
31 import org.springframework.http.HttpEntity;
32 import org.springframework.http.HttpHeaders;
33 import org.springframework.http.HttpMethod;
34 import org.springframework.http.HttpStatus;
35 import org.springframework.http.ResponseEntity;
36 import org.springframework.stereotype.Service;
37 import org.springframework.util.MultiValueMap;
38 import org.springframework.web.client.RestTemplate;
39 import org.springframework.web.util.UriComponentsBuilder;
40
41 /**
42  * @author user
43  *
44  */
45 @Service
46 public class SdcClient {
47
48     @Autowired
49     private RestTemplate restTemplate;
50
51     @Value("${sdc.host}")
52     private String sdcHost;
53
54     @Value("${sdc.header.ecompInstanceId}")
55     private String ecompInstanceId;
56
57     @Value("${sdc.header.authorization}")
58     private String sdcHeaderAuthorization;
59
60     private static final String HEADER_ECOMP_INSTANCE_ID = "x-ecomp-instanceid";
61     private static final String HEADER_AUTHORIZATION = "Authorization";
62
63     private static final Logger LOGGER = LoggerFactory.getLogger(SdcClient.class);
64
65
66     public Map callGet(String id) {
67         StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(OnapComponentsUrlPaths.SDC_ROOT_URL)
68                 .append("/").append(id).append(OnapComponentsUrlPaths.SDC_GET_PATH);
69
70         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
71
72         ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
73         return (LinkedHashMap) response.getBody();
74
75     }
76
77     public List<LinkedHashMap> callFind(MultiValueMap<String, String> parametersMap) {
78
79         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(sdcHost + OnapComponentsUrlPaths.SDC_ROOT_URL);
80         if (parametersMap != null) {
81             Map<String, String> stringStringMap = parametersMap.toSingleValueMap();
82             for (Entry<String, String> entry : stringStringMap.entrySet()) {
83                 if (!entry.getKey().equals("fields")) {
84                     callURI.queryParam(entry.getKey(), entry.getValue());
85                 }
86             }
87         }
88
89         ResponseEntity<Object> response = callSdc(callURI.build().encode().toUri());
90         return (List<LinkedHashMap>) response.getBody();
91
92     }
93
94
95     public File callGetWithAttachment(String toscaModelUrl) {
96         StringBuilder urlBuilder = new StringBuilder().append(sdcHost).append(toscaModelUrl);
97
98         UriComponentsBuilder callURI = UriComponentsBuilder.fromHttpUrl(urlBuilder.toString());
99
100
101         String fileName = System.currentTimeMillis() + "tosca.csar";
102         ResponseEntity<byte[]> response = callSdcWithAttachment(callURI.build().encode().toUri());
103         File toscaFile = new File(fileName);
104         try {
105             FileOutputStream toscaFileStream = new FileOutputStream(toscaFile);
106             if (response != null) {
107                 IOUtils.write(response.getBody(), toscaFileStream);
108             }
109             toscaFileStream.close();
110         } catch (IOException e) {
111             LOGGER.error("cannot get TOSCA File for url " + toscaModelUrl, e);
112         }
113         return toscaFile;
114
115     }
116
117     private HttpEntity<String> buildRequestHeader() {
118         HttpHeaders httpHeaders = new HttpHeaders();
119         httpHeaders.add(HEADER_ECOMP_INSTANCE_ID, ecompInstanceId);
120         httpHeaders.add(HEADER_AUTHORIZATION, sdcHeaderAuthorization);
121         return new HttpEntity<>("parameters", httpHeaders);
122     }
123
124
125     private ResponseEntity<Object> callSdc(URI callURI) {
126         ResponseEntity<Object> response =
127                 restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), Object.class);
128         if(LOGGER.isDebugEnabled()) {
129             LOGGER.debug("response body : {} ",response.getBody().toString());
130         }
131         LOGGER.info("response status : {}", response.getStatusCodeValue());
132         loggDebugIfResponseKo(callURI.toString(), response);
133         return response;
134     }
135
136
137     private ResponseEntity<byte[]> callSdcWithAttachment(URI callURI) {
138         try {
139             ResponseEntity<byte[]> response =
140                     restTemplate.exchange(callURI, HttpMethod.GET, buildRequestHeader(), byte[].class);
141             LOGGER.info("response status : " + response.getStatusCodeValue());
142             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
143                 LOGGER.warn("HTTP call SDC on {} returns {} ", callURI.toString() , response.getStatusCodeValue());
144             }
145             return response;
146
147         } catch (BackendFunctionalException e) {
148             LOGGER.error("HTTP call SDC on {} error : {}", callURI.toString() , e);
149             return null;
150         }
151     }
152
153
154     private void loggDebugIfResponseKo(String callURI, ResponseEntity<Object> response) {
155         if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
156             LOGGER.warn("HTTP call SDC on {} returns {} , {}", callURI , response.getStatusCodeValue() , response.getBody().toString());
157         }
158     }
159 }
160
161