Merge "Initial draft of Frankfurt Release notes for RC0"
[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
17 package org.onap.nbi.apis.serviceorder;
18
19 import java.net.URI;
20 import java.util.HashMap;
21 import java.util.LinkedHashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Map.Entry;
25 import org.onap.nbi.OnapComponentsUrlPaths;
26 import org.onap.nbi.apis.serviceorder.model.ServiceOrder;
27 import org.onap.nbi.apis.serviceorder.model.ServiceOrderItem;
28 import org.onap.nbi.apis.serviceorder.model.consumer.SubscriberInfo;
29 import org.onap.nbi.apis.serviceorder.service.ServiceOrderService;
30 import org.onap.nbi.exceptions.BackendFunctionalException;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33 import org.springframework.beans.factory.annotation.Autowired;
34 import org.springframework.beans.factory.annotation.Value;
35 import org.springframework.http.HttpEntity;
36 import org.springframework.http.HttpHeaders;
37 import org.springframework.http.HttpMethod;
38 import org.springframework.http.HttpStatus;
39 import org.springframework.http.ResponseEntity;
40 import org.springframework.stereotype.Service;
41 import org.springframework.web.client.ResourceAccessException;
42 import org.springframework.web.client.RestTemplate;
43 import org.springframework.web.util.UriComponentsBuilder;
44
45 @Service
46 public class MultiClient {
47
48     @Autowired
49     private RestTemplate restTemplate;
50
51     @Value("${aai.host}")
52     private String aaiHost;
53
54     @Value("${aai.header.authorization}")
55     private String aaiHeaderAuthorization;
56
57     @Value("${aai.api.id}")
58     private String aaiApiId;
59
60     @Value("${aai.header.transaction.id}")
61     private String aaiTransactionId;
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     private static final String HEADER_AUTHORIZATION = "Authorization";
88     private static final String X_FROM_APP_ID = "X-FromAppId";
89     private static final String X_TRANSACTION_ID = "X-TransactionId";
90     private static final String EXCEPTION_STRING = "error on calling";
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,
111             ServiceOrder serviceOrder) {
112         StringBuilder callURL = new StringBuilder().append(serviceInventoryUrl.getServiceInventoryUrl()).append(id);
113         Map<String, String> param = new HashMap<>();
114         param.put("serviceSpecification.name", serviceName);
115         param.put("relatedParty.id", globalSubscriberId);
116
117         ResponseEntity<Object> response = callApiGet(callURL.toString(), new HttpHeaders(), param);
118         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
119             serviceOrderService.addOrderMessage(serviceOrder, "501");
120             return false;
121         }
122         return response.getStatusCode().equals(HttpStatus.OK);
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     public boolean isTenantIdPresentInAAI(ServiceOrder serviceOrder) {
137         StringBuilder callURL = new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_TENANTS_PATH);
138         String callUrlFormated = callURL.toString().replace("$onap.lcpCloudRegionId", lcpCloudRegionId);
139         callUrlFormated = callUrlFormated.replace("$onap.cloudOwner", cloudOwner);
140
141         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
142         if (response.getStatusCode().is2xxSuccessful()) {
143             LinkedHashMap body = (LinkedHashMap) response.getBody();
144             List<LinkedHashMap> tenants = (List<LinkedHashMap>) body.get("tenant");
145             for (LinkedHashMap tenant : tenants) {
146                 if (tenantId.equalsIgnoreCase((String) tenant.get("tenant-id"))) {
147                     return true;
148                 }
149             }
150         } else {
151             serviceOrderService.addOrderMessage(serviceOrder, "501");
152         }
153         return false;
154     }
155
156     public String getOwningEntityIdInAAI(ServiceOrder serviceOrder) {
157         StringBuilder callURL =
158                 new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_OWNING_ENTITIES);
159         String callUrlFormated = callURL.toString();
160
161         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
162         if (response.getStatusCode().is2xxSuccessful()) {
163             LinkedHashMap body = (LinkedHashMap) response.getBody();
164             List<LinkedHashMap> owningEntities = (List<LinkedHashMap>) body.get("owning-entity");
165             for (LinkedHashMap owningEntity : owningEntities) {
166                 if (owningEntityName.equalsIgnoreCase((String) owningEntity.get("owning-entity-name"))) {
167                     return owningEntity.get("owning-entity-id").toString();
168                 }
169             }
170         } else {
171             serviceOrderService.addOrderMessage(serviceOrder, "501");
172         }
173         return null;
174     }
175
176     public boolean isCustomerPresentInAAI(String customerId, ServiceOrder serviceOrder) {
177         StringBuilder callURL = new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_CUSTOMER_PATH)
178                 .append(customerId);
179         ResponseEntity<Object> response = callApiGet(callURL.toString(), buildRequestHeaderForAAI(), null);
180         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
181             serviceOrderService.addOrderMessage(serviceOrder, "501");
182             return false;
183         }
184         return response.getStatusCode().equals(HttpStatus.OK);
185     }
186
187     public boolean putOwningEntity(ServiceOrder serviceOrder) {
188         Map<String, String> param = new HashMap<>();
189         param.put("owning-entity-id", owningEntityId);
190         param.put("owning-entity-name", owningEntityName);
191         String callURL = aaiHost + OnapComponentsUrlPaths.AAI_PUT_OWNING_ENTITIES;
192         String callUrlFormated = callURL.replace("$onap.owning.entity.id", owningEntityId);
193         ResponseEntity<Object> response = putRequest(param, callUrlFormated, buildRequestHeaderForAAI());
194         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
195             serviceOrderService.addOrderMessage(serviceOrder, "501");
196             return false;
197         }
198         return response.getStatusCode().equals(HttpStatus.CREATED);
199     }
200
201     public boolean putCustomer(SubscriberInfo subscriberInfo, ServiceOrder serviceOrder) {
202         Map<String, String> param = new HashMap<>();
203         param.put("global-customer-id", subscriberInfo.getGlobalSubscriberId());
204         param.put("subscriber-name", subscriberInfo.getSubscriberName());
205         param.put("subscriber-type", "BSS");
206         String callURL =
207                 aaiHost + OnapComponentsUrlPaths.AAI_GET_CUSTOMER_PATH + subscriberInfo.getGlobalSubscriberId();
208
209         ResponseEntity<Object> response = putRequest(param, callURL, buildRequestHeaderForAAI());
210         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
211             serviceOrderService.addOrderMessage(serviceOrder, "501");
212             return false;
213         }
214         return response.getStatusCode().equals(HttpStatus.CREATED);
215     }
216
217     public Map getServicesInAaiForCustomer(String customerId, ServiceOrder serviceOrder) {
218         StringBuilder callURL =
219                 new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_SERVICES_FOR_CUSTOMER_PATH);
220         String callUrlFormated = callURL.toString().replace("$customerId", customerId);
221
222         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
223         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
224             serviceOrderService.addOrderMessage(serviceOrder, "501");
225             return null;
226         } else if (response.getStatusCode().is2xxSuccessful()) {
227             return (LinkedHashMap) response.getBody();
228         }
229         return null;
230     }
231
232     public boolean putServiceType(String globalSubscriberId, String serviceName, ServiceOrder serviceOrder) {
233         Map<String, String> param = new HashMap<>();
234         param.put("service-type", serviceName);
235         String callURL = aaiHost + OnapComponentsUrlPaths.AAI_PUT_SERVICE_FOR_CUSTOMER_PATH + serviceName;
236         String callUrlFormated = callURL.replace("$customerId", globalSubscriberId);
237         ResponseEntity<Object> response = putRequest(param, callUrlFormated, buildRequestHeaderForAAI());
238         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
239             serviceOrderService.addOrderMessage(serviceOrder, "501");
240         }
241         return response.getStatusCode().is2xxSuccessful();
242     }
243
244     private ResponseEntity<Object> putRequest(Map<String, String> param, String callUrl, HttpHeaders httpHeaders) {
245         try {
246             ResponseEntity<Object> response =
247                     restTemplate.exchange(callUrl, HttpMethod.PUT, new HttpEntity<>(param, httpHeaders), Object.class);
248             LOGGER.info("response status :{} " , response.getStatusCodeValue());
249             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.CREATED)) {
250                 LOGGER.warn("HTTP call on {} returns {} , {}", callUrl, response.getStatusCodeValue(),
251                         response.getBody());
252             }
253             return response;
254         } catch (BackendFunctionalException e) {
255             LOGGER.error(EXCEPTION_STRING , callUrl , e);
256             return new ResponseEntity<>("problem calling onap services", e.getHttpStatus());
257         } catch (ResourceAccessException e) {
258             LOGGER.error(EXCEPTION_STRING , callUrl , e);
259             return new ResponseEntity<>("unable to reach onap services", HttpStatus.INTERNAL_SERVER_ERROR);
260         }
261     }
262
263     private ResponseEntity<Object> callApiGet(String callURL, HttpHeaders httpHeaders, Map<String, String> param) {
264         try {
265             UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(callURL);
266             if (param != null) {
267                 for (Entry<String, String> stringEntry : param.entrySet()) {
268                     builder.queryParam(stringEntry.getKey(), stringEntry.getValue());
269
270                 }
271             }
272             URI uri = builder.build().encode().toUri();
273             ResponseEntity<Object> response =
274                     restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<>(httpHeaders), Object.class);
275             if (LOGGER.isDebugEnabled()) {
276                 LOGGER.debug("response body : {}", response.getBody());
277             }
278             LOGGER.info("response status : {}", response.getStatusCodeValue());
279             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
280                 LOGGER.warn("HTTP call on {} returns {} , {}", callURL, response.getStatusCodeValue(),
281                         response.getBody());
282
283             }
284             return response;
285
286         } catch (BackendFunctionalException e) {
287             LOGGER.error(EXCEPTION_STRING,callURL , e);
288             return new ResponseEntity<>("problem calling onap services", e.getHttpStatus());
289         } catch (ResourceAccessException e) {
290             LOGGER.error(EXCEPTION_STRING , callURL, e);
291             return new ResponseEntity<>("unable to reach onap services", HttpStatus.INTERNAL_SERVER_ERROR);
292         }
293
294     }
295
296 }