1 package org.onap.vid.aai;
3 import org.apache.http.HttpStatus;
4 import org.apache.http.client.utils.URIBuilder;
5 import org.codehaus.jackson.map.ObjectMapper;
6 import org.json.simple.JSONArray;
7 import org.json.simple.JSONObject;
8 import org.json.simple.parser.JSONParser;
9 import org.onap.vid.aai.util.AAIRestInterface;
10 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
11 import org.onap.vid.aai.model.AaiGetAicZone.AicZones;
12 import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
13 import org.onap.vid.aai.model.*;
14 import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
15 import org.onap.vid.aai.model.AaiGetServicesRequestModel.GetServicesAAIRespone;
16 import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
17 import org.onap.vid.model.SubscriberList;
18 import org.springframework.beans.factory.annotation.Autowired;
19 import org.springframework.web.util.UriUtils;
21 import javax.servlet.ServletContext;
22 import javax.ws.rs.BadRequestException;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.core.Response;
26 import java.io.IOException;
27 import java.io.UnsupportedEncodingException;
28 import java.net.URLEncoder;
29 import java.text.DateFormat;
30 import java.text.SimpleDateFormat;
31 import java.util.Date;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.UUID;
38 * Created by Oren on 7/4/17.
40 public class AaiClient implements AaiClientInterface {
43 * The Constant dateFormat.
45 final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
46 protected String fromAppId = "VidAaiController";
48 ServletContext servletContext;
53 EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiClient.class);
54 private final String getServiceModelsResponseBody = "{\"start\" : \"service-design-and-creation/models/\", \"query\" : \"query/serviceModels-byDistributionStatus?distributionStatus=DISTRIBUTION_COMPLETE_OK\"}";
57 // certiPath = getCertificatesFile().getAbsolutePath();
61 public AaiClient(ServletContext context) {
62 servletContext = context;
66 private static String checkForNull(String local) {
75 public AaiResponse getServicesByOwningEntityId(List<String> owningEntityIds){
76 File certiPath = getCertificatesFile();
77 Response resp = doAaiGet(certiPath.getAbsolutePath(), getUrlFromLIst("business/owning-entities?", "owning-entity-id=", owningEntityIds), false);
78 AaiResponse aaiResponse = proccessAaiResponse(resp, OwningEntityResponse.class, null);
84 public AaiResponse getServicesByProjectNames(List<String> projectNames){
85 File certiPath = getCertificatesFile();
86 Response resp = doAaiGet(certiPath.getAbsolutePath(), getUrlFromLIst("business/projects?", "project-name=", projectNames), false);
87 AaiResponse aaiResponse = proccessAaiResponse(resp, ProjectResponse.class, null);
93 public AaiResponse getServiceModelsByDistributionStatus() {
94 File certiPath = getCertificatesFile();
95 Response resp = doAaiPut(certiPath.getAbsolutePath(), "query?format=resource", getServiceModelsResponseBody, false);
96 AaiResponse aaiResponse = proccessAaiResponse(resp, GetServiceModelsByDistributionStatusResponse.class, null);
102 public AaiResponse getPNFData(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion, String equipVendor, String equipModel) {
103 String certiPath = getCertificatesFile().getAbsolutePath();
104 String siQuery = "/business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + "&model-invariant-id=" + modelInvariantId;
105 String pnfQuery = "query/pnf-fromModel-byRegion?cloudRegionId=" + encodePathSegment(cloudRegion) + "&equipVendor=" + encodePathSegment(equipVendor) + "&equipModel=" + encodePathSegment(equipModel);
106 String payload = "{\"start\":\"" + siQuery + "\",\"query\":\"" + pnfQuery + "\"}";
107 Response resp = doAaiPut(certiPath, "query?format=simple", payload, false);
108 return proccessAaiResponse(resp, AaiGetPnfResponse.class, null);
113 public AaiResponse<Pnf> getSpecificPnf(String pnfId) {
114 File certiPath = getCertificatesFile();
115 Response resp = doAaiGet(certiPath.getAbsolutePath(), "network/pnfs/pnf/"+pnfId, false);
116 AaiResponse aaiResponse = proccessAaiResponse(resp, Pnf.class, null);
121 public AaiResponse getServiceInstance(String globalCustomerId, String serviceType, String serviceInstanceId) {
122 String certiPath = getCertificatesFile().getAbsolutePath();
123 String getServiceInstancePath = "business/customers/customer/"+globalCustomerId+"/service-subscriptions/service-subscription/"+serviceType+"/service-instances/service-instance/"+serviceInstanceId;
124 Response resp = doAaiGet(certiPath , getServiceInstancePath , false);
125 return proccessAaiResponse(resp, ServiceRelationships.class, null);
129 public AaiResponse getLogicalLink(String link) {
130 String certiPath = getCertificatesFile().getAbsolutePath();
131 Response resp = doAaiGet(certiPath , "network/logical-links/logical-link/" + link , false);
132 return proccessAaiResponse(resp, LogicalLinkResponse.class, null);
135 private String getUrlFromLIst(String url, String paramKey, List<String> params){
136 url.concat(paramKey);
138 for(String param: params){
140 url = url.concat(paramKey);
141 String encodedParam= param;
143 encodedParam= URLEncoder.encode(param, "UTF-8");
144 } catch (UnsupportedEncodingException e) {
145 String methodName = "getUrlFromList";
146 logger.error(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
147 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
149 url = url.concat(encodedParam);
150 if(i != params.size()){
151 url = url.concat("&");
159 public AaiResponse<SubscriberList> getAllSubscribers() {
160 String certiPath = getCertificatesFile().getAbsolutePath();
162 Response resp = doAaiGet(certiPath, "business/customers?subscriber-type=INFRA&depth=" + depth, false);
163 return proccessAaiResponse(resp, SubscriberList.class, null);
168 public AaiResponse getAllAicZones() {
169 String certiPath = getCertificatesFile().getAbsolutePath();
170 Response resp = doAaiGet(certiPath, "network/zones", false);
171 AaiResponse aaiAicZones = proccessAaiResponse(resp, AicZones.class, null);
177 public AaiResponse<String> getAicZoneForPnf(String globalCustomerId , String serviceType , String serviceId) {
178 String certiPath = getCertificatesFile().getAbsolutePath();
179 String aicZonePath = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId;
180 Response resp = doAaiGet(certiPath , aicZonePath , false);
181 AaiResponse<ServiceRelationships> aaiResponse = proccessAaiResponse(resp , ServiceRelationships.class , null);
182 ServiceRelationships serviceRelationships = (ServiceRelationships)aaiResponse.getT();
183 RelationshipList relationshipList = serviceRelationships.getRelationshipList();
184 Relationship relationship = relationshipList.getRelationship().get(0);
185 RelationshipData relationshipData= relationship.getRelationDataList().get(0);
186 String aicZone = relationshipData.getRelationshipValue();
187 AaiResponse<String> aaiAicZonaForPnfResponse = new AaiResponse(aicZone , null ,HttpStatus.SC_OK);
188 return aaiAicZonaForPnfResponse;
193 public AaiResponse getVNFData() {
194 String certiPath = getCertificatesFile().getAbsolutePath();
195 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\"}";
196 Response resp = doAaiPut(certiPath, "query?format=simple", payload, false);
197 return proccessAaiResponse(resp, AaiGetVnfResponse.class, null);
202 public Response getVNFData(String globalSubscriberId, String serviceType) {
203 String certiPath = getCertificatesFile().getAbsolutePath();
204 String payload = "{\"start\": [\"business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/"+ encodePathSegment(serviceType) +"/service-instances\"]," +
205 "\"query\": \"query/vnf-topology-fromServiceInstance\"}";
206 return doAaiPut(certiPath, "query?format=simple", payload, false);
211 public AaiResponse getVNFData(String globalSubscriberId, String serviceType, String serviceInstanceId) {
212 String certiPath = getCertificatesFile().getAbsolutePath();
213 String payload = "{\"start\": [\"/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + encodePathSegment(serviceType) + "/service-instances/service-instance/" + serviceInstanceId + "\"], \"query\": \"query/vnf-topology-fromServiceInstance\"}";
214 Response resp = doAaiPut(certiPath, "query?format=simple", payload, false);
215 return proccessAaiResponse(resp, AaiGetVnfResponse.class, null);
219 public Response getVersionByInvariantId(List<String> modelInvariantId) {
220 File certiPath = getCertificatesFile();
221 StringBuilder sb = new StringBuilder();
222 for (String id : modelInvariantId){
223 sb.append("&model-invariant-id=");
227 Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/models?depth=2"+ sb.toString(), false);
232 public AaiResponse getSubscriberData(String subscriberId) {
233 File certiPath = getCertificatesFile();
235 AaiResponse subscriberDataResponse;
236 Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId + "?depth=" + depth, false);
237 subscriberDataResponse = proccessAaiResponse(resp, Services.class, null);
238 return subscriberDataResponse;
242 public AaiResponse getServices() {
243 File certiPath = getCertificatesFile();
244 Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/services", false);
245 AaiResponse<GetServicesAAIRespone> getServicesResponse = proccessAaiResponse(resp, GetServicesAAIRespone.class, null);
247 return getServicesResponse;
251 public AaiResponse getOperationalEnvironments(String operationalEnvironmentType, String operationalEnvironmentStatus) {
252 File certiPath = getCertificatesFile();
253 String url = "cloud-infrastructure/operational-environments";
254 URIBuilder urlBuilder = new URIBuilder();
255 if (operationalEnvironmentType != null)
256 urlBuilder.addParameter("operational-environment-type", operationalEnvironmentType);
257 if (operationalEnvironmentStatus != null)
258 urlBuilder.addParameter("operational-environment-status", operationalEnvironmentStatus);
259 url += urlBuilder.toString();
260 Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false);
261 AaiResponse<OperationalEnvironmentList> getOperationalEnvironmentsResponse = proccessAaiResponse(resp, OperationalEnvironmentList.class, null);
262 return getOperationalEnvironmentsResponse;
267 public AaiResponse getTenants(String globalCustomerId, String serviceType) {
268 File certiPath = getCertificatesFile();
269 String url = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType;
271 Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false);
272 String responseAsString = parseForTenantsByServiceSubscription(resp.readEntity(String.class));
273 if (responseAsString.equals("")){
274 AaiResponse aaiResponse = 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);
278 AaiResponse<GetTenantsResponse[]> getTenantsResponse = proccessAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
279 return getTenantsResponse;
285 public AaiResponse getNodeTemplateInstances(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion) {
287 String certiPath = getCertificatesFile().getAbsolutePath();
289 String siQuery = "/business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + encodePathSegment(serviceType) + "/service-instances?model-version-id=" + modelVersionId + "&model-invariant-id=" + modelInvariantId;
290 String vnfQuery = "query/queryvnfFromModelbyRegion?cloudRegionId=" + encodePathSegment(cloudRegion);
291 String payload1 = "{\"start\":\"" + siQuery + "\",\"query\":\"" + vnfQuery + "\"}";
293 Response resp1 = doAaiPut(certiPath, "query?format=simple", payload1, false);
294 AaiResponse aaiResponse1 = proccessAaiResponse(resp1, AaiGetVnfResponse.class, null);
295 logger.debug(EELFLoggerDelegate.debugLogger, "getNodeTemplateInstances AAI's response: {}", aaiResponse1);
299 private AaiResponse proccessAaiResponse(Response resp, Class classType, String responseBody) {
300 AaiResponse subscriberDataResponse = null;
302 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
303 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI");
305 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString());
306 if (resp.getStatus() != HttpStatus.SC_OK) {
307 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "Invalid response from AAI");
308 subscriberDataResponse = new AaiResponse<>(null, resp.readEntity(String.class), resp.getStatus());
310 String finalResponse = null;
312 if (responseBody != null) {
313 finalResponse = responseBody;
315 finalResponse = resp.readEntity(String.class);
318 subscriberDataResponse = new AaiResponse<>((new ObjectMapper().readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
320 } catch(Exception e){
321 subscriberDataResponse = new AaiResponse<>(null, null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
322 logger.error("Failed to parse aai response: \"{}\" to class {}", finalResponse, classType, e);
326 return subscriberDataResponse;
329 private File getCertificatesFile() {
330 if (servletContext != null)
331 return new File(servletContext.getRealPath("/WEB-INF/cert/"));
335 @SuppressWarnings("all")
336 public Response doAaiGet(String certiPath, String uri, boolean xml) {
337 String methodName = "doAaiGet";
338 String transId = UUID.randomUUID().toString();
339 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
341 Response resp = null;
344 AAIRestInterface restContrller = new AAIRestInterface(certiPath);
345 resp = restContrller.RestGet(fromAppId, transId, uri, xml);
347 } catch (WebApplicationException e) {
348 final String message = ((BadRequestException) e).getResponse().readEntity(String.class);
349 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
350 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
351 } catch (Exception e) {
352 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
353 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
359 private String parseForTenantsByServiceSubscription(String resp) {
360 String tenantList = "";
363 JSONParser jsonParser = new JSONParser();
365 JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
367 return parseServiceSubscriptionObjectForTenants(jsonObject);
368 } catch (Exception ex) {
375 protected Response doAaiPut(String certiPath, String uri, String payload, boolean xml) {
376 String methodName = "doAaiPut";
377 String transId = UUID.randomUUID().toString();
378 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");
380 Response resp = null;
383 AAIRestInterface restContrller = new AAIRestInterface(certiPath);
384 resp = restContrller.RestPut(fromAppId, transId, uri, payload, xml);
386 } catch (Exception e) {
387 logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
388 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
395 public static String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) {
397 JSONArray tenantArray = new JSONArray();
398 boolean bconvert = false;
401 JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");
402 if (relationShipListsObj != null) {
403 JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");
404 if (rShipArray != null) {
405 Iterator i1 = rShipArray.iterator();
407 while (i1.hasNext()) {
409 JSONObject inner1Obj = (JSONObject) i1.next();
411 if (inner1Obj == null)
414 String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
415 if (relatedTo.equalsIgnoreCase("tenant")) {
416 JSONObject tenantNewObj = new JSONObject();
418 String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
419 tenantNewObj.put("link", relatedLink);
421 JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
422 if (rDataArray != null) {
423 Iterator i2 = rDataArray.iterator();
425 while (i2.hasNext()) {
426 JSONObject inner2Obj = (JSONObject) i2.next();
428 if (inner2Obj == null)
431 String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));
432 String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));
433 if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {
434 tenantNewObj.put("cloudOwner", rShipVal);
435 } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {
436 tenantNewObj.put("cloudRegionID", rShipVal);
439 if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {
440 tenantNewObj.put("tenantID", rShipVal);
445 JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
446 if (relatedTPropArray != null) {
447 Iterator i3 = relatedTPropArray.iterator();
449 while (i3.hasNext()) {
450 JSONObject inner3Obj = (JSONObject) i3.next();
452 if (inner3Obj == null)
455 String propKey = checkForNull((String) inner3Obj.get("property-key"));
456 String propVal = checkForNull((String) inner3Obj.get("property-value"));
457 if (propKey.equalsIgnoreCase("tenant.tenant-name")) {
458 tenantNewObj.put("tenantName", propVal);
463 tenantArray.add(tenantNewObj);
469 } catch (NullPointerException ex) {
475 return tenantArray.toJSONString();
481 private static String encodePathSegment(String segmentToEncode) {
483 return UriUtils.encodePathSegment(segmentToEncode, "UTF-8");
484 } catch (UnsupportedEncodingException e) {
485 throw new RuntimeException("URI encoding failed unexpectedly", e);