1 package org.onap.vid.aai;
3 import com.fasterxml.jackson.databind.JsonNode;
4 import com.fasterxml.jackson.databind.ObjectMapper;
5 import org.apache.commons.lang3.StringUtils;
6 import org.apache.http.HttpStatus;
7 import org.apache.http.client.utils.URIBuilder;
8 import org.jetbrains.annotations.NotNull;
9 import org.json.simple.JSONArray;
10 import org.json.simple.JSONObject;
11 import org.json.simple.parser.JSONParser;
12 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
13 import org.onap.vid.aai.exceptions.InvalidAAIResponseException;
14 import org.onap.vid.aai.model.AaiGetAicZone.AicZones;
15 import org.onap.vid.aai.model.*;
16 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.*;
17 import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
18 import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
19 import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone;
20 import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
21 import org.onap.vid.aai.util.AAIRestInterface;
22 import org.onap.vid.aai.util.CacheProvider;
23 import org.onap.vid.aai.util.VidObjectMapperType;
24 import org.onap.vid.exceptions.GenericUncheckedException;
25 import org.onap.vid.model.SubscriberList;
26 import org.onap.vid.model.probes.ErrorMetadata;
27 import org.onap.vid.model.probes.ExternalComponentStatus;
28 import org.onap.vid.model.probes.HttpRequestMetadata;
29 import org.onap.vid.utils.Logging;
30 import org.onap.vid.utils.Unchecked;
31 import org.springframework.http.HttpMethod;
32 import org.springframework.web.util.UriUtils;
34 import javax.inject.Inject;
35 import javax.ws.rs.WebApplicationException;
36 import javax.ws.rs.core.Response;
37 import java.io.IOException;
38 import java.io.UnsupportedEncodingException;
40 import java.net.URLEncoder;
41 import java.util.LinkedHashMap;
42 import java.util.List;
44 import java.util.UUID;
45 import java.util.function.Function;
47 import static java.util.Collections.emptyList;
48 import static java.util.stream.Collectors.toMap;
49 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
53 * Created by Oren on 7/4/17.
55 public class AaiClient implements AaiClientInterface {
58 private static final String QUERY_FORMAT_RESOURCE = "query?format=resource";
59 private static final String SERVICE_SUBSCRIPTIONS_PATH = "/service-subscriptions/service-subscription/";
60 private static final String MODEL_INVARIANT_ID = "&model-invariant-id=";
61 private static final String QUERY_FORMAT_SIMPLE = "query?format=simple";
62 private static final String BUSINESS_CUSTOMER = "/business/customers/customer/";
63 private static final String SERVICE_INSTANCE = "/service-instances/service-instance/";
64 private static final String BUSINESS_CUSTOMERS_CUSTOMER = "business/customers/customer/";
66 protected String fromAppId = "VidAaiController";
68 private PortDetailsTranslator portDetailsTranslator;
70 private final AAIRestInterface restController;
72 private final CacheProvider cacheProvider;
74 ObjectMapper objectMapper = new ObjectMapper();
79 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class);
81 private static final String GET_SERVICE_MODELS_RESPONSE_BODY = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}";
84 public AaiClient(AAIRestInterface restController, PortDetailsTranslator portDetailsTranslator, CacheProvider cacheProvider) {
85 this.restController = restController;
86 this.portDetailsTranslator = portDetailsTranslator;
87 this.cacheProvider = cacheProvider;
91 private static String checkForNull(String local) {
100 public AaiResponse getServicesByOwningEntityId(List<String> owningEntityIds){
101 Response resp = doAaiGet(getUrlFromLIst("business/owning-entities?", "owning-entity-id=", owningEntityIds), false);
102 return processAaiResponse(resp, OwningEntityResponse.class, null);
106 public AaiResponse getServicesByProjectNames(List<String> projectNames){
107 Response resp = doAaiGet(getUrlFromLIst("business/projects?", "project-name=", projectNames), false);
108 return processAaiResponse(resp, ProjectResponse.class, null);
112 public AaiResponse getServiceModelsByDistributionStatus() {
113 return getFromCache("getServiceModelsByDistributionStatus", this::getServiceModelsByDistributionStatusNonCached,
114 true, "Failed to get service models by distribution status");
117 private AaiResponse getServiceModelsByDistributionStatusNonCached(boolean propagateExceptions) {
118 GetServiceModelsByDistributionStatusResponse response = typedAaiRest(QUERY_FORMAT_RESOURCE, GetServiceModelsByDistributionStatusResponse.class,
119 GET_SERVICE_MODELS_RESPONSE_BODY, HttpMethod.PUT, propagateExceptions);
120 return new AaiResponse(response, "", HttpStatus.SC_OK);
124 public AaiResponse getNetworkCollectionDetails(String serviceInstanceId) {
125 Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, "{\"start\": [\"nodes/service-instances/service-instance/" + serviceInstanceId + "\"],\"query\": \"query/network-collection-ByServiceInstance\"}\n", false);
126 AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse = processAaiResponse(resp, AaiGetNetworkCollectionDetailsHelper.class, null, VidObjectMapperType.FASTERXML);
127 return getNetworkCollectionDetailsResponse(aaiResponse);
131 public AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction) {
132 Response resp = doAaiPut(QUERY_FORMAT_RESOURCE,
133 "{\"start\": [\"cloud-infrastructure/cloud-regions/cloud-region/" + encodePathSegment(cloudOwner) + "/" + encodePathSegment(cloudRegionId) + "\"]," +
134 "\"query\": \"query/instance-groups-byCloudRegion?type=L3-NETWORK&role=SUB-INTERFACE&function=" + encodePathSegment(networkFunction) + "\"}\n", false);
135 return processAaiResponse(resp, AaiGetInstanceGroupsByCloudRegion.class, null, VidObjectMapperType.FASTERXML);
138 private AaiResponse getNetworkCollectionDetailsResponse(AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse){
139 if(aaiResponse.getHttpCode() == 200) {
140 ObjectMapper om = objectMapper;
141 AaiGetNetworkCollectionDetails aaiGetNetworkCollectionDetails = new AaiGetNetworkCollectionDetails();
143 for (int i = 0; i < aaiResponse.getT().getResults().size(); i++) {
144 LinkedHashMap<String, Object> temp = ((LinkedHashMap) aaiResponse.getT().getResults().get(i));
145 if (temp.get("service-instance") != null)
146 aaiGetNetworkCollectionDetails.getResults().setServiceInstance(om.readValue(om.writeValueAsString(temp.get("service-instance")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance.class));
147 else if (temp.get("collection") != null)
148 aaiGetNetworkCollectionDetails.getResults().setCollection(om.readValue(om.writeValueAsString(temp.get("collection")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Collection.class));
149 else if (temp.get("instance-group") != null)
150 aaiGetNetworkCollectionDetails.getResults().setInstanceGroup(om.readValue(om.writeValueAsString(temp.get("instance-group")), InstanceGroup.class));
151 else if (temp.get("l3-network") != null)
152 aaiGetNetworkCollectionDetails.getResults().getNetworks().add(om.readValue(om.writeValueAsString(temp.get("l3-network")), Network.class));
154 return new AaiResponse(aaiGetNetworkCollectionDetails, null, HttpStatus.SC_OK);
156 catch (com.fasterxml.jackson.databind.JsonMappingException e) {
157 logger.error(EELFLoggerDelegate.errorLogger, "AAI response parsing Error", e);
158 return new AaiResponse(e.getCause(), "AAI response parsing Error" , HttpStatus.SC_INTERNAL_SERVER_ERROR);
160 catch (Exception e) {
161 return new AaiResponse(e.getCause(), "Got " + aaiResponse.getHttpCode() + " from a&ai" , aaiResponse.getHttpCode());
168 public AaiResponse getPNFData(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion, String equipVendor, String equipModel) {
169 String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
170 String pnfQuery = "query/pnf-fromModel-byRegion?cloudRegionId=" + encodePathSegment(cloudRegion) + "&equipVendor=" + encodePathSegment(equipVendor) + "&equipModel=" + encodePathSegment(equipModel);
171 String payload = "{\"start\":\"" + siQuery + "\",\"query\":\"" + pnfQuery + "\"}";
172 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
173 return processAaiResponse(resp, AaiGetPnfResponse.class, null);
178 public AaiResponse<Pnf> getSpecificPnf(String pnfId) {
179 Response resp = doAaiGet("network/pnfs/pnf/"+pnfId, false);
180 return processAaiResponse(resp, Pnf.class, null);
184 public AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId){
185 Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId + "?depth=0", false);
186 return processAaiResponse(resp, AaiGetRelatedInstanceGroupsByVnfId.class , null, null);
191 public List<PortDetailsTranslator.PortDetails> getPortMirroringSourcePorts(String configurationID) {
192 String payload = "{\"start\":\"/network/configurations/configuration/" + configurationID + "\",\"query\":\"query/pserver-fromConfiguration\"}";
193 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
194 resp.bufferEntity(); // avoid later "Entity input stream has already been closed" problems
195 String rawPayload = resp.readEntity(String.class);
196 AaiResponse<CustomQuerySimpleResult> aaiResponse = processAaiResponse(resp, CustomQuerySimpleResult.class, rawPayload);
197 return portDetailsTranslator.extractPortDetails(aaiResponse, rawPayload);
202 public AaiResponse getServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) {
203 String getServiceInstancePath = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId+ SERVICE_SUBSCRIPTIONS_PATH +serviceType+ SERVICE_INSTANCE +serviceInstanceId;
204 Response resp = doAaiGet(getServiceInstancePath , false);
205 return processAaiResponse(resp, ServiceRelationships.class, null);
209 public AaiResponse getLogicalLink(String link) {
210 Response resp = doAaiGet("network/logical-links/logical-link/" + link , false);
211 return processAaiResponse(resp, LogicalLinkResponse.class, null);
215 public boolean isNodeTypeExistsByName(String name, ResourceType type) {
216 if (StringUtils.isEmpty(name)) {
217 throw new GenericUncheckedException("Empty resource-name provided to searchNodeTypeByName; request is rejected as this will cause full resources listing");
220 URI path = Unchecked.toURI(String.format( // e.g. GET /aai/v$/nodes/vf-modules?vf-module-name={vf-module-name}
223 type.getNameFilter(),
224 encodePathSegment(name)
226 final ResponseWithRequestInfo responseWithRequestInfo = restController.RestGet(fromAppId, UUID.randomUUID().toString(), path, false, true);
228 return isResourceExistByStatusCode(responseWithRequestInfo);
231 public Map<String, Properties> getCloudRegionAndTenantByVnfId(String vnfId) {
232 String start = "/network/generic-vnfs/generic-vnf/" + vnfId;
233 String query = "/query/cloud-region-fromVnf";
235 String payload = "{\"start\":[\"" + start + "\"],\"query\":\"" + query + "\"}";
236 CustomQuerySimpleResult result = typedAaiRest(QUERY_FORMAT_SIMPLE, CustomQuerySimpleResult.class, payload, HttpMethod.PUT, false);
238 return result.getResults().stream()
239 .filter(res -> StringUtils.equals(res.getNodeType(), "tenant") ||
240 StringUtils.equals(res.getNodeType(), "cloud-region"))
241 .collect(toMap(SimpleResult::getNodeType, SimpleResult::getProperties));
244 private boolean isResourceExistByStatusCode(ResponseWithRequestInfo responseWithRequestInfo) {
246 // 404 - resource not found
247 Response.Status statusInfo = responseWithRequestInfo.getResponse().getStatusInfo().toEnum();
248 switch (statusInfo) {
254 throw new GenericUncheckedException("Unexpected response-code (only OK and NOT_FOUND are expected): " +
255 responseWithRequestInfo.getResponse().getStatusInfo());
260 public <T> T typedAaiGet(URI uri, Class<T> clz) {
261 return typedAaiRest(uri, clz, null, HttpMethod.GET, false);
264 public <T> T typedAaiRest(String path, Class<T> clz, String payload, HttpMethod method, boolean propagateExceptions) {
265 return typedAaiRest(Unchecked.toURI(path), clz, payload, method, propagateExceptions);
269 public <T> T typedAaiRest(URI path, Class<T> clz, String payload, HttpMethod method, boolean propagateExceptions) {
270 ResponseWithRequestInfo responseWithRequestInfo;
272 responseWithRequestInfo = restController.doRest(fromAppId, UUID.randomUUID().toString(), path, payload, method, false, propagateExceptions);
273 } catch (Exception e) {
274 responseWithRequestInfo = handleExceptionFromRestCall(propagateExceptions, "doAai"+method.name(), e);
277 final AaiResponseWithRequestInfo<T> aaiResponse = processAaiResponse(responseWithRequestInfo, clz, VidObjectMapperType.FASTERXML, true);
279 if (aaiResponse.getAaiResponse().getHttpCode() > 399 || aaiResponse.getAaiResponse().getT() == null) {
280 throw new ExceptionWithRequestInfo(aaiResponse.getHttpMethod(),
281 aaiResponse.getRequestedUrl(),
282 aaiResponse.getRawData(),
283 responseWithRequestInfo.getResponse().getStatus(),
284 new InvalidAAIResponseException(aaiResponse.getAaiResponse()));
287 return aaiResponse.getAaiResponse().getT();
291 private String getUrlFromLIst(String url, String paramKey, List<String> params){
293 for(String param: params){
295 url = url.concat(paramKey);
296 String encodedParam= param;
298 encodedParam= URLEncoder.encode(param, "UTF-8");
299 } catch (UnsupportedEncodingException e) {
300 String methodName = "getUrlFromList";
301 logger.error(EELFLoggerDelegate.errorLogger, methodName + e.toString());
302 logger.debug(EELFLoggerDelegate.debugLogger, methodName + e.toString());
304 url = url.concat(encodedParam);
305 if(i != params.size()){
306 url = url.concat("&");
315 public AaiResponse<SubscriberList> getAllSubscribers() {
316 return getFromCache("getAllSubscribers", this::getAllSubscribersNonCached, true, "Failed to get all subscribers");
319 private <K> AaiResponse getFromCache(String cacheName, Function<K, AaiResponse> function, K argument, String errorMessage) {
322 .aaiClientCacheFor(cacheName, function)
324 } catch (ExceptionWithRequestInfo exception) {
325 logger.error(errorMessage, exception);
326 return new AaiResponse(null, exception.getRawData(), exception.getHttpCode());
328 catch (Exception exception) {
329 logger.error(errorMessage, exception);
330 return new AaiResponse(null, exception.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
334 private AaiResponse<SubscriberList> getAllSubscribersNonCached(boolean propagateExceptions) {
335 AaiResponse<SubscriberList> aaiResponse = getAllSubscribers(propagateExceptions).getAaiResponse();
336 if (propagateExceptions && (aaiResponse.getT() == null || aaiResponse.getT().customer == null || aaiResponse.getT().customer.isEmpty())) {
337 throw new GenericUncheckedException("Failed to get Subscribers data. The data is null or empty.");
343 AaiResponseWithRequestInfo<SubscriberList> getAllSubscribers(boolean propagateExceptions){
345 ResponseWithRequestInfo aaiGetResult = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false, propagateExceptions);
346 AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = processAaiResponse(aaiGetResult, SubscriberList.class, propagateExceptions);
347 responseWithRequestInfo.setRequestedUrl(aaiGetResult.getRequestUrl());
348 responseWithRequestInfo.setHttpMethod(aaiGetResult.getRequestHttpMethod());
349 return responseWithRequestInfo;
354 public AaiResponse getAllAicZones() {
355 Response resp = doAaiGet("network/zones", false);
356 return processAaiResponse(resp, AicZones.class, null);
360 public AaiResponse getVNFData(String globalSubscriberId, String serviceType) {
361 String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) +"/service-instances\"]," +
362 "\"query\": \"query/vnf-topology-fromServiceInstance\"}";
363 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
364 return processAaiResponse(resp, AaiGetVnfResponse.class, null);
368 public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) {
369 String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + SERVICE_INSTANCE + serviceInstanceId + "\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}";
370 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
371 return processAaiResponse(resp, AaiGetVnfResponse.class, null);
375 public Response getVersionByInvariantId(List<String> modelInvariantId) {
376 if (modelInvariantId.isEmpty()) {
377 throw new GenericUncheckedException("Zero invariant-ids provided to getVersionByInvariantId; request is rejected as this will cause full models listing");
380 StringBuilder sb = new StringBuilder();
381 for (String id : modelInvariantId){
382 sb.append(MODEL_INVARIANT_ID);
386 return doAaiGet("service-design-and-creation/models?depth=2"+ sb.toString(), false);
390 public AaiResponse getSubscriberData(String subscriberId) {
392 AaiResponse subscriberDataResponse;
393 Response resp = doAaiGet(BUSINESS_CUSTOMERS_CUSTOMER + subscriberId + "?depth=" + depth, false);
394 subscriberDataResponse = processAaiResponse(resp, Services.class, null);
395 return subscriberDataResponse;
399 public AaiResponse getServices() {
400 Response resp = doAaiGet("service-design-and-creation/services", false);
401 return processAaiResponse(resp, GetServicesAAIRespone.class, null);
405 public AaiResponse getOperationalEnvironments(String operationalEnvironmentType, String operationalEnvironmentStatus) {
406 String url = "cloud-infrastructure/operational-environments";
407 URIBuilder urlBuilder = new URIBuilder();
408 if (operationalEnvironmentType != null)
409 urlBuilder.addParameter("operational-environment-type", operationalEnvironmentType);
410 if (operationalEnvironmentStatus != null)
411 urlBuilder.addParameter("operational-environment-status", operationalEnvironmentStatus);
412 url += urlBuilder.toString();
413 Response resp = doAaiGet(url, false);
414 return processAaiResponse(resp, OperationalEnvironmentList.class, null);
418 public AaiResponse getTenants(String globalCustomerId, String serviceType) {
419 if ((globalCustomerId == null || globalCustomerId.isEmpty()) || ((serviceType == null) || (serviceType.isEmpty())) ){
420 return buildAaiResponseForGetTenantsFailure(" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.");
424 .aaiClientCacheFor("getTenants", this::getTenantsByKey)
425 .get(CacheProvider.compileKey(globalCustomerId, serviceType));
427 catch (ParsingGetTenantsResponseFailure exception) {
428 logger.error("Failed to get tenants ", exception);
429 return buildAaiResponseForGetTenantsFailure(exception.getMessage());
434 public AaiResponse getNodeTemplateInstances(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion) {
436 String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
437 String vnfQuery = "query/queryvnfFromModelbyRegion?cloudRegionId=" + encodePathSegment(cloudRegion);
438 String payload1 = "{\"start\":\"" + siQuery + "\",\"query\":\"" + vnfQuery + "\"}";
440 Response resp1 = doAaiPut(QUERY_FORMAT_SIMPLE, payload1, false);
441 AaiResponse aaiResponse1 = processAaiResponse(resp1, AaiGetVnfResponse.class, null);
442 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse1);
447 public AaiResponse<JsonNode> getCloudRegionAndSourceByPortMirroringConfigurationId(String configurationId) {
448 final String start = "[\"network/configurations/configuration/" + configurationId + "\"]";
449 final String query = "\"query/cloud-region-and-source-FromConfiguration\"";
450 String payload = "{\"start\":" + start + ",\"query\":" + query + "}";
452 Response response = doAaiPut("query?format=simple&nodesOnly=true", payload, false);
453 AaiResponse<JsonNode> aaiResponse = processAaiResponse(response, JsonNode.class, null);
455 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse);
459 private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, boolean propagateExceptions) {
460 return processAaiResponse(responseWithRequestInfo, classType, VidObjectMapperType.CODEHAUS, propagateExceptions);
463 private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, VidObjectMapperType omType, boolean propagateExceptions) {
464 String responseBody = null;
465 Integer responseHttpCode = null;
467 Response response = responseWithRequestInfo.getResponse();
468 responseHttpCode = (response != null) ? response.getStatus() : null;
469 responseBody = (response != null) ? response.readEntity(String.class) : null;
470 AaiResponse<T> processedAaiResponse = processAaiResponse(response, classType, responseBody, omType, propagateExceptions);
471 return new AaiResponseWithRequestInfo<>(responseWithRequestInfo.getRequestHttpMethod(), responseWithRequestInfo.getRequestUrl(), processedAaiResponse,
473 } catch (Exception e) {
474 throw new ExceptionWithRequestInfo(responseWithRequestInfo.getRequestHttpMethod(),
475 responseWithRequestInfo.getRequestUrl(), responseBody, responseHttpCode, e);
479 private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody) {
480 return processAaiResponse(resp, classType, responseBody, VidObjectMapperType.CODEHAUS);
483 private <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType) {
484 return processAaiResponse(resp, classType, responseBody, omType, false);
487 private <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
488 AaiResponse<T> subscriberDataResponse;
490 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
491 logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
493 logger.debug(EELFLoggerDelegate.debugLogger, "getSubscribers() resp=" + resp.getStatusInfo().toString());
494 if (resp.getStatus() != HttpStatus.SC_OK) {
495 subscriberDataResponse = processFailureResponse(resp,responseBody);
497 subscriberDataResponse = processOkResponse(resp, classType, responseBody, omType, propagateExceptions);
500 return subscriberDataResponse;
503 private AaiResponse processFailureResponse(Response resp, String responseBody) {
504 logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
506 if (responseBody != null) {
507 rawData = responseBody;
509 rawData = resp.readEntity(String.class);
511 return new AaiResponse<>(null, rawData, resp.getStatus());
514 private <T> AaiResponse<T> processOkResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
515 AaiResponse<T> subscriberDataResponse;
516 String finalResponse = null;
518 if (responseBody != null) {
519 finalResponse = responseBody;
521 finalResponse = resp.readEntity(String.class);
524 if(omType == VidObjectMapperType.CODEHAUS)
525 subscriberDataResponse = parseCodeHausObject(classType, finalResponse);
527 subscriberDataResponse = parseFasterXmlObject(classType, finalResponse);
529 } catch(Exception e){
530 if (propagateExceptions) {
531 throw new GenericUncheckedException(e);
533 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
534 logger.error("Failed to parse aai response: \"{}\" to class {}", finalResponse, classType, e);
537 return subscriberDataResponse;
540 private <T> AaiResponse<T> parseFasterXmlObject(Class<? extends T> classType, String finalResponse) throws IOException {
541 return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
544 private <T> AaiResponse<T> parseCodeHausObject(Class<? extends T> classType, String finalResponse) throws IOException {
545 return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
549 public Response doAaiGet(String uri, boolean xml) {
550 return doAaiGet(uri, xml, false).getResponse();
554 public ResponseWithRequestInfo doAaiGet(String uri, boolean xml, boolean propagateExceptions) {
555 return doAaiGet(Unchecked.toURI(uri), xml, propagateExceptions);
558 public ResponseWithRequestInfo doAaiGet(URI uri, boolean xml, boolean propagateExceptions) {
559 String methodName = "doAaiGet";
560 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
562 ResponseWithRequestInfo resp;
564 resp = restController.RestGet(fromAppId, UUID.randomUUID().toString(), uri, xml, propagateExceptions);
566 } catch (Exception e) {
567 resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
573 protected ResponseWithRequestInfo handleExceptionFromRestCall(boolean propagateExceptions, String methodName, Exception e) {
574 ResponseWithRequestInfo resp;
575 if (propagateExceptions) {
576 throw (e instanceof RuntimeException) ? (RuntimeException)e : new GenericUncheckedException(e);
578 final Exception actual =
579 e instanceof ExceptionWithRequestInfo ? (Exception) e.getCause() : e;
581 final String message =
582 actual instanceof WebApplicationException ? ((WebApplicationException) actual).getResponse().readEntity(String.class) : e.toString();
584 //ToDo: change parameter of requestUrl to real url from doRest function
585 resp = new ResponseWithRequestInfo(null, null, org.springframework.http.HttpMethod.GET);
586 logger.info(EELFLoggerDelegate.errorLogger, methodName + message);
587 logger.debug(EELFLoggerDelegate.debugLogger, methodName + message);
592 private String parseForTenantsByServiceSubscription(String relatedToKey, String resp) {
593 String tenantList = "";
596 JSONParser jsonParser = new JSONParser();
598 JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
600 return parseServiceSubscriptionObjectForTenants(relatedToKey, jsonObject);
601 } catch (Exception ex) {
602 logger.debug(EELFLoggerDelegate.debugLogger, "parseForTenantsByServiceSubscription error while parsing tenants by service subscription", ex);
607 protected Response doAaiPut(String uri, String payload, boolean xml) {
608 return doAaiPut(uri, payload, xml, false).getResponse();
611 protected ResponseWithRequestInfo doAaiPut(String uri, String payload, boolean xml, boolean propagateExceptions) {
612 String methodName = "doAaiPut";
613 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
615 ResponseWithRequestInfo resp;
618 resp = restController.RestPut(fromAppId, uri, payload, xml, propagateExceptions);
620 } catch (Exception e) {
621 resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
627 private String parseServiceSubscriptionObjectForTenants(String relatedToKey, JSONObject jsonObject) {
628 JSONArray tenantArray = new JSONArray();
629 boolean bconvert = false;
631 JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");
632 if (relationShipListsObj != null) {
633 JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
634 for (Object innerObj : defaultIfNull(rShipArray, emptyList())) {
635 if (innerObj != null) {
636 bconvert = parseTenant(relatedToKey, tenantArray, bconvert, (JSONObject) innerObj);
640 } catch (NullPointerException ex) {
641 logger.debug(EELFLoggerDelegate.debugLogger, "parseServiceSubscriptionObjectForTenants. error while parsing service subscription object for tenants", ex);
645 return tenantArray.toJSONString();
651 private static boolean parseTenant(String relatedToKey, JSONArray tenantArray, boolean bconvert, JSONObject inner1Obj) {
652 String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
653 if (relatedTo.equalsIgnoreCase(relatedToKey)) {
654 JSONObject tenantNewObj = new JSONObject();
656 String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
657 tenantNewObj.put("link", relatedLink);
659 JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
660 for (Object innerObj : defaultIfNull(rDataArray, emptyList())) {
661 parseRelationShip(tenantNewObj, (JSONObject) innerObj);
664 JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
665 for (Object innerObj : defaultIfNull(relatedTPropArray, emptyList())) {
666 parseRelatedTProp(tenantNewObj, (JSONObject) innerObj);
669 tenantArray.add(tenantNewObj);
674 private static void parseRelatedTProp(JSONObject tenantNewObj, JSONObject innerObj) {
675 if (innerObj == null)
678 String propKey = checkForNull((String) innerObj.get("property-key"));
679 String propVal = checkForNull((String) innerObj.get("property-value"));
680 if (propKey.equalsIgnoreCase("tenant.tenant-name")) {
681 tenantNewObj.put("tenantName", propVal);
685 private static void parseRelationShip(JSONObject tenantNewObj, JSONObject inner2Obj) {
686 if (inner2Obj == null)
689 String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
690 String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
691 if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {
692 tenantNewObj.put("cloudOwner", rShipVal);
693 } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {
694 tenantNewObj.put("cloudRegionID", rShipVal);
695 } else if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {
696 tenantNewObj.put("tenantID", rShipVal);
700 private static String encodePathSegment(String segmentToEncode) {
702 return UriUtils.encodePathSegment(segmentToEncode, "UTF-8");
703 } catch (UnsupportedEncodingException e) {
704 throw new GenericUncheckedException("URI encoding failed unexpectedly", e);
709 public ExternalComponentStatus probeAaiGetAllSubscribers(){
710 long startTime = System.currentTimeMillis();
712 AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = getAllSubscribers(true);
713 AaiResponse<SubscriberList> aaiResponse = responseWithRequestInfo.getAaiResponse();
714 long duration = System.currentTimeMillis() - startTime;
716 SubscriberList subscribersList = (aaiResponse != null) ? aaiResponse.getT() : null;
717 boolean isAvailable = subscribersList != null && subscribersList.customer != null && !subscribersList.customer.isEmpty();
719 HttpRequestMetadata metadata = new HttpRequestMetadata(
720 responseWithRequestInfo.getHttpMethod(),
721 (aaiResponse != null) ? aaiResponse.getHttpCode() : 0,
722 responseWithRequestInfo.getRequestedUrl(),
723 responseWithRequestInfo.getRawData(),
724 isAvailable ? "OK" : "No subscriber received",
727 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, metadata);
729 } catch (ExceptionWithRequestInfo e) {
730 long duration = System.currentTimeMillis() - startTime;
731 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
732 new HttpRequestMetadata(e, duration));
733 } catch (Exception e) {
734 long duration = System.currentTimeMillis() - startTime;
735 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
736 new ErrorMetadata(Logging.exceptionToDescription(e), duration));
741 public String getCloudOwnerByCloudRegionId(String cloudRegionId) {
743 .aaiClientCacheFor("getCloudOwnerByCloudRegionId", this::getCloudOwnerByCloudRegionIdNonCached)
749 public GetTenantsResponse getHomingDataByVfModule(String vnfInstanceId, String vfModuleId) {
751 if (StringUtils.isEmpty(vnfInstanceId)||StringUtils.isEmpty(vfModuleId)){
752 throw new GenericUncheckedException("Failed to retrieve homing data associated to vfModule from A&AI, VNF InstanceId or VF Module Id is missing.");
754 Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId +"/vf-modules/vf-module/"+ vfModuleId, false);
755 String responseAsString = parseForTenantsByServiceSubscription("vserver",resp.readEntity(String.class));
756 if (responseAsString.equals("")){
757 throw new GenericUncheckedException( String.format("A&AI has no homing data associated to vfModule '%s' of vnf '%s'", vfModuleId, vnfInstanceId));
760 AaiResponse aaiResponse = processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
761 return ((GetTenantsResponse[])aaiResponse.getT())[0];
766 public void resetCache(String cacheName) {
767 cacheProvider.resetCache(cacheName);
770 String getCloudOwnerByCloudRegionIdNonCached(String cloudRegionId) {
771 String uri = "cloud-infrastructure/cloud-regions?cloud-region-id=" + encodePathSegment(cloudRegionId);
773 final CloudRegion.Collection cloudRegionCollection =
774 typedAaiGet(Unchecked.toURI(uri), CloudRegion.Collection.class);
776 return cloudRegionCollection
777 .getCloudRegions().stream()
778 .map(CloudRegion::getCloudOwner)
779 // from here we assure that the cloud owner is given, and not null
780 // and non-empty, and that if more than one cloud-owner is given -
781 // it is only a single value.
782 // exception is thrown if none or more than a single values are
784 .filter(StringUtils::isNotEmpty)
787 // will be invoked only if distinct() leaves more than a single element
788 throw new GenericUncheckedException("Conflicting cloud-owner found for " + cloudRegionId + ": '" + a + "' / '" + b + "'");
790 .orElseThrow(() -> new GenericUncheckedException("No cloud-owner found for " + cloudRegionId));
793 private AaiResponse getTenantsByKey(String key) {
794 String[] args = CacheProvider.decompileKey(key);
795 String globalCustomerId = safeGetFromArray(args, 0);
796 String serviceType = safeGetFromArray(args, 1);
797 return getTenantsNonCached(globalCustomerId, serviceType);
800 AaiResponse getTenantsNonCached(String globalCustomerId, String serviceType) {
801 String url = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType;
803 Response resp = doAaiGet(url, false);
804 String responseAsString = parseForTenantsByServiceSubscription("tenant",resp.readEntity(String.class));
805 if (StringUtils.isEmpty(responseAsString)){
806 throw new ParsingGetTenantsResponseFailure(String.format("A&AI has no LCP Region & Tenants associated to subscriber '%s' and service type '%s'", globalCustomerId, serviceType));
809 return processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
813 public static class ParsingGetTenantsResponseFailure extends GenericUncheckedException {
815 public ParsingGetTenantsResponseFailure(String message) {
821 private AaiResponse<String> buildAaiResponseForGetTenantsFailure(String errorText) {
822 return new AaiResponse<>(null, String.format("{\"statusText\":\"%s\"}", errorText), HttpStatus.SC_INTERNAL_SERVER_ERROR);
825 private static String safeGetFromArray(String[] array, int i) {
826 if (i < 0 || i >= array.length) {