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
91     private static final Logger LOGGER = LoggerFactory.getLogger(MultiClient.class);
92
93     public Map getServiceCatalog(String id, ServiceOrder serviceOrder, ServiceOrderItem serviceOrderItem) {
94         StringBuilder callURL = new StringBuilder().append(serviceCatalogUrl.getServiceCatalogUrl()).append(id);
95         ResponseEntity<Object> response = callApiGet(callURL.toString(), new HttpHeaders(), null);
96
97         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
98             serviceOrderService.addOrderMessage(serviceOrder, "500");
99             LOGGER.warn("unable to retrieve catalog information for service {}",
100                     serviceOrderItem.getService().getServiceSpecification().getId());
101         }
102         if (response.getStatusCode().is2xxSuccessful()) {
103             return (LinkedHashMap) response.getBody();
104         }
105         return null;
106
107     }
108
109     public boolean doesServiceExistInServiceInventory(String id, String serviceName, String globalSubscriberId,
110             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     private HttpHeaders buildRequestHeaderForAAI() {
125         HttpHeaders httpHeaders = new HttpHeaders();
126         httpHeaders.add(HEADER_AUTHORIZATION, aaiHeaderAuthorization);
127         httpHeaders.add(X_FROM_APP_ID, aaiApiId);
128         httpHeaders.add("Accept", "application/json");
129         httpHeaders.add("Content-Type", "application/json");
130         httpHeaders.add(X_TRANSACTION_ID, aaiTransactionId);
131
132         return httpHeaders;
133     }
134
135     public boolean isTenantIdPresentInAAI(ServiceOrder serviceOrder) {
136         StringBuilder callURL = new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_TENANTS_PATH);
137         String callUrlFormated = callURL.toString().replace("$onap.lcpCloudRegionId", lcpCloudRegionId);
138         callUrlFormated = callUrlFormated.replace("$onap.cloudOwner", cloudOwner);
139
140         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
141         if (response.getStatusCode().is2xxSuccessful()) {
142             LinkedHashMap body = (LinkedHashMap) response.getBody();
143             List<LinkedHashMap> tenants = (List<LinkedHashMap>) body.get("tenant");
144             for (LinkedHashMap tenant : tenants) {
145                 if (tenantId.equalsIgnoreCase((String) tenant.get("tenant-id"))) {
146                     return true;
147                 }
148             }
149         } else {
150             serviceOrderService.addOrderMessage(serviceOrder, "501");
151         }
152         return false;
153     }
154
155     public String getOwningEntityIdInAAI(ServiceOrder serviceOrder) {
156         StringBuilder callURL =
157                 new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_OWNING_ENTITIES);
158         String callUrlFormated = callURL.toString();
159
160         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
161         if (response.getStatusCode().is2xxSuccessful()) {
162             LinkedHashMap body = (LinkedHashMap) response.getBody();
163             List<LinkedHashMap> owningEntities = (List<LinkedHashMap>) body.get("owning-entity");
164             for (LinkedHashMap owningEntity : owningEntities) {
165                 if (owningEntityName.equalsIgnoreCase((String) owningEntity.get("owning-entity-name"))) {
166                     return owningEntity.get("owning-entity-id").toString();
167                 }
168             }
169         } else {
170             serviceOrderService.addOrderMessage(serviceOrder, "501");
171         }
172         return null;
173     }
174
175     public boolean isCustomerPresentInAAI(String customerId, ServiceOrder serviceOrder) {
176         StringBuilder callURL = new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_CUSTOMER_PATH)
177                 .append(customerId);
178         ResponseEntity<Object> response = callApiGet(callURL.toString(), buildRequestHeaderForAAI(), null);
179         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
180             serviceOrderService.addOrderMessage(serviceOrder, "501");
181             return false;
182         }
183         return response.getStatusCode().equals(HttpStatus.OK);
184     }
185
186     public boolean putOwningEntity(ServiceOrder serviceOrder) {
187         Map<String, String> param = new HashMap<>();
188         param.put("owning-entity-id", owningEntityId);
189         param.put("owning-entity-name", owningEntityName);
190         String callURL = aaiHost + OnapComponentsUrlPaths.AAI_PUT_OWNING_ENTITIES;
191         String callUrlFormated = callURL.replace("$onap.owning.entity.id", owningEntityId);
192         ResponseEntity<Object> response = putRequest(param, callUrlFormated, buildRequestHeaderForAAI());
193         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
194             serviceOrderService.addOrderMessage(serviceOrder, "501");
195             return false;
196         }
197         return response.getStatusCode().equals(HttpStatus.CREATED);
198     }
199
200     public boolean putCustomer(SubscriberInfo subscriberInfo, ServiceOrder serviceOrder) {
201         Map<String, String> param = new HashMap<>();
202         param.put("global-customer-id", subscriberInfo.getGlobalSubscriberId());
203         param.put("subscriber-name", subscriberInfo.getSubscriberName());
204         param.put("subscriber-type", "BSS");
205         String callURL =
206                 aaiHost + OnapComponentsUrlPaths.AAI_GET_CUSTOMER_PATH + subscriberInfo.getGlobalSubscriberId();
207
208         ResponseEntity<Object> response = putRequest(param, callURL, buildRequestHeaderForAAI());
209         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
210             serviceOrderService.addOrderMessage(serviceOrder, "501");
211             return false;
212         }
213         return response.getStatusCode().equals(HttpStatus.CREATED);
214     }
215
216     public Map getServicesInAaiForCustomer(String customerId, ServiceOrder serviceOrder) {
217         StringBuilder callURL =
218                 new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_SERVICES_FOR_CUSTOMER_PATH);
219         String callUrlFormated = callURL.toString().replace("$customerId", customerId);
220
221         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
222         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
223             serviceOrderService.addOrderMessage(serviceOrder, "501");
224             return null;
225         } else if (response.getStatusCode().is2xxSuccessful()) {
226             return (LinkedHashMap) response.getBody();
227         }
228         return null;
229     }
230
231     public boolean putServiceType(String globalSubscriberId, String serviceName, ServiceOrder serviceOrder) {
232         Map<String, String> param = new HashMap<>();
233         param.put("service-type", serviceName);
234         String callURL = aaiHost + OnapComponentsUrlPaths.AAI_PUT_SERVICE_FOR_CUSTOMER_PATH + serviceName;
235         String callUrlFormated = callURL.replace("$customerId", globalSubscriberId);
236         ResponseEntity<Object> response = putRequest(param, callUrlFormated, buildRequestHeaderForAAI());
237         if (response.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) {
238             serviceOrderService.addOrderMessage(serviceOrder, "501");
239         }
240         return response.getStatusCode().is2xxSuccessful();
241     }
242
243     private ResponseEntity<Object> putRequest(Map<String, String> param, String callUrl, HttpHeaders httpHeaders) {
244         try {
245             ResponseEntity<Object> response =
246                     restTemplate.exchange(callUrl, HttpMethod.PUT, new HttpEntity<>(param, httpHeaders), Object.class);
247             LOGGER.info("response status : " + response.getStatusCodeValue());
248             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.CREATED)) {
249                 LOGGER.warn("HTTP call on {} returns {} , {}", callUrl, response.getStatusCodeValue(),
250                         response.getBody().toString());
251             }
252             return response;
253         } catch (BackendFunctionalException e) {
254             LOGGER.error("error on calling " + callUrl + " ," + e);
255             return new ResponseEntity<>("problem calling onap services", e.getHttpStatus());
256         } catch (ResourceAccessException e) {
257             LOGGER.error("error on calling " + callUrl + " ," + e);
258             return new ResponseEntity<>("unable to reach onap services", HttpStatus.INTERNAL_SERVER_ERROR);
259         }
260     }
261
262     private ResponseEntity<Object> callApiGet(String callURL, HttpHeaders httpHeaders, Map<String, String> param) {
263         try {
264             UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(callURL);
265             if (param != null) {
266                 for (Entry<String, String> stringEntry : param.entrySet()) {
267                     builder.queryParam(stringEntry.getKey(), stringEntry.getValue());
268
269                 }
270             }
271             URI uri = builder.build().encode().toUri();
272             ResponseEntity<Object> response =
273                     restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<>(httpHeaders), Object.class);
274             if (LOGGER.isDebugEnabled()) {
275                 LOGGER.debug("response body : {}", response.getBody().toString());
276             }
277             LOGGER.info("response status : {}", response.getStatusCodeValue());
278             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
279                 LOGGER.warn("HTTP call on {} returns {} , {}", callURL, response.getStatusCodeValue(),
280                         response.getBody().toString());
281
282             }
283             return response;
284
285         } catch (BackendFunctionalException e) {
286             LOGGER.error("error on calling " + callURL + " ," + e);
287             return new ResponseEntity<>("problem calling onap services", e.getHttpStatus());
288         } catch (ResourceAccessException e) {
289             LOGGER.error("error on calling " + callURL + " ," + e);
290             return new ResponseEntity<>("unable to reach onap services", HttpStatus.INTERNAL_SERVER_ERROR);
291         }
292
293     }
294
295 }