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