fix sonar alert
[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.consumer.SubscriberInfo;
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.web.client.ResourceAccessException;
38 import org.springframework.web.client.RestTemplate;
39 import org.springframework.web.util.UriComponentsBuilder;
40
41 @Service
42 public class MultiClient {
43
44     @Autowired
45     private RestTemplate restTemplate;
46
47     @Value("${aai.host}")
48     private String aaiHost;
49
50     @Value("${aai.header.authorization}")
51     private String aaiHeaderAuthorization;
52
53     @Value("${aai.api.id}")
54     private String aaiApiId;
55
56     @Value("${onap.lcpCloudRegionId}")
57     private String lcpCloudRegionId;
58
59     @Value("${onap.tenantId}")
60     private String tenantId;
61
62     @Value("${onap.cloudOwner}")
63     private String cloudOwner;
64
65     @Autowired
66     private ServiceCatalogUrl serviceCatalogUrl;
67
68     @Autowired
69     private ServiceInventoryUrl serviceInventoryUrl;
70
71
72     private static final String HEADER_AUTHORIZATION = "Authorization";
73     private static final String X_FROM_APP_ID = "X-FromAppId";
74
75     private static final Logger LOGGER = LoggerFactory.getLogger(MultiClient.class);
76
77     public ResponseEntity<Object> getServiceCatalog(String id) {
78         StringBuilder callURL = new StringBuilder().append(serviceCatalogUrl.getServiceCatalogUrl()).append(id);
79        return callApiGet(callURL.toString(), new HttpHeaders(), null);
80     }
81
82     public boolean doesServiceExistInServiceInventory(String id, String serviceName, String globalSubscriberId) {
83         StringBuilder callURL = new StringBuilder().append(serviceInventoryUrl.getServiceInventoryUrl()).append(id);
84         Map<String, String> param = new HashMap<>();
85         param.put("serviceSpecification.name", serviceName);
86         param.put("relatedParty.id", globalSubscriberId);
87
88         ResponseEntity<Object> response = callApiGet(callURL.toString(), new HttpHeaders(), param);
89        return response != null && response.getStatusCode().equals(HttpStatus.OK);
90     }
91
92
93     private HttpHeaders buildRequestHeaderForAAI() {
94         HttpHeaders httpHeaders = new HttpHeaders();
95         httpHeaders.add(HEADER_AUTHORIZATION, aaiHeaderAuthorization);
96         httpHeaders.add(X_FROM_APP_ID, aaiApiId);
97         httpHeaders.add("Accept", "application/json");
98         httpHeaders.add("Content-Type", "application/json");
99         return httpHeaders;
100     }
101
102
103     public boolean isTenantIdPresentInAAI() {
104         StringBuilder callURL = new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_TENANTS_PATH);
105         String callUrlFormated = callURL.toString().replace("$onap.lcpCloudRegionId", lcpCloudRegionId);
106         callUrlFormated = callUrlFormated.replace("$onap.cloudOwner", cloudOwner);
107
108         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
109         if (response != null) {
110             LinkedHashMap body = (LinkedHashMap) response.getBody();
111             List<LinkedHashMap> tenants = (List<LinkedHashMap>) body.get("tenant");
112             for (LinkedHashMap tenant : tenants) {
113                 if (tenantId.equalsIgnoreCase((String) tenant.get("tenant-id"))) {
114                     return true;
115                 }
116             }
117         }
118         return false;
119     }
120
121     public boolean isCustomerPresentInAAI(String customerId) {
122         StringBuilder callURL = new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_CUSTOMER_PATH)
123                 .append(customerId);
124         ResponseEntity<Object> response = callApiGet(callURL.toString(), buildRequestHeaderForAAI(), null);
125         return(response != null && response.getStatusCode().equals(HttpStatus.OK));
126     }
127
128
129     public boolean putCustomer(SubscriberInfo subscriberInfo) {
130         Map<String, String> param = new HashMap<>();
131         param.put("global-customer-id", subscriberInfo.getGlobalSubscriberId());
132         param.put("subscriber-name", subscriberInfo.getSubscriberName());
133         param.put("subscriber-type", "BSS");
134         String callURL =
135                 aaiHost + OnapComponentsUrlPaths.AAI_GET_CUSTOMER_PATH + subscriberInfo.getGlobalSubscriberId();
136
137         ResponseEntity<Object> response = putRequest(param, callURL, buildRequestHeaderForAAI());
138         return response != null && response.getStatusCode().equals(HttpStatus.CREATED);
139     }
140
141
142     public Map getServicesInAaiForCustomer(String customerId) {
143         StringBuilder callURL =
144                 new StringBuilder().append(aaiHost).append(OnapComponentsUrlPaths.AAI_GET_SERVICES_FOR_CUSTOMER_PATH);
145         String callUrlFormated = callURL.toString().replace("$customerId", customerId);
146
147         ResponseEntity<Object> response = callApiGet(callUrlFormated, buildRequestHeaderForAAI(), null);
148         if (response != null && response.getStatusCode().equals(HttpStatus.OK)) {
149             return (LinkedHashMap) response.getBody();
150         }
151         return null;
152     }
153
154     public boolean putServiceType(String globalSubscriberId, String serviceName) {
155         Map<String, String> param = new HashMap<>();
156         param.put("service-type", serviceName);
157         String callURL = aaiHost + OnapComponentsUrlPaths.AAI_PUT_SERVICE_FOR_CUSTOMER_PATH + serviceName;
158         String callUrlFormated = callURL.replace("$customerId", globalSubscriberId);
159         ResponseEntity<Object> response =  putRequest(param, callUrlFormated, buildRequestHeaderForAAI());
160         return response != null && response.getStatusCode().equals(HttpStatus.CREATED);
161     }
162
163
164     private  ResponseEntity<Object> putRequest(Map<String, String> param, String callUrl, HttpHeaders httpHeaders) {
165         try {
166             ResponseEntity<Object> response =
167                     restTemplate.exchange(callUrl, HttpMethod.PUT, new HttpEntity<>(param, httpHeaders), Object.class);
168             LOGGER.info("response status : " + response.getStatusCodeValue());
169             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.CREATED)) {
170                 LOGGER.warn("HTTP call on {} returns {} , {}", callUrl , response.getStatusCodeValue(), response.getBody().toString());
171             }
172             return response;
173         } catch (BackendFunctionalException|ResourceAccessException e) {
174             LOGGER.error("error on calling " + callUrl + " ," + e);
175             return null;
176         }
177     }
178
179     private ResponseEntity<Object> callApiGet(String callURL, HttpHeaders httpHeaders, Map<String, String> param) {
180
181
182         try {
183
184             UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(callURL);
185             if (param != null) {
186                 for (Entry<String, String> stringEntry : param.entrySet()) {
187                     builder.queryParam(stringEntry.getKey(), stringEntry.getValue());
188
189                 }
190             }
191             URI uri = builder.build().encode().toUri();
192
193
194             ResponseEntity<Object> response =
195                     restTemplate.exchange(uri, HttpMethod.GET, new HttpEntity<>(httpHeaders), Object.class);
196             if(LOGGER.isDebugEnabled()){
197                 LOGGER.debug("response body : {}", response.getBody().toString());
198             }
199             LOGGER.info("response status : {}", response.getStatusCodeValue());
200             if (LOGGER.isWarnEnabled() && !response.getStatusCode().equals(HttpStatus.OK)) {
201                 LOGGER.warn("HTTP call on {} returns {} , {}", callURL , response.getStatusCodeValue(), response.getBody().toString());
202
203             }
204             return response;
205
206         } catch (BackendFunctionalException|ResourceAccessException e) {
207             LOGGER.error("error on calling " + callURL + " ," + e);
208             return null;
209         }
210     }
211
212
213 }