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