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