AAI Query optimization for VID
[vid.git] / vid-app-common / src / main / java / org / onap / vid / controller / AaiController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * VID
4  * ================================================================================
5  * Copyright (C) 2017 - 2019 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2019 Nokia.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.vid.controller;
23
24 import static org.onap.vid.utils.Logging.getMethodName;
25
26 import com.fasterxml.jackson.databind.ObjectMapper;
27 import java.io.IOException;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Optional;
31 import java.util.UUID;
32 import java.util.stream.Collectors;
33 import javax.servlet.http.HttpServletRequest;
34 import javax.ws.rs.DefaultValue;
35 import javax.ws.rs.QueryParam;
36 import javax.ws.rs.WebApplicationException;
37 import javax.ws.rs.core.Response;
38 import org.apache.commons.lang3.tuple.ImmutablePair;
39 import org.apache.commons.lang3.tuple.Pair;
40 import org.onap.portalsdk.core.controller.RestrictedBaseController;
41 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
42 import org.onap.vid.aai.AaiResponse;
43 import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData;
44 import org.onap.vid.aai.ServiceInstancesSearchResults;
45 import org.onap.vid.aai.SubscriberFilteredResults;
46 import org.onap.vid.aai.model.AaiGetInstanceGroupsByCloudRegion;
47 import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
48 import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
49 import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
50 import org.onap.vid.aai.util.AAIRestInterface;
51 import org.onap.vid.model.VersionByInvariantIdsRequest;
52 import org.onap.vid.properties.Features;
53 import org.onap.vid.roles.RoleProvider;
54 import org.onap.vid.roles.RoleValidator;
55 import org.onap.vid.services.AaiService;
56 import org.onap.vid.utils.SystemPropertiesWrapper;
57 import org.onap.vid.utils.Unchecked;
58 import org.springframework.beans.factory.annotation.Autowired;
59 import org.springframework.http.HttpStatus;
60 import org.springframework.http.MediaType;
61 import org.springframework.http.ResponseEntity;
62 import org.springframework.web.bind.annotation.PathVariable;
63 import org.springframework.web.bind.annotation.RequestBody;
64 import org.springframework.web.bind.annotation.RequestMapping;
65 import org.springframework.web.bind.annotation.RequestMethod;
66 import org.springframework.web.bind.annotation.RequestParam;
67 import org.springframework.web.bind.annotation.RestController;
68 import org.springframework.web.servlet.HandlerMapping;
69 import org.springframework.web.servlet.ModelAndView;
70 import org.togglz.core.manager.FeatureManager;
71
72 import org.json.JSONException;
73 import org.json.JSONObject;
74 import org.json.simple.JSONArray;
75 import org.json.simple.parser.JSONParser;
76 import org.json.simple.parser.ParseException;
77 import org.onap.vid.aai.CustomerSpecificServiceInstance;
78 import org.onap.vid.aai.DSLQuerySimpleResponse;
79 import org.onap.vid.aai.model.ServiceRelationships;
80 import org.onap.vid.aai.model.ViewEditSIResult;
81
82
83 @RestController
84 public class AaiController extends RestrictedBaseController {
85
86     private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AaiController.class);
87     private static final String FROM_APP_ID = "VidAaiController";
88     private final ObjectMapper objectMapper = new ObjectMapper();
89
90     private AaiService aaiService;
91     private AAIRestInterface aaiRestInterface;
92     private RoleProvider roleProvider;
93     private SystemPropertiesWrapper systemPropertiesWrapper;
94     private FeatureManager featureManager;
95
96
97     @Autowired
98     public AaiController(AaiService aaiService,
99         AAIRestInterface aaiRestInterface,
100         RoleProvider roleProvider,
101         SystemPropertiesWrapper systemPropertiesWrapper,
102         FeatureManager featureManager
103     ) {
104
105         this.aaiService = aaiService;
106         this.aaiRestInterface = aaiRestInterface;
107         this.roleProvider = roleProvider;
108         this.systemPropertiesWrapper = systemPropertiesWrapper;
109         this.featureManager = featureManager;
110     }
111
112     @RequestMapping(value = {"/subscriberSearch"}, method = RequestMethod.GET)
113     public ModelAndView welcome() {
114         LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== AaiController welcome start");
115         return new ModelAndView(getViewName());
116     }
117
118     @RequestMapping(value = {"/aai_get_aic_zones"}, method = RequestMethod.GET)
119     public ResponseEntity<String> getAicZones() throws IOException {
120         LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== getAicZones controller start");
121         AaiResponse response = aaiService.getAaiZones();
122         return aaiResponseToResponseEntity(response);
123     }
124
125     @RequestMapping(value = {
126         "/aai_get_aic_zone_for_pnf/{globalCustomerId}/{serviceType}/{serviceId}"}, method = RequestMethod.GET)
127     public ResponseEntity<String> getAicZoneForPnf(@PathVariable("globalCustomerId") String globalCustomerId,
128         @PathVariable("serviceType") String serviceType, @PathVariable("serviceId") String serviceId) throws IOException {
129         LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== getAicZoneForPnf controller start");
130         AaiResponse response = aaiService.getAicZoneForPnf(globalCustomerId, serviceType, serviceId);
131         return aaiResponseToResponseEntity(response);
132     }
133
134     @RequestMapping(value = {"/aai_get_instance_groups_by_vnf_instance_id/{vnfInstanceId}"}, method = RequestMethod.GET)
135     public ResponseEntity<String> getInstanceGroupsByVnfInstanceId(@PathVariable("vnfInstanceId") String vnfInstanceId) throws IOException {
136         AaiResponse response = aaiService.getInstanceGroupsByVnfInstanceId(vnfInstanceId);
137         return aaiResponseToResponseEntity(response);
138     }
139
140     @RequestMapping(value = {"/getuserID"}, method = RequestMethod.GET)
141     public ResponseEntity<String> getUserID(HttpServletRequest request) {
142
143         String userId = new ControllersUtils(systemPropertiesWrapper).extractUserId(request);
144
145         return new ResponseEntity<>(userId, HttpStatus.OK);
146     }
147
148     @RequestMapping(value = "/aai_get_services", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
149     public ResponseEntity<String> doGetServices(HttpServletRequest request) throws IOException {
150         RoleValidator roleValidator = roleProvider.getUserRolesValidator(request);
151
152         AaiResponse subscriberList = aaiService.getServices(roleValidator);
153         return aaiResponseToResponseEntity(subscriberList);
154     }
155
156
157     @RequestMapping(value = {"/aai_get_version_by_invariant_id"}, method = RequestMethod.POST)
158     public ResponseEntity<String> getVersionByInvariantId(@RequestBody VersionByInvariantIdsRequest versions) {
159         Response result = aaiService.getVersionByInvariantId(versions.versions);
160
161         return new ResponseEntity<>(result.readEntity(String.class), HttpStatus.OK);
162     }
163
164
165     private ResponseEntity<String> aaiResponseToResponseEntity(AaiResponse aaiResponseData)
166         throws IOException {
167         ResponseEntity<String> responseEntity;
168         if (aaiResponseData.getHttpCode() == 200) {
169             responseEntity = new ResponseEntity<>(objectMapper.writeValueAsString(aaiResponseData.getT()),
170                 HttpStatus.OK);
171         } else {
172             responseEntity = new ResponseEntity<>(aaiResponseData.getErrorMessage(),
173                 HttpStatus.valueOf(aaiResponseData.getHttpCode()));
174         }
175
176         return responseEntity;
177     }
178
179     @RequestMapping(value = "/aai_get_service_instance/{service-instance-id}/{service-instance-type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
180     public ResponseEntity<String> doGetServiceInstance(@PathVariable("service-instance-id") String serviceInstanceId,
181         @PathVariable("service-instance-type") String serviceInstanceType) {
182         Response resp = null;
183
184         if (serviceInstanceType.equalsIgnoreCase("Service Instance Id")) {
185             resp = doAaiGet(
186                 "search/nodes-query?search-node-type=service-instance&filter=service-instance-id:EQUALS:"
187                     + serviceInstanceId, false);
188         } else {
189             resp = doAaiGet(
190                 "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:"
191                     + serviceInstanceId, false);
192         }
193         return convertResponseToResponseEntity(resp);
194     }
195
196     @RequestMapping(value = "/aai_get_service_subscription/{global-customer-id}/{service-subscription-id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
197     public ResponseEntity<String> doGetServices(@PathVariable("global-customer-id") String globalCustomerId,
198         @PathVariable("service-subscription-id") String serviceSubscriptionId) {
199         Response resp = doAaiGet("business/customers/customer/" + globalCustomerId
200             + "/service-subscriptions/service-subscription/" + serviceSubscriptionId + "?depth=0", false);
201         return convertResponseToResponseEntity(resp);
202     }
203
204     @RequestMapping(value = "/aai_get_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
205     public ResponseEntity<String> doGetSubscriberList(HttpServletRequest request,
206         @DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException {
207         return getFullSubscriberList(request);
208     }
209
210     @RequestMapping(value = "/get_system_prop_vnf_prov_status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
211     public ResponseEntity<String> getTargetProvStatus() {
212         String p = systemPropertiesWrapper.getProperty("aai.vnf.provstatus");
213         return new ResponseEntity<>(p, HttpStatus.OK);
214     }
215
216     @RequestMapping(value = "/get_operational_environments", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
217     public AaiResponse<OperationalEnvironmentList> getOperationalEnvironments(
218         @RequestParam(value = "operationalEnvironmentType", required = false) String operationalEnvironmentType,
219         @RequestParam(value = "operationalEnvironmentStatus", required = false) String operationalEnvironmentStatus) {
220         LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({}, {})", getMethodName(), operationalEnvironmentType,
221             operationalEnvironmentStatus);
222         AaiResponse<OperationalEnvironmentList> response = aaiService
223             .getOperationalEnvironments(operationalEnvironmentType, operationalEnvironmentStatus);
224         if (response.getHttpCode() != 200) {
225             String errorMessage = getAaiErrorMessage(response.getErrorMessage());
226             if (errorMessage != null) {
227                 response = new AaiResponse<>(response.getT(), errorMessage, response.getHttpCode());
228             }
229         }
230
231         LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), response);
232         return response;
233     }
234
235     @RequestMapping(value = "/aai_get_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
236     public ResponseEntity<String> getFullSubscriberList(HttpServletRequest request) throws IOException {
237         ResponseEntity<String> responseEntity;
238         RoleValidator roleValidator = roleProvider.getUserRolesValidator(request);
239         SubscriberFilteredResults subscriberList = aaiService.getFullSubscriberList(roleValidator);
240         if (subscriberList.getHttpCode() == 200) {
241             responseEntity = new ResponseEntity<>(objectMapper.writeValueAsString(subscriberList.getSubscriberList()),
242                 HttpStatus.OK);
243         } else {
244             responseEntity = new ResponseEntity<>(subscriberList.getErrorMessage(),
245                 HttpStatus.valueOf(subscriberList.getHttpCode()));
246         }
247
248         return responseEntity;
249     }
250
251     @RequestMapping(value = "/aai_refresh_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
252     public ResponseEntity<String> doRefreshSubscriberList() {
253         return refreshSubscriberList();
254     }
255
256     @RequestMapping(value = "/aai_refresh_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
257     public ResponseEntity<String> doRefreshFullSubscriberList() {
258         return refreshSubscriberList();
259     }
260
261     protected ResponseEntity<String> refreshSubscriberList() {
262         Response resp = getSubscribers();
263         return convertResponseToResponseEntity(resp);
264     }
265
266     @RequestMapping(value = "/aai_sub_details/{subscriberId}", method = RequestMethod.GET)
267     public ResponseEntity<String> getSubscriberDetails(HttpServletRequest request, @PathVariable("subscriberId") String subscriberId,
268                                                        @RequestParam(value="omitServiceInstances", required = false, defaultValue = "false") boolean omitServiceInstances) throws IOException {
269         RoleValidator roleValidator = roleProvider.getUserRolesValidator(request);
270         AaiResponse subscriberData = aaiService.getSubscriberData(subscriberId, roleValidator,
271             featureManager.isActive(Features.FLAG_1906_AAI_SUB_DETAILS_REDUCE_DEPTH) && omitServiceInstances);
272         String httpMessage = subscriberData.getT() != null ? objectMapper.writeValueAsString(subscriberData.getT()) : subscriberData.getErrorMessage();
273
274         return new ResponseEntity<>(httpMessage,
275             HttpStatus.valueOf(subscriberData.getHttpCode()));
276     }
277
278     @RequestMapping(value = "/search_service_instances", method = RequestMethod.GET)
279     public ResponseEntity<String> SearchServiceInstances(HttpServletRequest request,
280         @RequestParam(value = "subscriberId", required = false) String subscriberId,
281         @RequestParam(value = "serviceInstanceIdentifier", required = false) String instanceIdentifier,
282         @RequestParam(value = "serviceInstanceIdentifierType", required = false) String instanceIdentifierType,
283         @RequestParam(value = "project", required = false) List<String> projects,
284         @RequestParam(value = "owningEntity", required = false) List<String> owningEntities) throws IOException {
285         ResponseEntity responseEntity;
286
287         RoleValidator roleValidator = roleProvider.getUserRolesValidator(request);
288
289         AaiResponse<ServiceInstancesSearchResults> searchResult = null;
290
291         if( instanceIdentifier != null && isValidInstanceIdentifierType(instanceIdentifierType)) {
292             LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== search_service_instances search by subscriberId "
293                 + " instanceIdentifier and instanceIdentifierType start");
294             searchResult = aaiService
295                 .getServiceInstanceSearchResultsByIdentifierType(subscriberId, instanceIdentifier,
296                     instanceIdentifierType, roleValidator, owningEntities, projects);
297         } else {
298             LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== search_service_instances search by subscriberId "
299                 + "instanceIdentifier instanceIdentifier and instanceIdentifierType start");
300             searchResult = aaiService
301                 .getServiceInstanceSearchResults(subscriberId, instanceIdentifier, roleValidator, owningEntities, projects);
302         }
303
304         String httpMessage = searchResult.getT() != null ?
305             objectMapper.writeValueAsString(searchResult.getT()) :
306             searchResult.getErrorMessage();
307
308         if (searchResult.getT().serviceInstances.isEmpty()) {
309             responseEntity = new ResponseEntity<>(httpMessage, HttpStatus.NOT_FOUND);
310
311         } else {
312             responseEntity = new ResponseEntity<>(httpMessage, HttpStatus.valueOf(searchResult.getHttpCode()));
313
314         }
315         return responseEntity;
316     }
317
318     @RequestMapping(value = {
319         "/aai_get_service_instance_by_id_and_type/{globalCustomerId}/{serviceInstanceIdentifier}/{serviceIdentifierType}/{subscriberName}",
320         "/aai_get_service_instance_by_id_and_type/{globalCustomerId}/{serviceInstanceIdentifier}/{serviceIdentifierType}"},
321         method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
322     public ResponseEntity<String> doGetServiceInstanceByIdAndType(
323         @PathVariable("globalCustomerId") String globalCustomerId,
324         @PathVariable("serviceInstanceIdentifier") String serviceInstanceIdentifier,
325         @PathVariable("serviceIdentifierType") String serviceIdentifierType,
326         @PathVariable("subscriberName") java.util.Optional<String> subscriberName) throws IOException {
327
328         AaiResponse aaiResponse = null;
329         String orchStatus = null;
330         String siid, siName, modelVerId, modelInvId = null;
331         String errorMessage = null;
332         int statusCode = -1;
333         ViewEditSIResult viewEditSIResult = new ViewEditSIResult();
334         if(!subscriberName.equals(Optional.empty()) && serviceInstanceIdentifier != null) {
335             LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + ".aai_get_service_instance_by_id_and_type. "
336                 + "Search node query to get Service Type: "+serviceInstanceIdentifier);
337             ResponseEntity entity = convertResponseToResponseEntity(doAaiGet(
338                 "search/nodes-query?search-node-type=service-instance&filter=service-instance-id:EQUALS:"
339                     + serviceInstanceIdentifier, false));
340             JSONParser jsonParser = new JSONParser();
341             try {
342                 if(entity != null) {
343                     org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) jsonParser.parse(
344                                                                                             entity.getBody().toString());
345                     JSONArray jSONArray = (JSONArray)jsonObject.get("result-data");
346                     org.json.simple.JSONObject jSONObject = (org.json.simple.JSONObject)jSONArray.get(0);
347                     String resourceLink = jSONObject.get("resource-link").toString();
348                     String serviceType = resourceLink.split("/")[9];
349                     aaiResponse = aaiService.getServiceInstanceBySubscriberIdAndSIID(globalCustomerId,serviceType,
350                                                                                             serviceInstanceIdentifier);
351                     if(aaiResponse != null && aaiResponse.getT() != null) {
352                         viewEditSIResult.setOrchestrationStatus(((ServiceRelationships) aaiResponse.getT()).orchestrationStatus);
353                         viewEditSIResult.setServiceInstanceId(((ServiceRelationships) aaiResponse.getT()).serviceInstanceId);
354                         viewEditSIResult.setServiceInstanceName(((ServiceRelationships) aaiResponse.getT()).serviceInstanceName);
355                         viewEditSIResult.setModelVersionId(((ServiceRelationships) aaiResponse.getT()).modelVersionId);
356                         viewEditSIResult.setModelInvariantId(((ServiceRelationships) aaiResponse.getT()).modelInvariantId);
357                         viewEditSIResult.setSubscriberName(subscriberName.get());
358                     } else {
359                         LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + ".aai_get_service_instance_by_id_and_type. No response for getServiceInstanceBySubscriberIdAndSIID: "+serviceInstanceIdentifier);
360                         errorMessage = aaiResponse.getErrorMessage();
361                     }
362                     statusCode = aaiResponse.getHttpCode();
363                 } else {
364                     LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + ".aai_get_service_instance_by_id_and_type. No response for nodes-query for siid: "+serviceInstanceIdentifier);
365                     statusCode = entity.getStatusCode().value();
366                     errorMessage = aaiResponse.getErrorMessage();
367                 }
368             } catch (Exception e) {
369                 LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + ".aai_get_service_instance_by_id_and_type" + e.toString());
370                 LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + ".aai_get_service_instance_by_id_and_type" + e.toString());
371             }
372         } else {
373             LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + ".aai_get_service_instance_by_id_and_type. Use DSL query to get SI details."+serviceInstanceIdentifier);
374             aaiResponse = aaiService
375                 .getServiceInstanceBySubscriberIdAndInstanceIdentifier(globalCustomerId, serviceIdentifierType, serviceInstanceIdentifier);
376             if(aaiResponse != null && aaiResponse.getT() != null) {
377                 CustomerSpecificServiceInstance siData = ((DSLQuerySimpleResponse)aaiResponse.getT()).getResults().get(0).getCustomer().
378                     customerRelatedNodes.get(0).getCustomerServiceSubscription().
379                     getServiceSubscriptionRelatedNodes().get(0).getServiceInstance();
380                 viewEditSIResult.setOrchestrationStatus(siData.getOrchestrationStatus());
381                 viewEditSIResult.setServiceInstanceId(siData.serviceInstanceId);
382                 viewEditSIResult.setServiceInstanceName(siData.serviceInstanceName);
383                 viewEditSIResult.setModelVersionId(siData.modelVersionId);
384                 viewEditSIResult.setModelInvariantId(siData.modelInvariantId);
385                 viewEditSIResult.setSubscriberName(((DSLQuerySimpleResponse)aaiResponse.getT()).getResults().get(0).getCustomer().subscriberName);
386             } else {
387                 LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + ".aai_get_service_instance_by_id_and_type. No result for DSL query :"+serviceInstanceIdentifier);
388                 errorMessage = aaiResponse.getErrorMessage();
389             }
390             statusCode = aaiResponse.getHttpCode();
391         }
392         String httpMessage = viewEditSIResult != null ? objectMapper.writeValueAsString(viewEditSIResult) : errorMessage;
393         return new ResponseEntity<>(httpMessage,HttpStatus.valueOf(statusCode));
394     }
395
396
397     @RequestMapping(value = "/aai_sub_viewedit/{namedQueryId}/{globalCustomerId}/{serviceType}/{serviceInstance}", method = RequestMethod.GET)
398     public ResponseEntity<String> viewEditGetComponentList(
399         @PathVariable("namedQueryId") String namedQueryId,
400         @PathVariable("globalCustomerId") String globalCustomerId,
401         @PathVariable("serviceType") String serviceType,
402         @PathVariable("serviceInstance") String serviceInstance) {
403
404         String componentListPayload = getComponentListPutPayload(namedQueryId, globalCustomerId, serviceType,
405             serviceInstance);
406
407         Response resp = doAaiPost("search/named-query", componentListPayload, false);
408         return convertResponseToResponseEntity(resp);
409     }
410
411     @RequestMapping(value = "/aai_get_models_by_service_type/{namedQueryId}/{globalCustomerId}/{serviceType}", method = RequestMethod.GET)
412     public ResponseEntity<String> viewEditGetComponentList(
413         @PathVariable("namedQueryId") String namedQueryId,
414         @PathVariable("globalCustomerId") String globalCustomerId,
415         @PathVariable("serviceType") String serviceType) {
416
417         String componentListPayload = getModelsByServiceTypePayload(namedQueryId, globalCustomerId, serviceType);
418
419         Response resp = doAaiPost("search/named-query", componentListPayload, false);
420         return convertResponseToResponseEntity(resp);
421     }
422
423     @RequestMapping(value = "/aai_get_vnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}", method = RequestMethod.GET)
424     public ResponseEntity<String> getNodeTemplateInstances(
425         @PathVariable("globalCustomerId") String globalCustomerId,
426         @PathVariable("serviceType") String serviceType,
427         @PathVariable("modelVersionId") String modelVersionId,
428         @PathVariable("modelInvariantId") String modelInvariantId,
429         @PathVariable("cloudRegion") String cloudRegion) {
430
431         AaiResponse<String> resp = aaiService
432             .getNodeTemplateInstances(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion);
433         return new ResponseEntity<>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode()));
434     }
435
436     @RequestMapping(value = "/aai_get_network_collection_details/{serviceInstanceId}", method = RequestMethod.GET)
437     public ResponseEntity<String> getNetworkCollectionDetails(
438         @PathVariable("serviceInstanceId") String serviceInstanceId) throws IOException {
439         AaiResponse<String> resp = aaiService.getNetworkCollectionDetails(serviceInstanceId);
440
441         String httpMessage = resp.getT() != null ?
442             objectMapper.writeValueAsString(resp.getT()) :
443             resp.getErrorMessage();
444         return new ResponseEntity<>(httpMessage, HttpStatus.valueOf(resp.getHttpCode()));
445     }
446
447     @RequestMapping(value = "/aai_get_instance_groups_by_cloudregion/{cloudOwner}/{cloudRegionId}/{networkFunction}", method = RequestMethod.GET)
448     public ResponseEntity<String> getInstanceGroupsByCloudRegion(@PathVariable("cloudOwner") String cloudOwner,
449         @PathVariable("cloudRegionId") String cloudRegionId,
450         @PathVariable("networkFunction") String networkFunction) throws IOException {
451         AaiResponse<AaiGetInstanceGroupsByCloudRegion> resp = aaiService
452             .getInstanceGroupsByCloudRegion(cloudOwner, cloudRegionId, networkFunction);
453
454         String httpMessage = resp.getT() != null ?
455             objectMapper.writeValueAsString(resp.getT()) :
456             resp.getErrorMessage();
457         return new ResponseEntity<>(httpMessage, HttpStatus.valueOf(resp.getHttpCode()));
458     }
459
460     @RequestMapping(value = "/aai_get_by_uri/**", method = RequestMethod.GET)
461     public ResponseEntity<String> getByUri(HttpServletRequest request) {
462
463         String restOfTheUrl = (String) request.getAttribute(
464             HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
465         String formattedUri = restOfTheUrl.replaceFirst("/aai_get_by_uri/", "").replaceFirst("^aai/v[\\d]+/", "");
466
467         Response resp = doAaiGet(formattedUri, false);
468
469         return convertResponseToResponseEntity(resp);
470     }
471
472     @RequestMapping(value = "/aai_get_configuration/{configuration_id}", method = RequestMethod.GET)
473     public ResponseEntity<String> getSpecificConfiguration(@PathVariable("configuration_id") String configurationId) {
474
475         Response resp = doAaiGet("network/configurations/configuration/" + configurationId, false);
476
477         return convertResponseToResponseEntity(resp);
478     }
479
480     @RequestMapping(value = "/aai_get_service_instance_pnfs/{globalCustomerId}/{serviceType}/{serviceInstanceId}", method = RequestMethod.GET)
481     public List<String> getServiceInstanceAssociatedPnfs(
482         @PathVariable("globalCustomerId") String globalCustomerId,
483         @PathVariable("serviceType") String serviceType,
484         @PathVariable("serviceInstanceId") String serviceInstanceId) {
485
486         return aaiService.getServiceInstanceAssociatedPnfs(globalCustomerId, serviceType, serviceInstanceId);
487     }
488
489     @RequestMapping(value = "/aai_get_pnfs/pnf/{pnf_id}", method = RequestMethod.GET)
490     public ResponseEntity getSpecificPnf(@PathVariable("pnf_id") String pnfId) {
491         ResponseEntity<Pnf> re;
492         try {
493             AaiResponse<Pnf> resp = aaiService.getSpecificPnf(pnfId);
494             re = new ResponseEntity<>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode()));
495         } catch (Exception e) {
496             return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
497         }
498         return re;
499     }
500
501     @RequestMapping(value = "/aai_get_tenants/{global-customer-id}/{service-type}", method = RequestMethod.GET)
502     public ResponseEntity<String> viewEditGetTenantsFromServiceType(HttpServletRequest request,
503         @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) {
504
505         ResponseEntity responseEntity;
506         try {
507             RoleValidator roleValidator = roleProvider.getUserRolesValidator(request);
508             AaiResponse<GetTenantsResponse[]> response = aaiService
509                 .getTenants(globalCustomerId, serviceType, roleValidator);
510             if (response.getHttpCode() == 200) {
511                 responseEntity = new ResponseEntity<>(objectMapper.writeValueAsString(response.getT()),
512                     HttpStatus.OK);
513             } else {
514                 responseEntity = new ResponseEntity<>(response.getErrorMessage(),
515                     HttpStatus.valueOf(response.getHttpCode()));
516             }
517         } catch (Exception e) {
518             responseEntity = new ResponseEntity<>("Unable to proccess getTenants reponse",
519                 HttpStatus.INTERNAL_SERVER_ERROR);
520         }
521         return responseEntity;
522     }
523
524     @RequestMapping(value = "/aai_get_pnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}/{equipVendor}/{equipModel}", method = RequestMethod.GET)
525     public ResponseEntity<String> getPnfInstances(
526         @PathVariable("globalCustomerId") String globalCustomerId,
527         @PathVariable("serviceType") String serviceType,
528         @PathVariable("modelVersionId") String modelVersionId,
529         @PathVariable("modelInvariantId") String modelInvariantId,
530         @PathVariable("cloudRegion") String cloudRegion,
531         @PathVariable("equipVendor") String equipVendor,
532         @PathVariable("equipModel") String equipModel) {
533
534         AaiResponse<String> resp = aaiService
535             .getPNFData(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion, equipVendor,
536                 equipModel);
537         return new ResponseEntity<>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode()));
538     }
539
540     @RequestMapping(value = "/aai_getPortMirroringConfigsData", method = RequestMethod.GET)
541     public Map<String, PortMirroringConfigData> getPortMirroringConfigsData(
542         @RequestParam("configurationIds") List<String> configurationIds) {
543
544         return configurationIds.stream()
545             .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringConfigData(id)))
546             .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
547     }
548
549     @RequestMapping(value = "/aai_getPortMirroringSourcePorts", method = RequestMethod.GET)
550     public Map<String, Object> getPortMirroringSourcePorts(
551         @RequestParam("configurationIds") List<String> configurationIds) {
552
553         return configurationIds.stream()
554             .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringSourcePorts(id)))
555             .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
556     }
557
558     private ResponseEntity<String> convertResponseToResponseEntity(Response resp) {
559         ResponseEntity<String> respEnt;
560         if (resp == null) {
561             respEnt = new ResponseEntity<>("Failed to fetch data from A&AI, check server logs for details.",
562                 HttpStatus.INTERNAL_SERVER_ERROR);
563         } else {
564             respEnt = new ResponseEntity<>(resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));
565         }
566         return respEnt;
567     }
568
569     private Response getSubscribers() {
570
571         String depth = "0";
572
573         Response resp = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false);
574         if (resp != null) {
575             LOGGER
576                 .debug(EELFLoggerDelegate.debugLogger, "<== getSubscribers() resp=" + resp.getStatusInfo().toString());
577         }
578         return resp;
579     }
580
581     protected Response doAaiGet(String uri, boolean xml) {
582         String methodName = "getSubscriberList";
583         String transId = UUID.randomUUID().toString();
584         LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " start");
585
586         Response resp = null;
587         try {
588
589             resp = aaiRestInterface.RestGet(FROM_APP_ID, transId, Unchecked.toURI(uri), xml).getResponse();
590
591         } catch (WebApplicationException e) {
592             final String message = e.getResponse().readEntity(String.class);
593             LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + "." + methodName + message);
594             LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + "." + methodName + message);
595         } catch (Exception e) {
596             LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + "." + methodName + e.toString());
597             LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + "." + methodName + e.toString());
598         }
599
600         return resp;
601     }
602
603     protected Response doAaiPost(String uri, String payload, boolean xml) {
604         String methodName = "getSubscriberList";
605         LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + methodName + " start");
606
607         Response resp = null;
608         try {
609
610             resp = aaiRestInterface.RestPost(FROM_APP_ID, uri, payload, xml);
611
612         } catch (Exception e) {
613             LOGGER.info(EELFLoggerDelegate.errorLogger, "<== " + "." + methodName + e.toString());
614             LOGGER.debug(EELFLoggerDelegate.debugLogger, "<== " + "." + methodName + e.toString());
615         }
616
617         return resp;
618     }
619
620     private String getComponentListPutPayload(String namedQueryId, String globalCustomerId, String serviceType,
621         String serviceInstance) {
622         return
623             "           {" +
624                 "    \"instance-filters\": {" +
625                 "        \"instance-filter\": [" +
626                 "            {" +
627                 "                \"customer\": {" +
628                 "                    \"global-customer-id\": \"" + globalCustomerId + "\"" +
629                 "                }," +
630                 "                \"service-instance\": {" +
631                 "                    \"service-instance-id\": \"" + serviceInstance + "\"" +
632                 "                }," +
633                 "                \"service-subscription\": {" +
634                 "                    \"service-type\": \"" + serviceType + "\"" +
635                 "                }" +
636                 "            }" +
637                 "        ]" +
638                 "    }," +
639                 "    \"query-parameters\": {" +
640                 "        \"named-query\": {" +
641                 "            \"named-query-uuid\": \"" + namedQueryId + "\"" +
642                 "        }" +
643                 "    }" +
644                 "}";
645
646     }
647
648     private String getModelsByServiceTypePayload(String namedQueryId, String globalCustomerId, String serviceType) {
649         // TODO Auto-generated method stub
650         return "                {" +
651             "    \"instance-filters\": {" +
652             "        \"instance-filter\": [" +
653             "            {" +
654             "                \"customer\": {" +
655             "                    \"global-customer-id\": \"" + globalCustomerId + "\"" +
656             "                }," +
657             "                \"service-subscription\": {" +
658             "                    \"service-type\": \"" + serviceType + "\"" +
659             "                }" +
660             "            }" +
661             "        ]" +
662             "    }," +
663             "    \"query-parameters\": {" +
664             "        \"named-query\": {" +
665             "            \"named-query-uuid\": \"" + namedQueryId + "\"" +
666             "        }" +
667             "    }" +
668             "}";
669
670     }
671
672     private String getAaiErrorMessage(String message) {
673         try {
674             org.json.JSONObject json = new org.json.JSONObject(message);
675             json = json.getJSONObject("requestError").getJSONObject("serviceException");
676
677             return json.getString("messageId") + ": " + json.getString("text");
678
679         } catch (Exception e) {
680             return null;
681         }
682     }
683     private boolean isValidInstanceIdentifierType(String instanceIdentifierType) {
684         return instanceIdentifierType != null
685             && (    instanceIdentifierType.equalsIgnoreCase("Service Instance Id") ||
686             instanceIdentifierType.equalsIgnoreCase("Service Instance Name"));
687     }
688 }