6a38fbcce559039c07d31e449039dfbbd0217115
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / serviceorder / MultiClient.java
1 /**
2  *     Copyright (c) 2018 Orange
3  *
4  *     Licensed under the Apache License, Version 2.0 (the "License");
5  *     you may not use this file except in compliance with the License.
6  *     You may obtain a copy of the License at
7  *
8  *         http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *     Unless required by applicable law or agreed to in writing, software
11  *     distributed under the License is distributed on an "AS IS" BASIS,
12  *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *     See the License for the specific language governing permissions and
14  *     limitations under the License.
15  */
16 package org.onap.nbi.apis.serviceorder;
17
18 import java.net.URI;
19 import java.util.HashMap;
20 import java.util.LinkedHashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Map.Entry;
24 import org.onap.nbi.OnapComponentsUrlPaths;
25 import org.onap.nbi.apis.serviceorder.model.ServiceOrder;
26 import org.onap.nbi.apis.serviceorder.model.ServiceOrderItem;
27 import org.onap.nbi.apis.serviceorder.model.consumer.SubscriberInfo;
28 import org.onap.nbi.apis.serviceorder.service.ServiceOrderService;
29 import org.onap.nbi.exceptions.BackendFunctionalException;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32 import org.springframework.beans.factory.annotation.Autowired;
33 import org.springframework.beans.factory.annotation.Value;
34 import org.springframework.http.HttpEntity;
35 import org.springframework.http.HttpHeaders;
36 import org.springframework.http.HttpMethod;
37 import org.springframework.http.HttpStatus;
38 import org.springframework.http.ResponseEntity;
39 import org.springframework.stereotype.Service;
40 import org.springframework.web.client.ResourceAccessException;
41 import org.springframework.web.client.RestTemplate;
42 import org.springframework.web.util.UriComponentsBuilder;
43
44 @Service
45 public class MultiClient {
46
47     @Autowired
48     private RestTemplate restTemplate;
49
50     @Value("${aai.host}")
51     private String aaiHost;
52
53     @Value("${aai.header.authorization}")
54     private String aaiHeaderAuthorization;
55
56     @Value("${aai.api.id}")
57     private String aaiApiId;
58
59     @Value("${aai.header.transaction.id}")
60     private String aaiTransactionId;
61
62
63     @Value("${onap.lcpCloudRegionId}")
64     private String lcpCloudRegionId;
65
66     @Value("${onap.tenantId}")
67     private String tenantId;
68
69     @Value("${onap.cloudOwner}")
70     private String cloudOwner;
71
72     @Value("${so.owning.entity.id}")
73     private String owningEntityId;
74
75     @Value("${so.owning.entity.name}")
76     private String owningEntityName;
77
78     @Autowired
79     private ServiceCatalogUrl serviceCatalogUrl;
80
81     @Autowired
82     private ServiceInventoryUrl serviceInventoryUrl;
83
84     @Autowired
85     private ServiceOrderService serviceOrderService;
86
87
88     private static final String HEADER_AUTHORIZATION = "Authorization";
89     private static final String X_FROM_APP_ID = "X-FromAppId";
90     private static final String X_TRANSACTION_ID = "X-TransactionId";
91
92     private static final Logger LOGGER = LoggerFactory.getLogger(MultiClient.class);
93
94     public Map getServiceCatalog(String id,ServiceOrder serviceOrder, ServiceOrderItem serviceOrderItem){
95         StringBuilder callURL = new StringBuilder().append(serviceCatalogUrl.getServiceCatalogUrl()).append(id);
96         ResponseEntity<Object> response = callApiGet(callURL.toString(), new HttpHeaders(), null);
97
98         if(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
99             serviceOrderService.addOrderMessage(serviceOrder, "500");
100             LOGGER.warn("unable to retrieve catalog information for service {}",
101                 serviceOrderItem.getService().getServiceSpecification().getId());
102         }
103         if (response.getStatusCode().is2xxSuccessful()) {
104             return (LinkedHashMap) response.getBody();
105         }
106         return null;
107
108     }
109
110     public boolean doesServiceExistInServiceInventory(String id, String serviceName, String globalSubscriberId, ServiceOrder serviceOrder) {
111         StringBuilder callURL = new StringBuilder().append(serviceInventoryUrl.getServiceInventoryUrl()).append(id);
112         Map<String, String> param = new HashMap<>();
113         param.put("serviceSpecification.name", serviceName);
114         param.put("relatedParty.id", globalSubscriberId);
115
116         ResponseEntity<Object> response = callApiGet(callURL.toString(), new HttpHeaders(), param);
117         if(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
118             serviceOrderService.addOrderMessage(serviceOrder, "501");
119             return false;
120         }
121         return response.getStatusCode().equals(HttpStatus.OK);
122     }
123
124
125     private HttpHeaders buildRequestHeaderForAAI() {
126         HttpHeaders httpHeaders = new HttpHeaders();
127         httpHeaders.add(HEADER_AUTHORIZATION, aaiHeaderAuthorization);
128         httpHeaders.add(X_FROM_APP_ID, aaiApiId);
129         httpHeaders.add("Accept", "application/json");
130         httpHeaders.add("Content-Type", "application/json");
131         httpHeaders.add(X_TRANSACTION_ID, aaiTransactionId);
132
133         return httpHeaders;
134     }
135
136
137     public boolean isTenantIdPresentInAAI(ServiceOrder serviceOrder) {
138         StringBuilder callURL = new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_TENANTS_PATH);
139         String callUrlFormated = callURL.toString().replace("$onap.lcpCloudRegionId", lcpCloudRegionId);
140         callUrlFormated = callUrlFormated.replace("$onap.cloudOwner", cloudOwner);
141
142         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
143         if (response.getStatusCode().is2xxSuccessful()) {
144             LinkedHashMap body = (LinkedHashMap) response.getBody();
145             List<LinkedHashMap> tenants = (List<LinkedHashMap>) body.get("tenant");
146             for (LinkedHashMap tenant : tenants) {
147                 if (tenantId.equalsIgnoreCase((String) tenant.get("tenant-id"))) {
148                     return true;
149                 }
150             }
151         } else {
152             serviceOrderService.addOrderMessage(serviceOrder, "501");
153         }
154         return false;
155     }
156
157
158     public String getOwningEntityIdInAAI(ServiceOrder serviceOrder) {
159         StringBuilder callURL = new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_OWNING_ENTITIES);
160         String callUrlFormated = callURL.toString();
161
162         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
163         if (response.getStatusCode().is2xxSuccessful()) {
164             LinkedHashMap body = (LinkedHashMap) response.getBody();
165             List<LinkedHashMap> owningEntities = (List<LinkedHashMap>) body.get("owning-entity");
166             for (LinkedHashMap owningEntity : owningEntities) {
167                 if (owningEntityName.equalsIgnoreCase((String) owningEntity.get("owning-entity-name"))) {
168                     return owningEntity.get("owning-entity-id").toString();
169                 }
170             }
171         } else {
172             serviceOrderService.addOrderMessage(serviceOrder, "501");
173         }
174         return null;
175     }
176
177
178     public boolean isCustomerPresentInAAI(String customerId,
179         ServiceOrder serviceOrder) {
180         StringBuilder callURL = new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_CUSTOMER_PATH)
181                 .append(customerId);
182         ResponseEntity<Object> response = callApiGet(callURL.toString(), buildRequestHeaderForAAI(), null);
183         if(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
184             serviceOrderService.addOrderMessage(serviceOrder, "501");
185             return false;
186         }
187         return response.getStatusCode().equals(HttpStatus.OK);
188     }
189
190
191     public boolean putOwningEntity(ServiceOrder serviceOrder) {
192         Map<String, String> param = new HashMap<>();
193         param.put("owning-entity-id", owningEntityId);
194         param.put("owning-entity-name", owningEntityName);
195         String callURL =
196             aaiHost + OnapComponentsUrlPaths.AAI_PUT_OWNING_ENTITIES;
197         String callUrlFormated = callURL.replace("$onap.owning.entity.id", owningEntityId);
198         ResponseEntity<Object> response = putRequest(param, callUrlFormated, buildRequestHeaderForAAI());
199         if(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
200             serviceOrderService.addOrderMessage(serviceOrder, "501");
201             return false;
202         }
203         return response.getStatusCode().equals(HttpStatus.CREATED);
204     }
205
206
207     public boolean putCustomer(SubscriberInfo subscriberInfo,
208         ServiceOrder serviceOrder) {
209         Map<String, String> param = new HashMap<>();
210         param.put("global-customer-id", subscriberInfo.getGlobalSubscriberId());
211         param.put("subscriber-name", subscriberInfo.getSubscriberName());
212         param.put("subscriber-type", "BSS");
213         String callURL =
214                 aaiHost + OnapComponentsUrlPaths.AAI_GET_CUSTOMER_PATH + subscriberInfo.getGlobalSubscriberId();
215
216         ResponseEntity<Object> response = putRequest(param, callURL, buildRequestHeaderForAAI());
217         if(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
218             serviceOrderService.addOrderMessage(serviceOrder, "501");
219             return false;
220         }
221         return response.getStatusCode().equals(HttpStatus.CREATED);
222     }
223
224
225     public Map getServicesInAaiForCustomer(String customerId,
226         ServiceOrder serviceOrder) {
227         StringBuilder callURL =
228                 new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_SERVICES_FOR_CUSTOMER_PATH);
229         String callUrlFormated = callURL.toString().replace("$customerId", customerId);
230
231         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
232         if(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
233             serviceOrderService.addOrderMessage(serviceOrder, "501");
234             return null;
235         }
236         else if (response.getStatusCode().is2xxSuccessful()) {
237             return (LinkedHashMap) response.getBody();
238         }
239         return null;
240     }
241
242     public boolean putServiceType(String globalSubscriberId, String serviceName,
243         ServiceOrder serviceOrder) {
244         Map<String, String> param = new HashMap<>();
245         param.put("service-type", serviceName);
246         String callURL = aaiHost + OnapComponentsUrlPaths.AAI_PUT_SERVICE_FOR_CUSTOMER_PATH + serviceName;
247         String callUrlFormated = callURL.replace("$customerId", globalSubscriberId);
248         ResponseEntity<Object> response =  putRequest(param, callUrlFormated, buildRequestHeaderForAAI());
249         if(response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
250             serviceOrderService.addOrderMessage(serviceOrder, "501");
251         }
252         return response.getStatusCode().is2xxSuccessful();
253     }
254
255
256     private  ResponseEntity<Object> putRequest(Map<String, String> param, String callUrl, HttpHeaders httpHeaders) {
257         try {
258             ResponseEntity<Object> response =
259                     restTemplate.exchange(callUrl, HttpMethod.PUT, new HttpEntity<>(param, httpHeaders), Object.class);
260             LOGGER.info("response status : " + response.getStatusCodeValue());
261             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.CREATED)) {
262                 LOGGER.warn("HTTP call on {} returns {} , {}", callUrl , response.getStatusCodeValue(), response.getBody().toString());
263             }
264             return response;
265         } catch (BackendFunctionalException e) {
266             LOGGER.error("error on calling " + callUrl + " ," + e);
267             return new ResponseEntity<>("problem calling onap services", e.getHttpStatus());
268         }catch (ResourceAccessException e) {
269             LOGGER.error("error on calling " + callUrl + " ," + e);
270             return new ResponseEntity<>("unable to reach onap services", HttpStatus.INTERNAL_SERVER_ERROR);
271         }
272     }
273
274     private ResponseEntity<Object> callApiGet(String callURL, HttpHeaders httpHeaders, Map<String, String> param) {
275         try {
276             UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(callURL);
277             if (param != null) {
278                 for (Entry<String, String> stringEntry : param.entrySet()) {
279                     builder.queryParam(stringEntry.getKey(), stringEntry.getValue());
280
281                 }
282             }
283             URI uri = builder.build().encode().toUri();
284             ResponseEntity<Object> response =
285                     restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<>(httpHeaders), Object.class);
286             if(LOGGER.isDebugEnabled()){
287                 LOGGER.debug("response body : {}", response.getBody().toString());
288             }
289             LOGGER.info("response status : {}", response.getStatusCodeValue());
290             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
291                 LOGGER.warn("HTTP call on {} returns {} , {}", callURL , response.getStatusCodeValue(), response.getBody().toString());
292
293             }
294             return response;
295
296         } catch (BackendFunctionalException e) {
297             LOGGER.error("error on calling " + callURL + " ," + e);
298             return new ResponseEntity<>("problem calling onap services", e.getHttpStatus());
299         }catch (ResourceAccessException e) {
300             LOGGER.error("error on calling " + callURL + " ," + e);
301             return new ResponseEntity<>("unable to reach onap services", HttpStatus.INTERNAL_SERVER_ERROR);
302         }
303
304     }
305
306
307 }