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