org.onap migration
[vid.git] / vid-app-common / src / main / java / org / onap / vid / aai / AaiClient.java
1 package org.onap.vid.aai;
2
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;
20
21 import javax.servlet.ServletContext;
22 import javax.ws.rs.BadRequestException;
23 import javax.ws.rs.WebApplicationException;
24 import javax.ws.rs.core.Response;
25 import java.io.File;
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;
35
36 /**
37
38  * Created by Oren on 7/4/17.
39  */
40 public class AaiClient implements AaiClientInterface {
41
42     /**
43      * The Constant dateFormat.
44      */
45     final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
46     protected String fromAppId = "VidAaiController";
47     @Autowired
48     ServletContext servletContext;
49     /**
50      * The logger
51      */
52
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\"}";
55
56     public AaiClient() {
57         //        certiPath = getCertificatesFile().getAbsolutePath();
58         //        depth = "0";
59     }
60
61     public AaiClient(ServletContext context) {
62         servletContext = context;
63     }
64
65
66     private static String checkForNull(String local) {
67         if (local != null)
68             return local;
69         else
70             return "";
71
72     }
73
74     @Override
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);
79
80         return aaiResponse;
81     }
82
83     @Override
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);
88
89         return aaiResponse;
90     }
91
92     @Override
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);
97
98         return aaiResponse;
99     }
100
101     @Override
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);
109     }
110
111
112     @Override
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);
117
118         return aaiResponse;
119     }
120
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);
126     }
127
128     @Override
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);
133     }
134
135     private String getUrlFromLIst(String url, String paramKey, List<String> params){
136         url.concat(paramKey);
137         int i = 0;
138         for(String param: params){
139             i ++;
140             url = url.concat(paramKey);
141             String encodedParam= param;
142             try {
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());
148             }
149             url = url.concat(encodedParam);
150             if(i != params.size()){
151                 url = url.concat("&");
152             }
153         }
154         return url;
155     }
156
157
158     @Override
159     public AaiResponse<SubscriberList> getAllSubscribers() {
160         String certiPath = getCertificatesFile().getAbsolutePath();
161         String depth = "0";
162         Response resp = doAaiGet(certiPath, "business/customers?subscriber-type=INFRA&depth=" + depth, false);
163         return proccessAaiResponse(resp, SubscriberList.class, null);
164     }
165
166
167     @Override
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);
172         return aaiAicZones;
173     }
174
175
176     @Override
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;
189     }
190
191
192     @Override
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);
198
199     }
200
201     @Override
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);
207
208     }
209
210     @Override
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);
216     }
217
218     @Override
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=");
224             sb.append(id);
225
226         }
227         Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/models?depth=2"+ sb.toString(), false);
228         return resp;
229     }
230
231     @Override
232     public AaiResponse getSubscriberData(String subscriberId) {
233         File certiPath = getCertificatesFile();
234         String depth = "2";
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;
239     }
240
241     @Override
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);
246
247         return getServicesResponse;
248     }
249
250     @Override
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;
263
264     }
265
266     @Override
267     public AaiResponse getTenants(String globalCustomerId, String serviceType) {
268         File certiPath = getCertificatesFile();
269         String url = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType;
270
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);
275             return  aaiResponse;
276         }
277         else {
278             AaiResponse<GetTenantsResponse[]> getTenantsResponse = proccessAaiResponse(resp, GetTenantsResponse[].class, responseAsString);
279             return getTenantsResponse;
280         }
281
282     }
283
284     @Override
285     public AaiResponse getNodeTemplateInstances(String globalCustomerId, String serviceType, String modelVersionId, String modelInvariantId, String cloudRegion) {
286
287         String certiPath = getCertificatesFile().getAbsolutePath();
288
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 + "\"}";
292
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);
296         return aaiResponse1;
297     }
298
299     private AaiResponse proccessAaiResponse(Response resp, Class classType, String responseBody) {
300         AaiResponse subscriberDataResponse = null;
301         if (resp == 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");
304         } else {
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());
309             } else {
310                 String finalResponse = null;
311                 try {
312                     if (responseBody != null) {
313                         finalResponse = responseBody;
314                     } else {
315                         finalResponse = resp.readEntity(String.class);
316                     }
317
318                     subscriberDataResponse = new AaiResponse<>((new ObjectMapper().readValue(finalResponse, classType)), null, HttpStatus.SC_OK);
319
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);
323                 }
324             }
325         }
326         return subscriberDataResponse;
327     }
328
329     private File getCertificatesFile() {
330         if (servletContext != null)
331             return new File(servletContext.getRealPath("/WEB-INF/cert/"));
332         return null;
333     }
334
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");
340
341         Response resp = null;
342         try {
343
344             AAIRestInterface restContrller = new AAIRestInterface(certiPath);
345             resp = restContrller.RestGet(fromAppId, transId, uri, xml);
346
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());
354         }
355
356         return resp;
357     }
358
359     private String parseForTenantsByServiceSubscription(String resp) {
360         String tenantList = "";
361
362         try {
363             JSONParser jsonParser = new JSONParser();
364
365             JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);
366
367             return parseServiceSubscriptionObjectForTenants(jsonObject);
368         } catch (Exception ex) {
369
370         }
371
372         return tenantList;
373     }
374
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");
379
380         Response resp = null;
381         try {
382
383             AAIRestInterface restContrller = new AAIRestInterface(certiPath);
384             resp = restContrller.RestPut(fromAppId, transId, uri, payload, xml);
385
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());
389         }
390
391         return resp;
392     }
393
394
395     public static String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) {
396
397         JSONArray tenantArray = new JSONArray();
398         boolean bconvert = false;
399
400         try {
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();
406
407                     while (i1.hasNext()) {
408
409                         JSONObject inner1Obj = (JSONObject) i1.next();
410
411                         if (inner1Obj == null)
412                             continue;
413
414                         String relatedTo = checkForNull((String) inner1Obj.get("related-to"));
415                         if (relatedTo.equalsIgnoreCase("tenant")) {
416                             JSONObject tenantNewObj = new JSONObject();
417
418                             String relatedLink = checkForNull((String) inner1Obj.get("related-link"));
419                             tenantNewObj.put("link", relatedLink);
420
421                             JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");
422                             if (rDataArray != null) {
423                                 Iterator i2 = rDataArray.iterator();
424
425                                 while (i2.hasNext()) {
426                                     JSONObject inner2Obj = (JSONObject) i2.next();
427
428                                     if (inner2Obj == null)
429                                         continue;
430
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);
437                                     }
438
439                                     if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {
440                                         tenantNewObj.put("tenantID", rShipVal);
441                                     }
442                                 }
443                             }
444
445                             JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");
446                             if (relatedTPropArray != null) {
447                                 Iterator i3 = relatedTPropArray.iterator();
448
449                                 while (i3.hasNext()) {
450                                     JSONObject inner3Obj = (JSONObject) i3.next();
451
452                                     if (inner3Obj == null)
453                                         continue;
454
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);
459                                     }
460                                 }
461                             }
462                             bconvert = true;
463                             tenantArray.add(tenantNewObj);
464                         }
465                     }
466
467                 }
468             }
469         } catch (NullPointerException ex) {
470
471
472         }
473
474         if (bconvert)
475             return tenantArray.toJSONString();
476         else
477             return "";
478
479     }
480
481     private static String encodePathSegment(String segmentToEncode) {
482         try {
483             return UriUtils.encodePathSegment(segmentToEncode, "UTF-8");
484         } catch (UnsupportedEncodingException e) {
485             throw new RuntimeException("URI encoding failed unexpectedly", e);
486         }
487     }
488
489 }