2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.vid.aai;
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;
29 import com.fasterxml.jackson.databind.JsonNode;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import java.io.IOException;
32 import java.io.UnsupportedEncodingException;
34 import java.net.URLEncoder;
35 import java.util.LinkedHashMap;
36 import java.util.List;
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;
90 * Created by Oren on 7/4/17.
92 public class AaiClient implements AaiClientInterface {
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/";
103 protected String fromAppId = "VidAaiController";
105 private PortDetailsTranslator portDetailsTranslator;
107 private final AAIRestInterface restController;
109 private final CacheProvider cacheProvider;
111 ObjectMapper objectMapper = new ObjectMapper();
116 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class);
118 private static final String GET_SERVICE_MODELS_RESPONSE_BODY = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}";
121 public AaiClient(AAIRestInterface restController, PortDetailsTranslator portDetailsTranslator, CacheProvider cacheProvider) {
122 this.restController = restController;
123 this.portDetailsTranslator = portDetailsTranslator;
124 this.cacheProvider = cacheProvider;
128 private static String checkForNull(String local) {
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);
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);
149 public AaiResponse getServiceModelsByDistributionStatus() {
150 return getFromCache("getServiceModelsByDistributionStatus", this::getServiceModelsByDistributionStatusNonCached,
151 true, "Failed to get service models by distribution status");
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);
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);
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);
175 private AaiResponse getNetworkCollectionDetailsResponse(AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse){
176 if(aaiResponse.getHttpCode() == 200) {
177 ObjectMapper om = objectMapper;
178 AaiGetNetworkCollectionDetails aaiGetNetworkCollectionDetails = new AaiGetNetworkCollectionDetails();
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));
191 return new AaiResponse(aaiGetNetworkCollectionDetails, null, HttpStatus.SC_OK);
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);
197 catch (Exception e) {
198 return new AaiResponse(e.getCause(), "Got " + aaiResponse.getHttpCode() + " from a&ai" , aaiResponse.getHttpCode());
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);
215 public AaiResponse<Pnf> getSpecificPnf(String pnfId) {
216 Response resp = doAaiGet("network/pnfs/pnf/"+pnfId, false);
217 return processAaiResponse(resp, Pnf.class, null);
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);
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);
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);
246 public AaiResponse getLogicalLink(String link) {
247 Response resp = doAaiGet("network/logical-links/logical-link/" + link , false);
248 return processAaiResponse(resp, LogicalLinkResponse.class, null);
252 public boolean isNodeTypeExistsByName(String name, ResourceType type) {
254 throw new GenericUncheckedException("Empty resource-name provided to searchNodeTypeByName; request is rejected as this will cause full resources listing");
257 URI path = Unchecked.toURI(String.format( // e.g. GET /aai/v$/nodes/vf-modules?vf-module-name={vf-module-name}
260 type.getNameFilter(),
261 encodePathSegment(name)
263 final ResponseWithRequestInfo responseWithRequestInfo = restController.RestGet(fromAppId, UUID.randomUUID().toString(), path, false, true);
265 return isResourceExistByStatusCode(responseWithRequestInfo);
268 public Map<String, Properties> getCloudRegionAndTenantByVnfId(String vnfId) {
269 String start = "/network/generic-vnfs/generic-vnf/" + vnfId;
270 String query = "/query/cloud-region-fromVnf";
272 String payload = "{\"start\":[\"" + start + "\"],\"query\":\"" + query + "\"}";
273 CustomQuerySimpleResult result = typedAaiRest(QUERY_FORMAT_SIMPLE, CustomQuerySimpleResult.class, payload, HttpMethod.PUT, false);
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));
281 private boolean isResourceExistByStatusCode(ResponseWithRequestInfo responseWithRequestInfo) {
283 // 404 - resource not found
284 Response.Status statusInfo = responseWithRequestInfo.getResponse().getStatusInfo().toEnum();
285 switch (statusInfo) {
291 throw new GenericUncheckedException("Unexpected response-code (only OK and NOT_FOUND are expected): " +
292 responseWithRequestInfo.getResponse().getStatusInfo());
297 public <T> T typedAaiGet(URI uri, Class<T> clz) {
298 return typedAaiRest(uri, clz, null, HttpMethod.GET, false);
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);
306 public <T> T typedAaiRest(URI path, Class<T> clz, String payload, HttpMethod method, boolean propagateExceptions) {
307 ResponseWithRequestInfo responseWithRequestInfo;
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);
314 final AaiResponseWithRequestInfo<T> aaiResponse = processAaiResponse(responseWithRequestInfo, clz, VidObjectMapperType.FASTERXML, true);
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()));
324 return aaiResponse.getAaiResponse().getT();
328 private String getUrlFromLIst(String url, String paramKey, List<String> params){
330 for(String param: params){
332 url = url.concat(paramKey);
333 String encodedParam= param;
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());
341 url = url.concat(encodedParam);
342 if(i != params.size()){
343 url = url.concat("&");
352 public AaiResponse<SubscriberList> getAllSubscribers() {
353 return getFromCache("getAllSubscribers", this::getAllSubscribersNonCached, true, "Failed to get all subscribers");
356 private <K> AaiResponse getFromCache(String cacheName, Function<K, AaiResponse> function, K argument, String errorMessage) {
359 .aaiClientCacheFor(cacheName, function)
361 } catch (ExceptionWithRequestInfo exception) {
362 logger.error(errorMessage, exception);
363 return new AaiResponse(null, exception.getRawData(), exception.getHttpCode());
365 catch (Exception exception) {
366 logger.error(errorMessage, exception);
367 return new AaiResponse(null, exception.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR);
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.");
380 AaiResponseWithRequestInfo<SubscriberList> getAllSubscribers(boolean propagateExceptions){
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;
391 public AaiResponse getAllAicZones() {
392 Response resp = doAaiGet("network/zones", false);
393 return processAaiResponse(resp, AicZones.class, null);
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);
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);
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");
417 StringBuilder sb = new StringBuilder();
418 for (String id : modelInvariantId){
419 sb.append(MODEL_INVARIANT_ID);
423 return doAaiGet("service-design-and-creation/models?depth=2"+ sb.toString(), false);
427 public AaiResponse getSubscriberData(String subscriberId) {
429 AaiResponse subscriberDataResponse;
430 Response resp = doAaiGet(BUSINESS_CUSTOMERS_CUSTOMER + subscriberId + "?depth=" + depth, false);
431 subscriberDataResponse = processAaiResponse(resp, Services.class, null);
432 return subscriberDataResponse;
436 public AaiResponse getServices() {
437 Response resp = doAaiGet("service-design-and-creation/services", false);
438 return processAaiResponse(resp, GetServicesAAIRespone.class, null);
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);
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.");
461 .aaiClientCacheFor("getTenants", this::getTenantsByKey)
462 .get(CacheProvider.compileKey(globalCustomerId, serviceType));
464 catch (ParsingGetTenantsResponseFailure exception) {
465 logger.error("Failed to get tenants ", exception);
466 return buildAaiResponseForGetTenantsFailure(exception.getMessage());
471 public AaiResponse getNodeTemplateInstances(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion) {
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 + "\"}";
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);
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 + "}";
489 Response response = doAaiPut("query?format=simple&nodesOnly=true", payload, false);
490 AaiResponse<JsonNode> aaiResponse = processAaiResponse(response, JsonNode.class, null);
492 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse);
496 private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, boolean propagateExceptions) {
497 return processAaiResponse(responseWithRequestInfo, classType, VidObjectMapperType.CODEHAUS, propagateExceptions);
500 private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, VidObjectMapperType omType, boolean propagateExceptions) {
501 String responseBody = null;
502 Integer responseHttpCode = null;
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,
510 } catch (Exception e) {
511 throw new ExceptionWithRequestInfo(responseWithRequestInfo.getRequestHttpMethod(),
512 responseWithRequestInfo.getRequestUrl(), responseBody, responseHttpCode, e);
516 private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody) {
517 return processAaiResponse(resp, classType, responseBody, VidObjectMapperType.CODEHAUS);
520 private <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType) {
521 return processAaiResponse(resp, classType, responseBody, omType, false);
524 private <T> AaiResponse<T> processAaiResponse(Response resp, Class<? extends T> classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
525 AaiResponse<T> subscriberDataResponse;
527 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
528 logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
530 logger.debug(EELFLoggerDelegate.debugLogger, "getSubscribers() resp=" + resp.getStatusInfo().toString());
531 if (resp.getStatus() != HttpStatus.SC_OK) {
532 subscriberDataResponse = processFailureResponse(resp,responseBody);
534 subscriberDataResponse = processOkResponse(resp, classType, responseBody, omType, propagateExceptions);
537 return subscriberDataResponse;
540 private AaiResponse processFailureResponse(Response resp, String responseBody) {
541 logger.debug(EELFLoggerDelegate.debugLogger, "Invalid response from AAI");
543 if (responseBody != null) {
544 rawData = responseBody;
546 rawData = resp.readEntity(String.class);
548 return new AaiResponse<>(null, rawData, resp.getStatus());
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;
555 if (responseBody != null) {
556 finalResponse = responseBody;
558 finalResponse = resp.readEntity(String.class);
561 if(omType == VidObjectMapperType.CODEHAUS)
562 subscriberDataResponse = parseCodeHausObject(classType, finalResponse);
564 subscriberDataResponse = parseFasterXmlObject(classType, finalResponse);
566 } catch(Exception e){
567 if (propagateExceptions) {
568 throw new GenericUncheckedException(e);
570 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
571 logger.error("Failed to parse aai response: \"{}\" to class {}", finalResponse, classType, e);
574 return subscriberDataResponse;
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);
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);
586 public Response doAaiGet(String uri, boolean xml) {
587 return doAaiGet(uri, xml, false).getResponse();
591 public ResponseWithRequestInfo doAaiGet(String uri, boolean xml, boolean propagateExceptions) {
592 return doAaiGet(Unchecked.toURI(uri), xml, propagateExceptions);
595 public ResponseWithRequestInfo doAaiGet(URI uri, boolean xml, boolean propagateExceptions) {
596 String methodName = "doAaiGet";
597 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
599 ResponseWithRequestInfo resp;
601 resp = restController.RestGet(fromAppId, UUID.randomUUID().toString(), uri, xml, propagateExceptions);
603 } catch (Exception e) {
604 resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
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);
615 final Exception actual =
616 e instanceof ExceptionWithRequestInfo ? (Exception) e.getCause() : e;
618 final String message =
619 actual instanceof WebApplicationException ? ((WebApplicationException) actual).getResponse().readEntity(String.class) : e.toString();
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);
629 private String parseForTenantsByServiceSubscription(String relatedToKey, String resp) {
630 String tenantList = "";
633 JSONParser jsonParser = new JSONParser();
635 JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
637 return parseServiceSubscriptionObjectForTenants(relatedToKey, jsonObject);
638 } catch (Exception ex) {
639 logger.debug(EELFLoggerDelegate.debugLogger, "parseForTenantsByServiceSubscription error while parsing tenants by service subscription", ex);
644 protected Response doAaiPut(String uri, String payload, boolean xml) {
645 return doAaiPut(uri, payload, xml, false).getResponse();
648 protected ResponseWithRequestInfo doAaiPut(String uri, String payload, boolean xml, boolean propagateExceptions) {
649 String methodName = "doAaiPut";
650 logger.debug(EELFLoggerDelegate.debugLogger, methodName + " start");
652 ResponseWithRequestInfo resp;
655 resp = restController.RestPut(fromAppId, uri, payload, xml, propagateExceptions);
657 } catch (Exception e) {
658 resp = handleExceptionFromRestCall(propagateExceptions, methodName, e);
664 private String parseServiceSubscriptionObjectForTenants(String relatedToKey, JSONObject jsonObject) {
665 JSONArray tenantArray = new JSONArray();
666 boolean bconvert = false;
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);
677 } catch (NullPointerException ex) {
678 logger.debug(EELFLoggerDelegate.debugLogger, "parseServiceSubscriptionObjectForTenants. error while parsing service subscription object for tenants", ex);
682 return tenantArray.toJSONString();
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();
693 String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
694 tenantNewObj.put("link", relatedLink);
696 JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
697 for (Object innerObj : defaultIfNull(rDataArray, emptyList())) {
698 parseRelationShip(tenantNewObj, (JSONObject) innerObj);
701 JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
702 for (Object innerObj : defaultIfNull(relatedTPropArray, emptyList())) {
703 parseRelatedTProp(tenantNewObj, (JSONObject) innerObj);
706 tenantArray.add(tenantNewObj);
711 private static void parseRelatedTProp(JSONObject tenantNewObj, JSONObject innerObj) {
712 if (innerObj == null)
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);
722 private static void parseRelationShip(JSONObject tenantNewObj, JSONObject inner2Obj) {
723 if (inner2Obj == null)
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);
737 private static String encodePathSegment(String segmentToEncode) {
739 return UriUtils.encodePathSegment(segmentToEncode, "UTF-8");
740 } catch (UnsupportedEncodingException e) {
741 throw new GenericUncheckedException("URI encoding failed unexpectedly", e);
746 public ExternalComponentStatus probeAaiGetAllSubscribers(){
747 long startTime = System.currentTimeMillis();
749 AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = getAllSubscribers(true);
750 AaiResponse<SubscriberList> aaiResponse = responseWithRequestInfo.getAaiResponse();
751 long duration = System.currentTimeMillis() - startTime;
753 SubscriberList subscribersList = (aaiResponse != null) ? aaiResponse.getT() : null;
754 boolean isAvailable = subscribersList != null && subscribersList.customer != null && !subscribersList.customer.isEmpty();
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",
764 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, metadata);
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));
778 public String getCloudOwnerByCloudRegionId(String cloudRegionId) {
780 .aaiClientCacheFor("getCloudOwnerByCloudRegionId", this::getCloudOwnerByCloudRegionIdNonCached)
786 public GetTenantsResponse getHomingDataByVfModule(String vnfInstanceId, String vfModuleId) {
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.");
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));
797 AaiResponse aaiResponse = processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
798 return ((GetTenantsResponse[])aaiResponse.getT())[0];
803 public void resetCache(String cacheName) {
804 cacheProvider.resetCache(cacheName);
807 String getCloudOwnerByCloudRegionIdNonCached(String cloudRegionId) {
808 String uri = "cloud-infrastructure/cloud-regions?cloud-region-id=" + encodePathSegment(cloudRegionId);
810 final CloudRegion.Collection cloudRegionCollection =
811 typedAaiGet(Unchecked.toURI(uri), CloudRegion.Collection.class);
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
821 .filter(StringUtils::isNotEmpty)
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 + "'");
827 .orElseThrow(() -> new GenericUncheckedException("No cloud-owner found for " + cloudRegionId));
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);
837 AaiResponse getTenantsNonCached(String globalCustomerId, String serviceType) {
838 String url = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType;
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));
846 return processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
850 public static class ParsingGetTenantsResponseFailure extends GenericUncheckedException {
852 public ParsingGetTenantsResponseFailure(String message) {
858 private AaiResponse<String> buildAaiResponseForGetTenantsFailure(String errorText) {
859 return new AaiResponse<>(null, String.format("{\"statusText\":\"%s\"}", errorText), HttpStatus.SC_INTERNAL_SERVER_ERROR);
862 private static String safeGetFromArray(String[] array, int i) {
863 if (i < 0 || i >= array.length) {