Merge "Increasing test coverage for vid.mso.model"
[vid.git] / vid-app-common / src / main / java / org / onap / vid / aai / AaiClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.vid.aai;
22
23 import static java.util.Collections.emptyList;
24 import static java.util.stream.Collectors.toMap;
25 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
26 import static org.apache.commons.lang3.StringUtils.equalsIgnoreCase;
27 import static org.apache.commons.lang3.StringUtils.isEmpty;
28
29 import com.fasterxml.jackson.databind.JsonNode;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import java.io.IOException;
32 import java.io.UnsupportedEncodingException;
33 import java.net.URI;
34 import java.net.URLEncoder;
35 import java.util.LinkedHashMap;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.UUID;
39 import java.util.function.Function;
40 import javax.inject.Inject;
41 import javax.ws.rs.WebApplicationException;
42 import javax.ws.rs.core.Response;
43 import org.apache.commons.lang3.StringUtils;
44 import org.apache.http.HttpStatus;
45 import org.apache.http.client.utils.URIBuilder;
46 import org.jetbrains.annotations.NotNull;
47 import org.json.simple.JSONArray;
48 import org.json.simple.JSONObject;
49 import org.json.simple.parser.JSONParser;
50 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
51 import org.onap.vid.aai.exceptions.InvalidAAIResponseException;
52 import org.onap.vid.aai.model.AaiGetAicZone.AicZones;
53 import org.onap.vid.aai.model.AaiGetInstanceGroupsByCloudRegion;
54 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetNetworkCollectionDetails;
55 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetNetworkCollectionDetailsHelper;
56 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.AaiGetRelatedInstanceGroupsByVnfId;
57 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.CloudRegion;
58 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.InstanceGroup;
59 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Network;
60 import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
61 import org.onap.vid.aai.model.AaiGetPnfResponse;
62 import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
63 import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone;
64 import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
65 import org.onap.vid.aai.model.CustomQuerySimpleResult;
66 import org.onap.vid.aai.model.GetServiceModelsByDistributionStatusResponse;
67 import org.onap.vid.aai.model.LogicalLinkResponse;
68 import org.onap.vid.aai.model.OwningEntityResponse;
69 import org.onap.vid.aai.model.PortDetailsTranslator;
70 import org.onap.vid.aai.model.ProjectResponse;
71 import org.onap.vid.aai.model.Properties;
72 import org.onap.vid.aai.model.ResourceType;
73 import org.onap.vid.aai.model.ServiceRelationships;
74 import org.onap.vid.aai.model.SimpleResult;
75 import org.onap.vid.aai.util.AAIRestInterface;
76 import org.onap.vid.aai.util.CacheProvider;
77 import org.onap.vid.aai.util.VidObjectMapperType;
78 import org.onap.vid.exceptions.GenericUncheckedException;
79 import org.onap.vid.model.SubscriberList;
80 import org.onap.vid.model.probes.ErrorMetadata;
81 import org.onap.vid.model.probes.ExternalComponentStatus;
82 import org.onap.vid.model.probes.HttpRequestMetadata;
83 import org.onap.vid.utils.Logging;
84 import org.onap.vid.utils.Unchecked;
85 import org.springframework.http.HttpMethod;
86 import org.springframework.web.util.UriUtils;
87
88 /**
89
90  * Created by Oren on 7/4/17.
91  */
92 public class AaiClient implements AaiClientInterface {
93
94
95     private static final String QUERY_FORMAT_RESOURCE = "query?format=resource";
96     private static final String SERVICE_SUBSCRIPTIONS_PATH = "/service-subscriptions/service-subscription/";
97     private static final String MODEL_INVARIANT_ID = "&model-invariant-id=";
98     private static final String QUERY_FORMAT_SIMPLE = "query?format=simple";
99     private static final String BUSINESS_CUSTOMER = "/business/customers/customer/";
100     private static final String SERVICE_INSTANCE = "/service-instances/service-instance/";
101     private static final String BUSINESS_CUSTOMERS_CUSTOMER = "business/customers/customer/";
102
103     protected String fromAppId = "VidAaiController";
104
105     private PortDetailsTranslator portDetailsTranslator;
106
107     private final AAIRestInterface restController;
108
109     private final CacheProvider cacheProvider;
110
111     ObjectMapper objectMapper = new ObjectMapper();
112
113     /**
114      * The logger
115      */
116     EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class);
117
118     private static final String GET_SERVICE_MODELS_RESPONSE_BODY = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}";
119
120     @Inject
121     public AaiClient(AAIRestInterface restController, PortDetailsTranslator portDetailsTranslator, CacheProvider cacheProvider) {
122         this.restController = restController;
123         this.portDetailsTranslator = portDetailsTranslator;
124         this.cacheProvider = cacheProvider;
125     }
126
127
128     private static String checkForNull(String local) {
129         if (local != null)
130             return local;
131         else
132             return "";
133
134     }
135
136     @Override
137     public AaiResponse getServicesByOwningEntityId(List<String> owningEntityIds){
138         Response resp = doAaiGet(getUrlFromLIst("business/owning-entities?", "owning-entity-id=", owningEntityIds), false);
139         return processAaiResponse(resp, OwningEntityResponse.class, null);
140     }
141
142     @Override
143     public AaiResponse getServicesByProjectNames(List<String> projectNames){
144         Response resp = doAaiGet(getUrlFromLIst("business/projects?", "project-name=",  projectNames), false);
145         return processAaiResponse(resp, ProjectResponse.class, null);
146     }
147
148     @Override
149     public AaiResponse getServiceModelsByDistributionStatus() {
150         return getFromCache("getServiceModelsByDistributionStatus", this::getServiceModelsByDistributionStatusNonCached,
151                 true, "Failed to get service models by distribution status");
152     }
153
154     private AaiResponse getServiceModelsByDistributionStatusNonCached(boolean propagateExceptions) {
155         GetServiceModelsByDistributionStatusResponse response = typedAaiRest(QUERY_FORMAT_RESOURCE, GetServiceModelsByDistributionStatusResponse.class,
156                 GET_SERVICE_MODELS_RESPONSE_BODY, HttpMethod.PUT, propagateExceptions);
157         return new AaiResponse(response, "", HttpStatus.SC_OK);
158     }
159
160     @Override
161     public AaiResponse getNetworkCollectionDetails(String serviceInstanceId) {
162         Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, "{\"start\": [\"nodes/service-instances/service-instance/" + serviceInstanceId + "\"],\"query\": \"query/network-collection-ByServiceInstance\"}\n", false);
163         AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse = processAaiResponse(resp, AaiGetNetworkCollectionDetailsHelper.class, null, VidObjectMapperType.FASTERXML);
164         return getNetworkCollectionDetailsResponse(aaiResponse);
165     }
166
167     @Override
168     public AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction) {
169         Response resp = doAaiPut(QUERY_FORMAT_RESOURCE,
170                 "{\"start\": [\"cloud-infrastructure/cloud-regions/cloud-region/" + encodePathSegment(cloudOwner) + "/" + encodePathSegment(cloudRegionId) + "\"]," +
171                         "\"query\": \"query/instance-groups-byCloudRegion?type=L3-NETWORK&role=SUB-INTERFACE&function=" + encodePathSegment(networkFunction) + "\"}\n", false);
172         return processAaiResponse(resp, AaiGetInstanceGroupsByCloudRegion.class, null, VidObjectMapperType.FASTERXML);
173     }
174
175     private AaiResponse getNetworkCollectionDetailsResponse(AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse){
176         if(aaiResponse.getHttpCode() == 200) {
177             ObjectMapper om = objectMapper;
178             AaiGetNetworkCollectionDetails aaiGetNetworkCollectionDetails = new AaiGetNetworkCollectionDetails();
179             try {
180                 for (int i = 0; i < aaiResponse.getT().getResults().size(); i++) {
181                     LinkedHashMap<String, Object> temp = ((LinkedHashMap) aaiResponse.getT().getResults().get(i));
182                     if (temp.get("service-instance") != null)
183                         aaiGetNetworkCollectionDetails.getResults().setServiceInstance(om.readValue(om.writeValueAsString(temp.get("service-instance")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance.class));
184                     else if (temp.get("collection") != null)
185                         aaiGetNetworkCollectionDetails.getResults().setCollection(om.readValue(om.writeValueAsString(temp.get("collection")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Collection.class));
186                     else if (temp.get("instance-group") != null)
187                         aaiGetNetworkCollectionDetails.getResults().setInstanceGroup(om.readValue(om.writeValueAsString(temp.get("instance-group")), InstanceGroup.class));
188                     else if (temp.get("l3-network") != null)
189                         aaiGetNetworkCollectionDetails.getResults().getNetworks().add(om.readValue(om.writeValueAsString(temp.get("l3-network")), Network.class));
190                 }
191                 return new AaiResponse(aaiGetNetworkCollectionDetails, null, HttpStatus.SC_OK);
192             }
193             catch (com.fasterxml.jackson.databind.JsonMappingException e) {
194                 logger.error(EELFLoggerDelegate.errorLogger, "AAI response parsing Error",  e);
195                 return new AaiResponse(e.getCause(), "AAI response parsing Error" , HttpStatus.SC_INTERNAL_SERVER_ERROR);
196             }
197             catch (Exception e) {
198                 return new AaiResponse(e.getCause(), "Got " + aaiResponse.getHttpCode() + " from a&ai" , aaiResponse.getHttpCode());
199             }
200         }
201         return aaiResponse;
202     }
203
204     @Override
205     public AaiResponse getPNFData(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion, String equipVendor, String equipModel) {
206         String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
207         String pnfQuery = "query/pnf-fromModel-byRegion?cloudRegionId=" + encodePathSegment(cloudRegion) + "&equipVendor=" + encodePathSegment(equipVendor) + "&equipModel=" + encodePathSegment(equipModel);
208         String payload = "{\"start\":\"" + siQuery + "\",\"query\":\"" + pnfQuery + "\"}";
209         Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
210         return processAaiResponse(resp, AaiGetPnfResponse.class, null);
211     }
212
213
214     @Override
215     public AaiResponse<Pnf> getSpecificPnf(String pnfId) {
216         Response resp = doAaiGet("network/pnfs/pnf/"+pnfId, false);
217         return processAaiResponse(resp, Pnf.class, null);
218     }
219
220
221     public AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId){
222         Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId + "?depth=0", false);
223         return processAaiResponse(resp, AaiGetRelatedInstanceGroupsByVnfId.class , null, null);
224     }
225
226
227     @Override
228     public List<PortDetailsTranslator.PortDetails> getPortMirroringSourcePorts(String configurationID) {
229         String payload = "{\"start\":\"/network/configurations/configuration/" + configurationID + "\",\"query\":\"query/pserver-fromConfiguration\"}";
230         Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
231         resp.bufferEntity(); // avoid later "Entity input stream has already been closed" problems
232         String rawPayload = resp.readEntity(String.class);
233         AaiResponse<CustomQuerySimpleResult> aaiResponse = processAaiResponse(resp, CustomQuerySimpleResult.class, rawPayload);
234         return portDetailsTranslator.extractPortDetails(aaiResponse, rawPayload);
235     }
236
237
238
239     public AaiResponse getServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) {
240         String getServiceInstancePath = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId+ SERVICE_SUBSCRIPTIONS_PATH +serviceType+ SERVICE_INSTANCE +serviceInstanceId;
241         Response resp = doAaiGet(getServiceInstancePath , false);
242         return processAaiResponse(resp, ServiceRelationships.class, null);
243     }
244
245     @Override
246     public AaiResponse getLogicalLink(String link) {
247         Response resp = doAaiGet("network/logical-links/logical-link/" + link , false);
248         return processAaiResponse(resp, LogicalLinkResponse.class, null);
249     }
250
251     @Override
252     public boolean isNodeTypeExistsByName(String name, ResourceType type) {
253         if (isEmpty(name)) {
254             throw new GenericUncheckedException("Empty resource-name provided to searchNodeTypeByName; request is rejected as this will cause full resources listing");
255         }
256
257         URI path = Unchecked.toURI(String.format( // e.g. GET /aai/v$/nodes/vf-modules?vf-module-name={vf-module-name}
258                 "nodes/%s?%s=%s",
259                 type.getAaiFormat(),
260                 type.getNameFilter(),
261                 encodePathSegment(name)
262         ));
263         final ResponseWithRequestInfo responseWithRequestInfo = restController.RestGet(fromAppId, UUID.randomUUID().toString(), path, false, true);
264
265         return isResourceExistByStatusCode(responseWithRequestInfo);
266     }
267
268     public Map<String, Properties> getCloudRegionAndTenantByVnfId(String vnfId) {
269         String start = "/network/generic-vnfs/generic-vnf/" + vnfId;
270         String query = "/query/cloud-region-fromVnf";
271
272         String payload = "{\"start\":[\"" + start + "\"],\"query\":\"" + query + "\"}";
273         CustomQuerySimpleResult result = typedAaiRest(QUERY_FORMAT_SIMPLE, CustomQuerySimpleResult.class, payload, HttpMethod.PUT, false);
274
275         return result.getResults().stream()
276                 .filter(res -> StringUtils.equals(res.getNodeType(), "tenant") ||
277                         StringUtils.equals(res.getNodeType(), "cloud-region"))
278                 .collect(toMap(SimpleResult::getNodeType, SimpleResult::getProperties));
279     }
280
281     private boolean isResourceExistByStatusCode(ResponseWithRequestInfo responseWithRequestInfo) {
282         // 200 - is found
283         // 404 - resource not found
284         Response.Status statusInfo = responseWithRequestInfo.getResponse().getStatusInfo().toEnum();
285         switch (statusInfo) {
286             case OK:
287                 return true;
288             case NOT_FOUND:
289                 return false;
290             default:
291                 throw new GenericUncheckedException("Unexpected response-code (only OK and NOT_FOUND are expected): " +
292                         responseWithRequestInfo.getResponse().getStatusInfo());
293         }
294     }
295
296     @Override
297     public <T> T typedAaiGet(URI uri, Class<T> clz) {
298         return typedAaiRest(uri, clz, null, HttpMethod.GET, false);
299     }
300
301     public <T> T typedAaiRest(String path, Class<T> clz, String payload, HttpMethod method, boolean propagateExceptions) {
302         return typedAaiRest(Unchecked.toURI(path), clz, payload, method, propagateExceptions);
303     }
304
305
306     public <T> T typedAaiRest(URI path, Class<T> clz, String payload, HttpMethod method, boolean propagateExceptions) {
307         ResponseWithRequestInfo responseWithRequestInfo;
308         try {
309             responseWithRequestInfo = restController.doRest(fromAppId, UUID.randomUUID().toString(), path, payload, method, false, propagateExceptions);
310         } catch (Exception e) {
311             responseWithRequestInfo = handleExceptionFromRestCall(propagateExceptions, "doAai"+method.name(), e);
312         }
313
314         final AaiResponseWithRequestInfo<T> aaiResponse = processAaiResponse(responseWithRequestInfo, clz, VidObjectMapperType.FASTERXML, true);
315
316         if (aaiResponse.getAaiResponse().getHttpCode() > 399 || aaiResponse.getAaiResponse().getT() == null) {
317             throw new ExceptionWithRequestInfo(aaiResponse.getHttpMethod(),
318                     aaiResponse.getRequestedUrl(),
319                     aaiResponse.getRawData(),
320                     responseWithRequestInfo.getResponse().getStatus(),
321                     new InvalidAAIResponseException(aaiResponse.getAaiResponse()));
322         }
323
324         return aaiResponse.getAaiResponse().getT();
325     }
326
327
328     private String getUrlFromLIst(String url, String paramKey, List<String> params){
329         int i = 0;
330         for(String param: params){
331             i ++;
332             url = url.concat(paramKey);
333             String encodedParam= param;
334             try {
335                 encodedParam= URLEncoder.encode(param, "UTF-8");
336             } catch (UnsupportedEncodingException e) {
337                 String methodName = "getUrlFromList";
338                 logger.error(EELFLoggerDelegate.errorLogger, methodName + e.toString());
339                 logger.debug(EELFLoggerDelegate.debugLogger, methodName + e.toString());
340             }
341             url = url.concat(encodedParam);
342             if(i != params.size()){
343                 url = url.concat("&");
344             }
345         }
346         return url;
347     }
348
349
350
351     @Override
352     public AaiResponse<SubscriberList> getAllSubscribers() {
353         return getFromCache("getAllSubscribers", this::getAllSubscribersNonCached, true, "Failed to get all subscribers");
354     }
355
356     private <K> AaiResponse getFromCache(String cacheName, Function<K, AaiResponse> function, K argument, String errorMessage) {
357         try {
358             return cacheProvider
359                     .aaiClientCacheFor(cacheName, function)
360                     .get(argument);
361         } catch (ExceptionWithRequestInfo exception) {
362             logger.error(errorMessage, exception);
363             return new AaiResponse(null, exception.getRawData(), exception.getHttpCode());
364         }
365         catch (Exception exception) {
366             logger.error(errorMessage, exception);
367             return new AaiResponse(null, exception.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
368         }
369     }
370
371     private AaiResponse<SubscriberList> getAllSubscribersNonCached(boolean propagateExceptions) {
372         AaiResponse<SubscriberList> aaiResponse = getAllSubscribers(propagateExceptions).getAaiResponse();
373         if (propagateExceptions && (aaiResponse.getT() == null || aaiResponse.getT().customer == null || aaiResponse.getT().customer.isEmpty())) {
374             throw new GenericUncheckedException("Failed to get Subscribers data. The data is null or empty.");
375         } else {
376             return aaiResponse;
377         }
378     }
379
380     AaiResponseWithRequestInfo<SubscriberList> getAllSubscribers(boolean propagateExceptions){
381         String depth = "0";
382         ResponseWithRequestInfo aaiGetResult = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false, propagateExceptions);
383         AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = processAaiResponse(aaiGetResult, SubscriberList.class, propagateExceptions);
384         responseWithRequestInfo.setRequestedUrl(aaiGetResult.getRequestUrl());
385         responseWithRequestInfo.setHttpMethod(aaiGetResult.getRequestHttpMethod());
386         return responseWithRequestInfo;
387     }
388
389
390     @Override
391     public AaiResponse getAllAicZones() {
392         Response resp = doAaiGet("network/zones", false);
393         return processAaiResponse(resp, AicZones.class, null);
394     }
395
396     @Override
397     public AaiResponse getVNFData(String globalSubscriberId, String serviceType) {
398         String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) +"/service-instances\"]," +
399                 "\"query\": \"query/vnf-topology-fromServiceInstance\"}";
400         Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
401         return processAaiResponse(resp, AaiGetVnfResponse.class, null);
402     }
403
404     @Override
405     public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) {
406         String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + SERVICE_INSTANCE + serviceInstanceId + "\"],       \"query\": \"query/vnf-topology-fromServiceInstance\"}";
407         Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
408         return processAaiResponse(resp, AaiGetVnfResponse.class, null);
409     }
410
411     @Override
412     public Response getVersionByInvariantId(List<String> modelInvariantId) {
413         if (modelInvariantId.isEmpty()) {
414             throw new GenericUncheckedException("Zero invariant-ids provided to getVersionByInvariantId; request is rejected as this will cause full models listing");
415         }
416
417         StringBuilder sb = new StringBuilder();
418         for (String id : modelInvariantId){
419             sb.append(MODEL_INVARIANT_ID);
420             sb.append(id);
421
422         }
423         return doAaiGet("service-design-and-creation/models?depth=2"+ sb.toString(), false);
424     }
425
426     @Override
427     public AaiResponse getSubscriberData(String subscriberId) {
428         String depth = "2";
429         AaiResponse subscriberDataResponse;
430         Response resp = doAaiGet(BUSINESS_CUSTOMERS_CUSTOMER + subscriberId + "?depth=" + depth, false);
431         subscriberDataResponse = processAaiResponse(resp, Services.class, null);
432         return subscriberDataResponse;
433     }
434
435     @Override
436     public AaiResponse getServices() {
437         Response resp = doAaiGet("service-design-and-creation/services", false);
438         return processAaiResponse(resp, GetServicesAAIRespone.class, null);
439     }
440
441     @Override
442     public AaiResponse getOperationalEnvironments(String operationalEnvironmentType, String operationalEnvironmentStatus) {
443         String url = "cloud-infrastructure/operational-environments";
444         URIBuilder urlBuilder  = new URIBuilder();
445         if (operationalEnvironmentType != null)
446             urlBuilder.addParameter("operational-environment-type", operationalEnvironmentType);
447         if (operationalEnvironmentStatus != null)
448             urlBuilder.addParameter("operational-environment-status", operationalEnvironmentStatus);
449         url += urlBuilder.toString();
450         Response resp = doAaiGet(url, false);
451         return processAaiResponse(resp, OperationalEnvironmentList.class, null);
452     }
453
454     @Override
455     public AaiResponse getTenants(String globalCustomerId, String serviceType) {
456         if ((globalCustomerId == null || globalCustomerId.isEmpty()) || ((serviceType == null) || (serviceType.isEmpty())) ){
457             return buildAaiResponseForGetTenantsFailure(" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.");
458         }
459         try {
460             return cacheProvider
461                     .aaiClientCacheFor("getTenants", this::getTenantsByKey)
462                     .get(CacheProvider.compileKey(globalCustomerId, serviceType));
463         }
464         catch (ParsingGetTenantsResponseFailure exception) {
465             logger.error("Failed to get tenants ", exception);
466             return buildAaiResponseForGetTenantsFailure(exception.getMessage());
467         }
468     }
469
470     @Override
471     public AaiResponse getNodeTemplateInstances(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion) {
472
473         String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
474         String vnfQuery = "query/queryvnfFromModelbyRegion?cloudRegionId=" + encodePathSegment(cloudRegion);
475         String payload1 = "{\"start\":\"" + siQuery + "\",\"query\":\"" + vnfQuery + "\"}";
476
477         Response resp1 = doAaiPut(QUERY_FORMAT_SIMPLE, payload1, false);
478         AaiResponse aaiResponse1 = processAaiResponse(resp1, AaiGetVnfResponse.class, null);
479         logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse1);
480         return aaiResponse1;
481     }
482
483     @Override
484     public AaiResponse<JsonNode> getCloudRegionAndSourceByPortMirroringConfigurationId(String configurationId) {
485         final String start = "[\"network/configurations/configuration/" + configurationId + "\"]";
486         final String query = "\"query/cloud-region-and-source-FromConfiguration\"";
487         String payload = "{\"start\":" + start + ",\"query\":" + query + "}";
488
489         Response response = doAaiPut("query?format=simple&nodesOnly=true", payload, false);
490         AaiResponse<JsonNode> aaiResponse = processAaiResponse(response, JsonNode.class, null);
491
492         logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse);
493         return aaiResponse;
494     }
495
496     private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, boolean propagateExceptions) {
497         return processAaiResponse(responseWithRequestInfo, classType, VidObjectMapperType.CODEHAUS, propagateExceptions);
498     }
499
500     private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, VidObjectMapperType omType, boolean propagateExceptions) {
501         String responseBody = null;
502         Integer responseHttpCode = null;
503         try {
504             Response response = responseWithRequestInfo.getResponse();
505             responseHttpCode = (response != null) ? response.getStatus() : null;
506             responseBody = (response != null) ? response.readEntity(String.class) : null;
507             AaiResponse<T> processedAaiResponse = processAaiResponse(response, classType, responseBody, omType, propagateExceptions);
508             return new AaiResponseWithRequestInfo<>(responseWithRequestInfo.getRequestHttpMethod(), responseWithRequestInfo.getRequestUrl(), processedAaiResponse,
509                     responseBody);
510         } catch (Exception e) {
511             throw new ExceptionWithRequestInfo(responseWithRequestInfo.getRequestHttpMethod(),
512                     responseWithRequestInfo.getRequestUrl(), responseBody, responseHttpCode, e);
513         }
514     }
515
516     private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody) {
517         return processAaiResponse(resp, classType, responseBody, VidObjectMapperType.CODEHAUS);
518     }
519
520     private <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType) {
521         return processAaiResponse(resp, classType, responseBody, omType, false);
522     }
523
524     private  <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
525         AaiResponse<T> subscriberDataResponse;
526         if (resp == null) {
527             subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
528             logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
529         } else {
530             logger.debug(EELFLoggerDelegate.debugLogger, "getSubscribers() resp=" + resp.getStatusInfo().toString());
531             if (resp.getStatus() != HttpStatus.SC_OK) {
532                 subscriberDataResponse = processFailureResponse(resp,responseBody);
533             } else {
534                 subscriberDataResponse = processOkResponse(resp, classType, responseBody, omType, propagateExceptions);
535             }
536         }
537         return subscriberDataResponse;
538     }
539
540     private AaiResponse processFailureResponse(Response resp, String responseBody) {
541         logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
542         String rawData;
543         if (responseBody != null) {
544             rawData = responseBody;
545         } else {
546             rawData = resp.readEntity(String.class);
547         }
548         return new AaiResponse<>(null, rawData, resp.getStatus());
549     }
550
551     private <T> AaiResponse<T> processOkResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
552         AaiResponse<T> subscriberDataResponse;
553         String finalResponse = null;
554         try {
555             if (responseBody != null) {
556                 finalResponse = responseBody;
557             } else {
558                 finalResponse = resp.readEntity(String.class);
559             }
560
561             if(omType == VidObjectMapperType.CODEHAUS)
562                 subscriberDataResponse = parseCodeHausObject(classType, finalResponse);
563             else
564                 subscriberDataResponse = parseFasterXmlObject(classType, finalResponse);
565
566         } catch(Exception e){
567             if (propagateExceptions) {
568                 throw new GenericUncheckedException(e);
569             } else {
570                 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
571                 logger.error("Failed to parse aai response: \"{}\" to class {}", finalResponse, classType, e);
572             }
573         }
574         return subscriberDataResponse;
575     }
576
577     private <T> AaiResponse<T> parseFasterXmlObject(Class<? extends T> classType, String finalResponse) throws IOException {
578         return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
579     }
580
581     private <T> AaiResponse<T> parseCodeHausObject(Class<? extends T> classType, String finalResponse) throws IOException {
582         return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
583     }
584
585     @Override
586     public Response doAaiGet(String uri, boolean xml) {
587         return doAaiGet(uri, xml, false).getResponse();
588     }
589
590
591     public ResponseWithRequestInfo doAaiGet(String uri, boolean xml, boolean propagateExceptions) {
592         return doAaiGet(Unchecked.toURI(uri), xml, propagateExceptions);
593     }
594
595     public ResponseWithRequestInfo doAaiGet(URI uri, boolean xml, boolean propagateExceptions) {
596         String methodName = "doAaiGet";
597         logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
598
599         ResponseWithRequestInfo resp;
600         try {
601             resp = restController.RestGet(fromAppId, UUID.randomUUID().toString(), uri, xml, propagateExceptions);
602
603         } catch (Exception e) {
604             resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
605         }
606         return resp;
607     }
608
609     @NotNull
610     protected ResponseWithRequestInfo handleExceptionFromRestCall(boolean propagateExceptions, String methodName, Exception e) {
611         ResponseWithRequestInfo resp;
612         if (propagateExceptions) {
613             throw (e instanceof RuntimeException) ? (RuntimeException)e : new GenericUncheckedException(e);
614         } else {
615             final Exception actual =
616                     e instanceof ExceptionWithRequestInfo ? (Exception) e.getCause() : e;
617
618             final String message =
619                     actual instanceof WebApplicationException ? ((WebApplicationException) actual).getResponse().readEntity(String.class) : e.toString();
620
621             //ToDo: change parameter of requestUrl to real url from doRest function
622             resp = new ResponseWithRequestInfo(null, null, org.springframework.http.HttpMethod.GET);
623             logger.info(EELFLoggerDelegate.errorLogger, methodName + message);
624             logger.debug(EELFLoggerDelegate.debugLogger, methodName + message);
625         }
626         return resp;
627     }
628
629     private String parseForTenantsByServiceSubscription(String relatedToKey, String resp) {
630         String tenantList = "";
631
632         try {
633             JSONParser jsonParser = new JSONParser();
634
635             JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
636
637             return parseServiceSubscriptionObjectForTenants(relatedToKey, jsonObject);
638         } catch (Exception ex) {
639             logger.debug(EELFLoggerDelegate.debugLogger, "parseForTenantsByServiceSubscription error while parsing tenants by service subscription", ex);
640         }
641         return tenantList;
642     }
643
644     protected Response doAaiPut(String uri, String payload, boolean xml) {
645         return doAaiPut(uri, payload, xml, false).getResponse();
646     }
647
648     protected ResponseWithRequestInfo doAaiPut(String uri, String payload, boolean xml, boolean propagateExceptions) {
649         String methodName = "doAaiPut";
650         logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
651
652         ResponseWithRequestInfo resp;
653         try {
654
655             resp = restController.RestPut(fromAppId, uri, payload, xml, propagateExceptions);
656
657         } catch (Exception e) {
658             resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
659         }
660         return resp;
661     }
662
663
664     private String parseServiceSubscriptionObjectForTenants(String relatedToKey, JSONObject jsonObject) {
665         JSONArray tenantArray = new JSONArray();
666         boolean bconvert = false;
667         try {
668             JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");
669             if (relationShipListsObj != null) {
670                 JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
671                 for (Object innerObj : defaultIfNull(rShipArray, emptyList())) {
672                     if (innerObj != null) {
673                         bconvert = parseTenant(relatedToKey, tenantArray, bconvert, (JSONObject) innerObj);
674                     }
675                 }
676             }
677         } catch (NullPointerException ex) {
678             logger.debug(EELFLoggerDelegate.debugLogger, "parseServiceSubscriptionObjectForTenants. error while parsing service subscription object for tenants", ex);
679         }
680
681         if (bconvert)
682             return tenantArray.toJSONString();
683         else
684             return "";
685
686     }
687
688     private static boolean parseTenant(String relatedToKey, JSONArray tenantArray, boolean bconvert, JSONObject inner1Obj) {
689         String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
690         if (relatedTo.equalsIgnoreCase(relatedToKey)) {
691             JSONObject tenantNewObj = new JSONObject();
692
693             String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
694             tenantNewObj.put("link", relatedLink);
695
696             JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
697             for (Object innerObj : defaultIfNull(rDataArray, emptyList())) {
698                 parseRelationShip(tenantNewObj, (JSONObject) innerObj);
699             }
700
701             JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
702             for (Object innerObj : defaultIfNull(relatedTPropArray, emptyList())) {
703                 parseRelatedTProp(tenantNewObj, (JSONObject) innerObj);
704             }
705             bconvert = true;
706             tenantArray.add(tenantNewObj);
707         }
708         return bconvert;
709     }
710
711     private static void parseRelatedTProp(JSONObject tenantNewObj, JSONObject innerObj) {
712         if (innerObj == null)
713             return;
714
715         String propKey = checkForNull((String) innerObj.get("property-key"));
716         String propVal = checkForNull((String) innerObj.get("property-value"));
717         if (equalsIgnoreCase(propKey, "tenant.tenant-name")) {
718             tenantNewObj.put("tenantName", propVal);
719         }
720     }
721
722     private static void parseRelationShip(JSONObject tenantNewObj, JSONObject inner2Obj) {
723         if (inner2Obj == null)
724             return;
725
726         String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
727         String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
728         if (equalsIgnoreCase(rShipKey, "cloud-region.cloud-owner")) {
729             tenantNewObj.put("cloudOwner", rShipVal);
730         } else if (equalsIgnoreCase(rShipKey, "cloud-region.cloud-region-id")) {
731             tenantNewObj.put("cloudRegionID", rShipVal);
732         } else if (equalsIgnoreCase(rShipKey, "tenant.tenant-id")) {
733             tenantNewObj.put("tenantID", rShipVal);
734         }
735     }
736
737     private static String encodePathSegment(String segmentToEncode) {
738         try {
739             return UriUtils.encodePathSegment(segmentToEncode, "UTF-8");
740         } catch (UnsupportedEncodingException e) {
741             throw new GenericUncheckedException("URI encoding failed unexpectedly", e);
742         }
743     }
744
745     @Override
746     public ExternalComponentStatus probeAaiGetAllSubscribers(){
747         long startTime = System.currentTimeMillis();
748         try {
749             AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = getAllSubscribers(true);
750             AaiResponse<SubscriberList> aaiResponse = responseWithRequestInfo.getAaiResponse();
751             long duration = System.currentTimeMillis() - startTime;
752
753             SubscriberList subscribersList = (aaiResponse != null) ? aaiResponse.getT() : null;
754             boolean isAvailable = subscribersList != null && subscribersList.customer != null && !subscribersList.customer.isEmpty();
755
756             HttpRequestMetadata metadata = new HttpRequestMetadata(
757                     responseWithRequestInfo.getHttpMethod(),
758                     (aaiResponse != null) ? aaiResponse.getHttpCode() : 0,
759                     responseWithRequestInfo.getRequestedUrl(),
760                     responseWithRequestInfo.getRawData(),
761                     isAvailable ? "OK" : "No subscriber received",
762                     duration
763             );
764             return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, metadata);
765
766         } catch (ExceptionWithRequestInfo e) {
767             long duration = System.currentTimeMillis() - startTime;
768             return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
769                     new HttpRequestMetadata(e, duration));
770         } catch (Exception e) {
771             long duration = System.currentTimeMillis() - startTime;
772             return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
773                     new ErrorMetadata(Logging.exceptionToDescription(e), duration));
774         }
775     }
776
777     @Override
778     public String getCloudOwnerByCloudRegionId(String cloudRegionId) {
779         return cacheProvider
780                 .aaiClientCacheFor("getCloudOwnerByCloudRegionId", this::getCloudOwnerByCloudRegionIdNonCached)
781                 .get(cloudRegionId);
782     }
783
784
785     @Override
786     public GetTenantsResponse getHomingDataByVfModule(String vnfInstanceId, String vfModuleId) {
787
788         if (isEmpty(vnfInstanceId)|| isEmpty(vfModuleId)){
789             throw new GenericUncheckedException("Failed to retrieve homing data associated to vfModule from A&AI, VNF InstanceId or VF Module Id is missing.");
790         }
791         Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId +"/vf-modules/vf-module/"+ vfModuleId, false);
792         String responseAsString = parseForTenantsByServiceSubscription("vserver",resp.readEntity(String.class));
793         if (isEmpty(responseAsString)){
794             throw new GenericUncheckedException( String.format("A&AI has no homing data associated to vfModule '%s' of vnf '%s'", vfModuleId, vnfInstanceId));
795         }
796         else {
797             AaiResponse aaiResponse = processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
798             return ((GetTenantsResponse[])aaiResponse.getT())[0];
799         }
800     }
801
802     @Override
803     public void resetCache(String cacheName) {
804         cacheProvider.resetCache(cacheName);
805     }
806
807     String getCloudOwnerByCloudRegionIdNonCached(String cloudRegionId) {
808         String uri = "cloud-infrastructure/cloud-regions?cloud-region-id=" + encodePathSegment(cloudRegionId);
809
810         final CloudRegion.Collection cloudRegionCollection =
811                 typedAaiGet(Unchecked.toURI(uri), CloudRegion.Collection.class);
812
813         return cloudRegionCollection
814                 .getCloudRegions().stream()
815                 .map(CloudRegion::getCloudOwner)
816                 // from here we assure that the cloud owner is given, and not null
817                 // and non-empty, and that if more than one cloud-owner is given -
818                 // it is only a single value.
819                 // exception is thrown if none or more than a single values are
820                 // given.
821                 .filter(StringUtils::isNotEmpty)
822                 .distinct()
823                 .reduce((a, b) -> {
824                     // will be invoked only if distinct() leaves more than a single element
825                     throw new GenericUncheckedException("Conflicting cloud-owner found for " + cloudRegionId + ": '" + a + "' / '" + b + "'");
826                 })
827                 .orElseThrow(() -> new GenericUncheckedException("No cloud-owner found for " + cloudRegionId));
828     }
829
830     private AaiResponse getTenantsByKey(String key) {
831         String[] args = CacheProvider.decompileKey(key);
832         String globalCustomerId = safeGetFromArray(args, 0);
833         String serviceType = safeGetFromArray(args, 1);
834         return getTenantsNonCached(globalCustomerId, serviceType);
835     }
836
837     AaiResponse getTenantsNonCached(String globalCustomerId, String serviceType) {
838         String url = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType;
839
840         Response resp = doAaiGet(url, false);
841         String responseAsString = parseForTenantsByServiceSubscription("tenant",resp.readEntity(String.class));
842         if (isEmpty(responseAsString)){
843            throw new ParsingGetTenantsResponseFailure(String.format("A&AI has no LCP Region & Tenants associated to subscriber '%s' and service type '%s'", globalCustomerId, serviceType));
844         }
845         else {
846             return processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
847         }
848     }
849
850     public static class ParsingGetTenantsResponseFailure extends GenericUncheckedException {
851
852         public ParsingGetTenantsResponseFailure(String message) {
853             super(message);
854         }
855     }
856
857     @NotNull
858     private AaiResponse<String> buildAaiResponseForGetTenantsFailure(String errorText) {
859         return new AaiResponse<>(null, String.format("{\"statusText\":\"%s\"}", errorText), HttpStatus.SC_INTERNAL_SERVER_ERROR);
860     }
861
862     private static String safeGetFromArray(String[] array, int i) {
863         if (i < 0 || i >= array.length) {
864             return null;
865         } else {
866             return array[i];
867         }
868     }
869 }