1 package org.onap.vid.aai;
3 import org.apache.commons.lang3.StringUtils;
4 import org.apache.http.HttpStatus;
5 import org.apache.http.client.utils.URIBuilder;
6 import org.codehaus.jackson.JsonNode;
7 import org.codehaus.jackson.map.ObjectMapper;
8 import org.json.simple.JSONArray;
9 import org.json.simple.JSONObject;
10 import org.json.simple.parser.JSONParser;
11 import org.onap.vid.aai.model.AaiGetAicZone.AicZones;
12 import org.onap.vid.aai.model.*;
13 import org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.*;
14 import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
15 import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
16 import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone;
17 import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
18 import org.onap.vid.aai.model.Relationship;
19 import org.onap.vid.aai.model.RelationshipData;
20 import org.onap.vid.aai.model.RelationshipList;
21 import org.onap.vid.aai.util.AAIRestInterface;
22 import org.onap.vid.aai.util.VidObjectMapperType;
23 import org.onap.vid.exceptions.GenericUncheckedException;
24 import org.onap.vid.model.SubscriberList;
25 import org.onap.vid.model.probes.ErrorMetadata;
26 import org.onap.vid.model.probes.ExternalComponentStatus;
27 import org.onap.vid.model.probes.HttpRequestMetadata;
28 import org.onap.vid.utils.Logging;
29 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
30 import org.springframework.web.util.UriUtils;
32 import javax.inject.Inject;
33 import javax.ws.rs.WebApplicationException;
34 import javax.ws.rs.core.Response;
35 import java.io.IOException;
36 import java.io.UnsupportedEncodingException;
37 import java.net.URLEncoder;
38 import java.text.DateFormat;
39 import java.text.SimpleDateFormat;
42 import static java.util.Collections.emptyList;
43 import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
47 * Created by Oren on 7/4/17.
49 public class AaiClient implements AaiClientInterface {
52 public static final String QUERY_FORMAT_RESOURCE = "query?format=resource";
53 public static final String SERVICE_SUBSCRIPTIONS_PATH = "/service-subscriptions/service-subscription/";
54 public static final String MODEL_INVARIANT_ID = "&model-invariant-id=";
55 public static final String QUERY_FORMAT_SIMPLE = "query?format=simple";
56 public static final String BUSINESS_CUSTOMER = "/business/customers/customer/";
57 public static final String SERVICE_INSTANCE = "/service-instances/service-instance/";
58 public static final String BUSINESS_CUSTOMERS_CUSTOMER = "business/customers/customer/";
60 protected String fromAppId = "VidAaiController";
62 private PortDetailsTranslator portDetailsTranslator;
64 private final AAIRestInterface restController;
69 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class);
72 * The Constant dateFormat.
74 static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
76 static final String GET_SERVICE_MODELS_RESPONSE_BODY = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}";
79 public AaiClient(AAIRestInterface restController, PortDetailsTranslator portDetailsTranslator) {
80 this.restController = restController;
81 this.portDetailsTranslator = portDetailsTranslator;
85 private static String checkForNull(String local) {
94 public AaiResponse getServicesByOwningEntityId(List<String> owningEntityIds){
95 Response resp = doAaiGet(getUrlFromLIst("business/owning-entities?", "owning-entity-id=", owningEntityIds), false);
96 return processAaiResponse(resp, OwningEntityResponse.class, null);
100 public AaiResponse getServicesByProjectNames(List<String> projectNames){
101 Response resp = doAaiGet(getUrlFromLIst("business/projects?", "project-name=", projectNames), false);
102 return processAaiResponse(resp, ProjectResponse.class, null);
106 public AaiResponse getServiceModelsByDistributionStatus() {
107 Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, GET_SERVICE_MODELS_RESPONSE_BODY, false);
108 return processAaiResponse(resp, GetServiceModelsByDistributionStatusResponse.class, null);
112 public AaiResponse getNetworkCollectionDetails(String serviceInstanceId) {
113 Response resp = doAaiPut(QUERY_FORMAT_RESOURCE, "{\"start\": [\"nodes/service-instances/service-instance/" + serviceInstanceId + "\"],\"query\": \"query/network-collection-ByServiceInstance\"}\n", false);
114 AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse = processAaiResponse(resp, AaiGetNetworkCollectionDetailsHelper.class, null, VidObjectMapperType.FASTERXML);
115 return getNetworkCollectionDetailsResponse(aaiResponse);
119 public AaiResponse getInstanceGroupsByCloudRegion(String cloudOwner, String cloudRegionId, String networkFunction) {
120 Response resp = doAaiPut(QUERY_FORMAT_RESOURCE,
121 "{\"start\": [\"cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId + "\"]," +
122 "\"query\": \"query/instance-group-byCloudRegion?type=L3-NETWORK&role=SUB-INTERFACE&function=" + networkFunction + "\"}\n", false);
123 return processAaiResponse(resp, AaiGetInstanceGroupsByCloudRegion.class, null, VidObjectMapperType.FASTERXML);
126 private AaiResponse getNetworkCollectionDetailsResponse(AaiResponse<AaiGetNetworkCollectionDetailsHelper> aaiResponse){
127 if(aaiResponse.getHttpCode() == 200) {
128 com.fasterxml.jackson.databind.ObjectMapper om = new com.fasterxml.jackson.databind.ObjectMapper();
129 AaiGetNetworkCollectionDetails aaiGetNetworkCollectionDetails = new AaiGetNetworkCollectionDetails();
131 for (int i = 0; i < aaiResponse.getT().getResults().size(); i++) {
132 LinkedHashMap<String, Object> temp = ((LinkedHashMap) aaiResponse.getT().getResults().get(i));
133 if (temp.get("service-instance") != null)
134 aaiGetNetworkCollectionDetails.getResults().setServiceInstance(om.readValue(om.writeValueAsString(temp.get("service-instance")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.ServiceInstance.class));
135 else if (temp.get("collection") != null)
136 aaiGetNetworkCollectionDetails.getResults().setCollection(om.readValue(om.writeValueAsString(temp.get("collection")), org.onap.vid.aai.model.AaiGetNetworkCollectionDetails.Collection.class));
137 else if (temp.get("instance-group") != null)
138 aaiGetNetworkCollectionDetails.getResults().setInstanceGroup(om.readValue(om.writeValueAsString(temp.get("instance-group")), InstanceGroup.class));
139 else if (temp.get("l3-network") != null)
140 aaiGetNetworkCollectionDetails.getResults().getNetworks().add(om.readValue(om.writeValueAsString(temp.get("l3-network")), Network.class));
142 return new AaiResponse(aaiGetNetworkCollectionDetails, null, HttpStatus.SC_OK);
144 catch (com.fasterxml.jackson.databind.JsonMappingException e) {
145 return new AaiResponse(e.getCause(), "AAI response parsing Error" , aaiResponse.getHttpCode());
147 catch (Exception e) {
148 return new AaiResponse(e.getCause(), "Got " + aaiResponse.getHttpCode() + " from a&ai" , aaiResponse.getHttpCode());
155 public AaiResponse getPNFData(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion, String equipVendor, String equipModel) {
156 String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
157 String pnfQuery = "query/pnf-fromModel-byRegion?cloudRegionId=" + encodePathSegment(cloudRegion) + "&equipVendor=" + encodePathSegment(equipVendor) + "&equipModel=" + encodePathSegment(equipModel);
158 String payload = "{\"start\":\"" + siQuery + "\",\"query\":\"" + pnfQuery + "\"}";
159 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
160 return processAaiResponse(resp, AaiGetPnfResponse.class, null);
165 public AaiResponse<Pnf> getSpecificPnf(String pnfId) {
166 Response resp = doAaiGet("network/pnfs/pnf/"+pnfId, false);
167 return processAaiResponse(resp, Pnf.class, null);
171 public AaiResponse getInstanceGroupsByVnfInstanceId(String vnfInstanceId){
172 Response resp = doAaiGet("network/generic-vnfs/generic-vnf/" + vnfInstanceId + "?depth=0", false);
173 return processAaiResponse(resp, AaiGetRelatedInstanceGroupsByVnfId.class , null, null);
178 public List<PortDetailsTranslator.PortDetails> getPortMirroringSourcePorts(String configurationID) {
179 String payload = "{\"start\":\"/network/configurations/configuration/" + configurationID + "\",\"query\":\"query/pserver-fromConfiguration\"}";
180 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
181 resp.bufferEntity(); // avoid later "Entity input stream has already been closed" problems
182 String rawPayload = resp.readEntity(String.class);
183 AaiResponse<AaiGetPortMirroringSourcePorts> aaiResponse = processAaiResponse(resp, AaiGetPortMirroringSourcePorts.class, rawPayload);
184 return portDetailsTranslator.extractPortDetails(aaiResponse, rawPayload);
189 public AaiResponse getServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) {
190 String getServiceInstancePath = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId+ SERVICE_SUBSCRIPTIONS_PATH +serviceType+ SERVICE_INSTANCE +serviceInstanceId;
191 Response resp = doAaiGet(getServiceInstancePath , false);
192 return processAaiResponse(resp, ServiceRelationships.class, null);
196 public AaiResponse getLogicalLink(String link) {
197 Response resp = doAaiGet("network/logical-links/logical-link/" + link , false);
198 return processAaiResponse(resp, LogicalLinkResponse.class, null);
202 public AaiResponse<AaiNodeQueryResponse> searchNodeTypeByName(String name, ResourceType type) {
203 String path = String.format(
204 "search/nodes-query?search-node-type=%s&filter=%s:EQUALS:%s",
206 type.getNameFilter(),
209 return typedAaiGet(path, AaiNodeQueryResponse.class);
212 private <T> AaiResponse<T> typedAaiGet(String path, Class<T> clz) {
213 Response resp = doAaiGet(path , false);
214 return processAaiResponse(resp, clz, null, VidObjectMapperType.FASTERXML);
219 private String getUrlFromLIst(String url, String paramKey, List<String> params){
221 for(String param: params){
223 url = url.concat(paramKey);
224 String encodedParam= param;
226 encodedParam= URLEncoder.encode(param, "UTF-8");
227 } catch (UnsupportedEncodingException e) {
228 String methodName = "getUrlFromList";
229 logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
230 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
232 url = url.concat(encodedParam);
233 if(i != params.size()){
234 url = url.concat("&");
242 public AaiResponse<SubscriberList> getAllSubscribers() {
243 return getAllSubscribers(false).getAaiResponse();
246 AaiResponseWithRequestInfo<SubscriberList> getAllSubscribers(boolean propagateExceptions){
248 ResponseWithRequestInfo aaiGetResult = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false, propagateExceptions);
249 AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = processAaiResponse(aaiGetResult, SubscriberList.class, propagateExceptions);
250 responseWithRequestInfo.setRequestedUrl(aaiGetResult.getRequestUrl());
251 responseWithRequestInfo.setHttpMethod(aaiGetResult.getRequestHttpMethod());
252 return responseWithRequestInfo;
257 public AaiResponse getAllAicZones() {
258 Response resp = doAaiGet("network/zones", false);
259 return processAaiResponse(resp, AicZones.class, null);
264 public AaiResponse<String> getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId) {
265 String aicZonePath = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType + SERVICE_INSTANCE + serviceId;
266 Response resp = doAaiGet(aicZonePath , false);
267 AaiResponse<ServiceRelationships> aaiResponse = processAaiResponse(resp , ServiceRelationships.class , null);
268 ServiceRelationships serviceRelationships = aaiResponse.getT();
269 RelationshipList relationshipList = serviceRelationships.getRelationshipList();
270 Relationship relationship = relationshipList.getRelationship().get(0);
271 RelationshipData relationshipData= relationship.getRelationDataList().get(0);
272 String aicZone = relationshipData.getRelationshipValue();
273 return new AaiResponse(aicZone , null ,HttpStatus.SC_OK);
278 public AaiResponse getVNFData() {
279 String payload = "{\"start\": [\"/business/customers/customer/e433710f-9217-458d-a79d-1c7aff376d89/service-subscriptions/service-subscription/VIRTUAL%20USP/service-instances/service-instance/3f93c7cb-2fd0-4557-9514-e189b7b04f9d\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}";
280 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
281 return processAaiResponse(resp, AaiGetVnfResponse.class, null);
285 public Response getVNFData(String globalSubscriberId, String serviceType) {
286 String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) +"/service-instances\"]," +
287 "\"query\": \"query/vnf-topology-fromServiceInstance\"}";
288 return doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
292 public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) {
293 String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + SERVICE_INSTANCE + serviceInstanceId + "\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}";
294 Response resp = doAaiPut(QUERY_FORMAT_SIMPLE, payload, false);
295 return processAaiResponse(resp, AaiGetVnfResponse.class, null);
299 public Response getVersionByInvariantId(List<String> modelInvariantId) {
300 StringBuilder sb = new StringBuilder();
301 for (String id : modelInvariantId){
302 sb.append(MODEL_INVARIANT_ID);
306 return doAaiGet("service-design-and-creation/models?depth=2"+ sb.toString(), false);
310 public AaiResponse getSubscriberData(String subscriberId) {
312 AaiResponse subscriberDataResponse;
313 Response resp = doAaiGet(BUSINESS_CUSTOMERS_CUSTOMER + subscriberId + "?depth=" + depth, false);
314 subscriberDataResponse = processAaiResponse(resp, Services.class, null);
315 return subscriberDataResponse;
319 public AaiResponse getServices() {
320 Response resp = doAaiGet("service-design-and-creation/services", false);
321 return processAaiResponse(resp, GetServicesAAIRespone.class, null);
325 public AaiResponse getOperationalEnvironments(String operationalEnvironmentType, String operationalEnvironmentStatus) {
326 String url = "cloud-infrastructure/operational-environments";
327 URIBuilder urlBuilder = new URIBuilder();
328 if (operationalEnvironmentType != null)
329 urlBuilder.addParameter("operational-environment-type", operationalEnvironmentType);
330 if (operationalEnvironmentStatus != null)
331 urlBuilder.addParameter("operational-environment-status", operationalEnvironmentStatus);
332 url += urlBuilder.toString();
333 Response resp = doAaiGet(url, false);
334 return processAaiResponse(resp, OperationalEnvironmentList.class, null);
338 public AaiResponse getTenants(String globalCustomerId, String serviceType) {
339 AaiResponse aaiResponse;
341 if ((globalCustomerId == null || globalCustomerId.isEmpty()) || ((serviceType == null) || (serviceType.isEmpty())) ){
342 aaiResponse = new AaiResponse<>(null, "{\"statusText\":\" Failed to retrieve LCP Region & Tenants from A&AI, Subscriber ID or Service Type is missing.\"}", HttpStatus.SC_INTERNAL_SERVER_ERROR);
346 String url = BUSINESS_CUSTOMERS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + serviceType;
348 Response resp = doAaiGet(url, false);
349 String responseAsString = parseForTenantsByServiceSubscription(resp.readEntity(String.class));
350 if (responseAsString.equals("")){
351 return new AaiResponse<>(null, String.format("{\"statusText\":\" A&AI has no LCP Region & Tenants associated to subscriber '%s' and service type '%s'\"}", globalCustomerId, serviceType), HttpStatus.SC_INTERNAL_SERVER_ERROR);
354 return processAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
359 public AaiResponse getNodeTemplateInstances(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion) {
361 String siQuery = BUSINESS_CUSTOMER + globalCustomerId + SERVICE_SUBSCRIPTIONS_PATH + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + MODEL_INVARIANT_ID + modelInvariantId;
362 String vnfQuery = "query/queryvnfFromModelbyRegion?cloudRegionId=" + encodePathSegment(cloudRegion);
363 String payload1 = "{\"start\":\"" + siQuery + "\",\"query\":\"" + vnfQuery + "\"}";
365 Response resp1 = doAaiPut(QUERY_FORMAT_SIMPLE, payload1, false);
366 AaiResponse aaiResponse1 = processAaiResponse(resp1, AaiGetVnfResponse.class, null);
367 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse1);
372 public AaiResponse<JsonNode> getCloudRegionAndSourceByPortMirroringConfigurationId(String configurationId) {
373 final String start = "[\"network/configurations/configuration/" + configurationId + "\"]";
374 final String query = "\"query/cloud-region-and-source-FromConfiguration\"";
375 String payload = "{\"start\":" + start + ",\"query\":" + query + "}";
377 Response response = doAaiPut("query?format=simple&nodesOnly=true", payload, false);
378 AaiResponse<JsonNode> aaiResponse = processAaiResponse(response, JsonNode.class, null);
380 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse);
384 private <T> AaiResponseWithRequestInfo<T> processAaiResponse(ResponseWithRequestInfo responseWithRequestInfo, Class<? extends T> classType, boolean propagateExceptions) {
385 String responseBody = null;
386 Integer responseHttpCode = null;
388 Response response = responseWithRequestInfo.getResponse();
389 responseHttpCode = (response != null) ? response.getStatus() : null;
390 responseBody = (response != null) ? response.readEntity(String.class) : null;
391 AaiResponse<T> processedAaiResponse = processAaiResponse(response, classType, responseBody, VidObjectMapperType.CODEHAUS, propagateExceptions);
392 return new AaiResponseWithRequestInfo<>(responseWithRequestInfo.getRequestHttpMethod(), responseWithRequestInfo.getRequestUrl(), processedAaiResponse,
394 } catch (Exception e) {
395 throw new ExceptionWithRequestInfo(responseWithRequestInfo.getRequestHttpMethod(),
396 responseWithRequestInfo.getRequestUrl(), responseBody, responseHttpCode, e);
400 private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody) {
401 return processAaiResponse(resp, classType, responseBody, VidObjectMapperType.CODEHAUS);
404 private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType) {
405 return processAaiResponse(resp, classType, responseBody, omType, false);
408 private AaiResponse processAaiResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
409 AaiResponse subscriberDataResponse;
411 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
412 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI");
414 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString());
415 if (resp.getStatus() != HttpStatus.SC_OK) {
416 subscriberDataResponse = processFailureResponse(resp,responseBody);
418 subscriberDataResponse = processOkResponse(resp, classType, responseBody, omType, propagateExceptions);
421 return subscriberDataResponse;
424 private AaiResponse processFailureResponse(Response resp, String responseBody) {
425 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI");
427 if (responseBody != null) {
428 rawData = responseBody;
430 rawData = resp.readEntity(String.class);
432 return new AaiResponse<>(null, rawData, resp.getStatus());
435 private AaiResponse processOkResponse(Response resp, Class classType, String responseBody, VidObjectMapperType omType, boolean propagateExceptions) {
436 AaiResponse subscriberDataResponse;
437 String finalResponse = null;
439 if (responseBody != null) {
440 finalResponse = responseBody;
442 finalResponse = resp.readEntity(String.class);
445 if(omType == VidObjectMapperType.CODEHAUS)
446 subscriberDataResponse = parseCodeHausObject(classType, finalResponse);
448 subscriberDataResponse = parseFasterXmlObject(classType, finalResponse);
450 } catch(Exception e){
451 if (propagateExceptions) {
452 throw new GenericUncheckedException(e);
454 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
455 logger.error("Failed to parse aai response: \"{}\" to class {}", finalResponse, classType, e);
458 return subscriberDataResponse;
461 private AaiResponse parseFasterXmlObject(Class classType, String finalResponse) throws IOException {
462 com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
463 return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
466 private AaiResponse parseCodeHausObject(Class classType, String finalResponse) throws IOException {
467 ObjectMapper objectMapper = new ObjectMapper();
468 return new AaiResponse<>((objectMapper.readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
471 public Response doAaiGet(String uri, boolean xml) {
472 return doAaiGet(uri, xml, false).getResponse();
476 public ResponseWithRequestInfo doAaiGet(String uri, boolean xml, boolean propagateExceptions) {
477 String methodName = "doAaiGet";
478 String transId = UUID.randomUUID().toString();
479 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
481 ResponseWithRequestInfo resp;
483 resp = restController.RestGet(fromAppId, transId, uri, xml, propagateExceptions);
485 } catch (Exception e) {
486 if (propagateExceptions) {
487 throw (e instanceof RuntimeException) ? (RuntimeException)e : new GenericUncheckedException(e);
489 final Exception actual =
490 e instanceof ExceptionWithRequestInfo ? (Exception) e.getCause() : e;
492 final String message =
493 actual instanceof WebApplicationException ? ((WebApplicationException) actual).getResponse().readEntity(String.class) : e.toString();
495 //ToDo: change parameter of requestUrl to real url from RestGet function
496 resp = new ResponseWithRequestInfo(null, null, org.springframework.http.HttpMethod.GET);
497 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
498 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
504 private String parseForTenantsByServiceSubscription(String resp) {
505 String tenantList = "";
508 JSONParser jsonParser = new JSONParser();
510 JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
512 return parseServiceSubscriptionObjectForTenants(jsonObject);
513 } catch (Exception ex) {
514 logger.debug(EELFLoggerDelegate.debugLogger, "parseForTenantsByServiceSubscription error while parsing tenants by service subscription", ex);
519 protected Response doAaiPut(String uri, String payload, boolean xml) {
520 String methodName = "doAaiPut";
521 String transId = UUID.randomUUID().toString();
522 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
524 Response resp = null;
527 resp = restController.RestPut(fromAppId, uri, payload, xml);
529 } catch (Exception e) {
530 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
531 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
537 private String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) {
538 JSONArray tenantArray = new JSONArray();
539 boolean bconvert = false;
541 JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");
542 if (relationShipListsObj != null) {
543 JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
544 for (Object innerObj : defaultIfNull(rShipArray, emptyList())) {
545 if (innerObj != null) {
546 bconvert = parseTenant(tenantArray, bconvert, (JSONObject) innerObj);
550 } catch (NullPointerException ex) {
551 logger.debug(EELFLoggerDelegate.debugLogger, "parseServiceSubscriptionObjectForTenants. error while parsing service subscription object for tenants", ex);
555 return tenantArray.toJSONString();
561 private static boolean parseTenant(JSONArray tenantArray, boolean bconvert, JSONObject inner1Obj) {
562 String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
563 if (relatedTo.equalsIgnoreCase("tenant")) {
564 JSONObject tenantNewObj = new JSONObject();
566 String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
567 tenantNewObj.put("link", relatedLink);
569 JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
570 for (Object innerObj : defaultIfNull(rDataArray, emptyList())) {
571 parseRelationShip(tenantNewObj, (JSONObject) innerObj);
574 JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
575 for (Object innerObj : defaultIfNull(relatedTPropArray, emptyList())) {
576 parseRelatedTProp(tenantNewObj, (JSONObject) innerObj);
579 tenantArray.add(tenantNewObj);
584 private static void parseRelatedTProp(JSONObject tenantNewObj, JSONObject innerObj) {
585 if (innerObj == null)
588 String propKey = checkForNull((String) innerObj.get("property-key"));
589 String propVal = checkForNull((String) innerObj.get("property-value"));
590 if (propKey.equalsIgnoreCase("tenant.tenant-name")) {
591 tenantNewObj.put("tenantName", propVal);
595 private static void parseRelationShip(JSONObject tenantNewObj, JSONObject inner2Obj) {
596 if (inner2Obj == null)
599 String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
600 String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
601 if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {
602 tenantNewObj.put("cloudOwner", rShipVal);
603 } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {
604 tenantNewObj.put("cloudRegionID", rShipVal);
607 if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {
608 tenantNewObj.put("tenantID", rShipVal);
612 private static String encodePathSegment(String segmentToEncode) {
614 return UriUtils.encodePathSegment(segmentToEncode, "UTF-8");
615 } catch (UnsupportedEncodingException e) {
616 throw new GenericUncheckedException("URI encoding failed unexpectedly", e);
621 public ExternalComponentStatus probeAaiGetAllSubscribers(){
622 long startTime = System.currentTimeMillis();
624 AaiResponseWithRequestInfo<SubscriberList> responseWithRequestInfo = getAllSubscribers(true);
625 AaiResponse<SubscriberList> aaiResponse = responseWithRequestInfo.getAaiResponse();
626 long duration = System.currentTimeMillis() - startTime;
628 SubscriberList subscribersList = (aaiResponse != null) ? aaiResponse.getT() : null;
629 boolean isAvailable = subscribersList != null && subscribersList.customer != null && !subscribersList.customer.isEmpty();
631 HttpRequestMetadata metadata = new HttpRequestMetadata(
632 responseWithRequestInfo.getHttpMethod(),
633 (aaiResponse != null) ? aaiResponse.getHttpCode() : 0,
634 responseWithRequestInfo.getRequestedUrl(),
635 StringUtils.substring(responseWithRequestInfo.getRawData(), 0, 500),
636 isAvailable ? "OK" : "No subscriber received",
639 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, isAvailable, metadata);
641 } catch (ExceptionWithRequestInfo e) {
642 long duration = System.currentTimeMillis() - startTime;
643 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
644 new HttpRequestMetadata(
646 defaultIfNull(e.getHttpCode(), 0),
649 Logging.exceptionToDescription(e.getCause()), duration));
650 } catch (Exception e) {
651 long duration = System.currentTimeMillis() - startTime;
652 return new ExternalComponentStatus(ExternalComponentStatus.Component.AAI, false,
653 new ErrorMetadata(Logging.exceptionToDescription(e), duration));