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