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