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