aboutsummaryrefslogtreecommitdiffstats
path: root/vid-app-common/src/main/java/org/onap/vid/controllers/AaiController.java
blob: 1a426ed29250e5394de2c53740fce4d5d530f405 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
/*-
 * ============LICENSE_START=======================================================
 * VID
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.vid.controllers;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.codehaus.jackson.map.ObjectMapper;
import org.onap.vid.aai.AaiResponse;
import org.onap.vid.aai.AaiResponseTranslator.PortMirroringConfigData;
import org.onap.vid.aai.ServiceInstancesSearchResults;
import org.onap.vid.aai.SubscriberData;
import org.onap.vid.aai.SubscriberFilteredResults;
import org.onap.vid.aai.model.AaiGetInstanceGroupsByCloudRegion;
import org.onap.vid.aai.model.AaiGetOperationalEnvironments.OperationalEnvironmentList;
import org.onap.vid.aai.model.AaiGetPnfs.Pnf;
import org.onap.vid.aai.model.AaiGetTenatns.GetTenantsResponse;
import org.onap.vid.aai.util.AAIRestInterface;
import org.onap.vid.model.VersionByInvariantIdsRequest;
import org.onap.vid.roles.Role;
import org.onap.vid.roles.RoleProvider;
import org.onap.vid.roles.RoleValidator;
import org.onap.vid.services.AaiService;
import org.onap.portalsdk.core.controller.RestrictedBaseController;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
import org.onap.portalsdk.core.util.SystemProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static org.onap.vid.utils.Logging.getMethodName;

/**
 * Controller to handle a&ai requests.
 */

@RestController
public class AaiController extends RestrictedBaseController {
    /**
     * The Constant dateFormat.
     */
    final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");
    /**
     * The from app id.
     */
    protected String fromAppId = "VidAaiController";
    /**
     * The logger.
     */
    private static final EELFLoggerDelegate LOGGER = EELFLoggerDelegate.getLogger(AaiController.class);
    /**
     * The model.
     */
    private Map<String, Object> model = new HashMap<String, Object>();
    /**
     * The servlet context.
     */
    @Autowired
    private ServletContext servletContext;
    /**
     * aai service
     */
    @Autowired
    private AaiService aaiService;
    @Autowired
    private RoleProvider roleProvider;

    @Autowired
    private AAIRestInterface aaiRestInterface;

    /**
     * Welcome method.
     *
     * @param request the request
     * @return ModelAndView The view
     */
    @RequestMapping(value = {"/subscriberSearch"}, method = RequestMethod.GET)
    public ModelAndView welcome(HttpServletRequest request) {
        LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== AaiController welcome start");
        return new ModelAndView(getViewName());
    }

    @RequestMapping(value = {"/aai_get_aic_zones"}, method = RequestMethod.GET)
    public ResponseEntity<String> getAicZones(HttpServletRequest request) throws IOException {
        LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZones controller start");
        AaiResponse response = aaiService.getAaiZones();
        return aaiResponseToResponseEntity(response);
    }

    @RequestMapping(value = {"/aai_get_aic_zone_for_pnf/{globalCustomerId}/{serviceType}/{serviceId}"}, method = RequestMethod.GET)
    public ResponseEntity<String> getAicZoneForPnf(@PathVariable("globalCustomerId") String globalCustomerId ,@PathVariable("serviceType") String serviceType , @PathVariable("serviceId") String serviceId ,HttpServletRequest request) throws IOException {
        LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZoneForPnf controller start");
        AaiResponse response = aaiService.getAicZoneForPnf(globalCustomerId , serviceType , serviceId);
        return aaiResponseToResponseEntity(response);
    }

    @RequestMapping(value = {"/aai_get_instance_groups_by_vnf_instance_id/{vnfInstanceId}"}, method = RequestMethod.GET)
    public ResponseEntity<String> getInstanceGroupsByVnfInstanceId(@PathVariable("vnfInstanceId") String vnfInstanceId ,HttpServletRequest request) throws IOException {
        AaiResponse response = aaiService.getInstanceGroupsByVnfInstanceId(vnfInstanceId);
        return aaiResponseToResponseEntity(response);
    }
    /**
     * Get services from a&ai.
     *
     * @return ResponseEntity<String> The response entity with the logged in user uuid.
     * @throws IOException          Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = {"/getuserID"}, method = RequestMethod.GET)
    public ResponseEntity<String> getUserID(HttpServletRequest request) {

        String userId = ControllersUtils.extractUserId(request);

        return new ResponseEntity<String>(userId, HttpStatus.OK);
    }

    /**
     * Get services from a&ai.
     *
     * @return ResponseEntity<String> The response entity
     * @throws IOException          Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = "/aai_get_services", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> doGetServices(HttpServletRequest request) throws IOException {
        RoleValidator roleValidator = new RoleValidator(roleProvider.getUserRoles(request));

        AaiResponse subscriberList = aaiService.getServices(roleValidator);
        ResponseEntity<String> responseEntity = aaiResponseToResponseEntity(subscriberList);

        return responseEntity;
    }


    @RequestMapping(value = {"/aai_get_version_by_invariant_id"}, method = RequestMethod.POST)
    public ResponseEntity<String> getVersionByInvariantId(HttpServletRequest request, @RequestBody VersionByInvariantIdsRequest versions) {
        ResponseEntity<String> responseEntity;
        ObjectMapper objectMapper = new ObjectMapper();

        Response result = aaiService.getVersionByInvariantId(versions.versions);

        return new ResponseEntity<String>(result.readEntity(String.class), HttpStatus.OK);
    }


    private ResponseEntity<String> aaiResponseToResponseEntity(AaiResponse aaiResponseData)
            throws IOException {
        ResponseEntity<String> responseEntity;
        ObjectMapper objectMapper = new ObjectMapper();
        if (aaiResponseData.getHttpCode() == 200) {
            responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(aaiResponseData.getT()), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<String>(aaiResponseData.getErrorMessage(), HttpStatus.valueOf(aaiResponseData.getHttpCode()));
        }
        return responseEntity;
    }

    /**
     * Lookup single service instance in a&ai.  Get the service-subscription and customer, too, i guess?
     *
     * @param serviceInstanceId the service instance Id
     * @return ResponseEntity The response entity
     * @throws IOException          Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = "/aai_get_service_instance/{service-instance-id}/{service-instance-type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> doGetServiceInstance(@PathVariable("service-instance-id") String serviceInstanceId, @PathVariable("service-instance-type") String serviceInstanceType) {
        Response resp = null;

        if (serviceInstanceType.equalsIgnoreCase("Service Instance Id")) {
            resp = doAaiGet(
                    "search/nodes-query?search-node-type=service-instance&filter=service-instance-id:EQUALS:"
                            + serviceInstanceId, false);
        } else {
            resp = doAaiGet(
                    "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:"
                            + serviceInstanceId, false);
        }
        return convertResponseToResponseEntity(resp);
    }

    /**
     * Get services from a&ai.
     *
     * @param globalCustomerId      the global customer id
     * @param serviceSubscriptionId the service subscription id
     * @return ResponseEntity The response entity
     * @throws IOException          Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = "/aai_get_service_subscription/{global-customer-id}/{service-subscription-id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> doGetServices(@PathVariable("global-customer-id") String globalCustomerId,
                                                @PathVariable("service-subscription-id") String serviceSubscriptionId) {
        Response resp = doAaiGet("business/customers/customer/" + globalCustomerId
                + "/service-subscriptions/service-subscription/" + serviceSubscriptionId + "?depth=0", false);
        return convertResponseToResponseEntity(resp);
    }

    /**
     * Obtain the subscriber list from a&ai.
     *
     * @param fullSet the full set
     * @return ResponseEntity The response entity
     * @throws IOException          Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = "/aai_get_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> doGetSubscriberList(HttpServletRequest request, @DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException {
        return getFullSubscriberList(request);
    }

    /**
     * Obtain the Target Prov Status from the System.Properties file.
     *
     * @return ResponseEntity The response entity
     * @throws IOException          Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = "/get_system_prop_vnf_prov_status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> getTargetProvStatus() {
        String p = SystemProperties.getProperty("aai.vnf.provstatus");
        return new ResponseEntity<String>(p, HttpStatus.OK);
    }


    /**
     * Obtain the Target Prov Status from the System.Properties file.
     *
     * @return ResponseEntity The response entity
     * @throws IOException          Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = "/get_operational_environments", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public AaiResponse<OperationalEnvironmentList> getOperationalEnvironments(@RequestParam(value="operationalEnvironmentType", required = false) String operationalEnvironmentType,
                                                           @RequestParam(value="operationalEnvironmentStatus", required = false) String operationalEnvironmentStatus) {
        LOGGER.debug(EELFLoggerDelegate.debugLogger, "start {}({}, {})", getMethodName(), operationalEnvironmentType, operationalEnvironmentStatus);
        AaiResponse<OperationalEnvironmentList> response = aaiService.getOperationalEnvironments(operationalEnvironmentType,operationalEnvironmentStatus);
        if (response.getHttpCode() != 200) {
            String errorMessage = getAaiErrorMessage(response.getErrorMessage());
            if(errorMessage != null) {
                response = new AaiResponse<OperationalEnvironmentList>(response.getT(), errorMessage, response.getHttpCode());
            }
        }

        LOGGER.debug(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), response);
        return response;
    }

    /**
     * Obtain the full subscriber list from a&ai.
     * <p>
     * g @return ResponseEntity The response entity
     *
     * @throws IOException          Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = "/aai_get_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> getFullSubscriberList(HttpServletRequest request) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseEntity<String> responseEntity;
        RoleValidator roleValidator = new RoleValidator(roleProvider.getUserRoles(request));
        SubscriberFilteredResults subscriberList = aaiService.getFullSubscriberList(roleValidator);
        if (subscriberList.getHttpCode() == 200) {
            responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(subscriberList.getSubscriberList()), HttpStatus.OK);
        } else {
            responseEntity = new ResponseEntity<String>(subscriberList.getErrorMessage(), HttpStatus.valueOf(subscriberList.getHttpCode()));
        }


        return responseEntity;
    }


    @RequestMapping(value = "/get_vnf_data_by_globalid_and_service_type/{globalCustomerId}/{serviceType}",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> getVnfDataByGlobalIdAndServiceType(HttpServletRequest request,
                                                                     @PathVariable("globalCustomerId") String globalCustomerId,
                                                                     @PathVariable("serviceType") String serviceType) {

        Response resp = aaiService.getVNFData(globalCustomerId, serviceType);
        return convertResponseToResponseEntity(resp);
    }


    /**
     * Refresh the subscriber list from a&ai.
     *
     * @return ResponseEntity The response entity
     * @throws IOException Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = "/aai_refresh_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> doRefreshSubscriberList() {
        Response resp = getSubscribers(false);
        return convertResponseToResponseEntity(resp);
    }

    /**
     * Refresh the full subscriber list from a&ai.
     *
     * @return ResponseEntity The response entity
     * @throws IOException Signals that an I/O exception has occurred.
     */
    @RequestMapping(value = "/aai_refresh_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> doRefreshFullSubscriberList() {
        Response resp = getSubscribers(false);
        return convertResponseToResponseEntity(resp);
    }

    /**
     * Get subscriber details from a&ai.
     *
     * @param subscriberId the subscriber id
     * @return ResponseEntity The response entity
     */
    @RequestMapping(value = "/aai_sub_details/{subscriberId}", method = RequestMethod.GET)
    public ResponseEntity<String> GetSubscriberDetails(HttpServletRequest request, @PathVariable("subscriberId") String subscriberId) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseEntity responseEntity;
        List<Role> roles = roleProvider.getUserRoles(request);
        RoleValidator roleValidator = new RoleValidator(roles);
        AaiResponse<SubscriberData> subscriberData = aaiService.getSubscriberData(subscriberId, roleValidator);
        String httpMessage = subscriberData.getT() != null ?
                objectMapper.writeValueAsString(subscriberData.getT()) :
                subscriberData.getErrorMessage();

        responseEntity = new ResponseEntity<String>(httpMessage, HttpStatus.valueOf(subscriberData.getHttpCode()));
        return responseEntity;
    }

    /**
     * Get service instances that match the query from a&ai.
     *
     * @param subscriberId the subscriber id
     * @param instanceIdentifier the service instance name or id.
     * @param projects the projects that are related to the instance
     * @param owningEntities the owningEntities that are related to the instance
     * @return ResponseEntity The response entity
     */
    @RequestMapping(value = "/search_service_instances", method = RequestMethod.GET)
    public ResponseEntity<String> SearchServiceInstances(HttpServletRequest request,
                                                         @RequestParam(value="subscriberId", required = false) String subscriberId,
                                                         @RequestParam(value="serviceInstanceIdentifier", required = false) String instanceIdentifier,
                                                         @RequestParam(value="project", required = false) List<String> projects,
                                                         @RequestParam(value="owningEntity", required = false) List<String> owningEntities) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        ResponseEntity responseEntity;

        List<Role> roles = roleProvider.getUserRoles(request);
        RoleValidator roleValidator = new RoleValidator(roles);

        AaiResponse<ServiceInstancesSearchResults> searchResult = aaiService.getServiceInstanceSearchResults(subscriberId, instanceIdentifier, roleValidator, owningEntities, projects);

        String httpMessage = searchResult.getT() != null ?
                objectMapper.writeValueAsString(searchResult.getT()) :
                searchResult.getErrorMessage();


        if(searchResult.getT().serviceInstances.size() == 0){
            responseEntity = new ResponseEntity<String>(httpMessage, HttpStatus.NOT_FOUND);

        } else {
            responseEntity = new ResponseEntity<String>(httpMessage, HttpStatus.valueOf(searchResult.getHttpCode()));

        }
        return responseEntity;
    }



    /**
     * Issue a named query to a&ai.
     *
     * @param namedQueryId     the named query id
     * @param globalCustomerId the global customer id
     * @param serviceType      the service type
     * @param serviceInstance  the service instance
     * @return ResponseEntity The response entity
     */
    @RequestMapping(value = "/aai_sub_viewedit/{namedQueryId}/{globalCustomerId}/{serviceType}/{serviceInstance}", method = RequestMethod.GET)
    public ResponseEntity<String> viewEditGetComponentList(
            @PathVariable("namedQueryId") String namedQueryId,
            @PathVariable("globalCustomerId") String globalCustomerId,
            @PathVariable("serviceType") String serviceType,
            @PathVariable("serviceInstance") String serviceInstance) {

        String componentListPayload = getComponentListPutPayload(namedQueryId, globalCustomerId, serviceType, serviceInstance);

        Response resp = doAaiPost("search/named-query", componentListPayload, false);
        return convertResponseToResponseEntity(resp);
    }

    @RequestMapping(value = "/aai_get_vnf_data/{globalCustomerId}/{serviceType}/{serviceInstanceId}", method = RequestMethod.GET)
    public AaiResponse<String> getVnfData(
            @PathVariable("globalCustomerId") String globalCustomerId,
            @PathVariable("serviceType") String serviceType,
            @PathVariable("serviceInstanceId") String serviceInstanceId) {

        return aaiService.getVNFData(globalCustomerId, serviceType, serviceInstanceId);

    }


    /**
     * Issue a named query to a&ai.
     *
     * @param namedQueryId     the named query id
     * @param globalCustomerId the global customer id
     * @param serviceType      the service type
     * @return ResponseEntity The response entity
     */
    @RequestMapping(value = "/aai_get_models_by_service_type/{namedQueryId}/{globalCustomerId}/{serviceType}", method = RequestMethod.GET)
    public ResponseEntity<String> viewEditGetComponentList(
            @PathVariable("namedQueryId") String namedQueryId,
            @PathVariable("globalCustomerId") String globalCustomerId,
            @PathVariable("serviceType") String serviceType) {

        String componentListPayload = getModelsByServiceTypePayload(namedQueryId, globalCustomerId, serviceType);

        Response resp = doAaiPost("search/named-query", componentListPayload, false);
        return convertResponseToResponseEntity(resp);
    }

    @RequestMapping(value = "/aai_get_vnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}", method = RequestMethod.GET)
    public ResponseEntity<String> getNodeTemplateInstances(
            @PathVariable("globalCustomerId") String globalCustomerId,
            @PathVariable("serviceType") String serviceType,
            @PathVariable("modelVersionId") String modelVersionId,
            @PathVariable("modelInvariantId") String modelInvariantId,
            @PathVariable("cloudRegion") String cloudRegion) {

        AaiResponse<String> resp = aaiService.getNodeTemplateInstances(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion);
        return new ResponseEntity<String>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode()));
    }

    @RequestMapping(value = "/aai_get_network_collection_details/{serviceInstanceId}", method = RequestMethod.GET)
    public ResponseEntity<String> getNetworkCollectionDetails(@PathVariable("serviceInstanceId") String serviceInstanceId) throws IOException {
        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
        AaiResponse<String> resp = aaiService.getNetworkCollectionDetails(serviceInstanceId);

        String httpMessage = resp.getT() != null ?
                objectMapper.writeValueAsString(resp.getT()) :
                resp.getErrorMessage();
        return new ResponseEntity<String>(httpMessage, HttpStatus.valueOf(resp.getHttpCode()));
    }

    @RequestMapping(value = "/aai_get_instance_groups_by_cloudregion/{cloudOwner}/{cloudRegionId}/{networkFunction}", method = RequestMethod.GET)
    public ResponseEntity<String> getInstanceGroupsByCloudRegion(@PathVariable("cloudOwner") String cloudOwner,
                                                                 @PathVariable("cloudRegionId") String cloudRegionId,
                                                                 @PathVariable("networkFunction") String networkFunction) throws IOException {
        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
        AaiResponse<AaiGetInstanceGroupsByCloudRegion> resp = aaiService.getInstanceGroupsByCloudRegion(cloudOwner, cloudRegionId, networkFunction);

        String httpMessage = resp.getT() != null ?
                objectMapper.writeValueAsString(resp.getT()) :
                resp.getErrorMessage();
        return new ResponseEntity<String>(httpMessage, HttpStatus.valueOf(resp.getHttpCode()));
    }

    @RequestMapping(value = "/aai_get_by_uri/**", method = RequestMethod.GET)
    public ResponseEntity<String> getByUri(HttpServletRequest request) {

        String restOfTheUrl = (String) request.getAttribute(
                HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String formattedUri = restOfTheUrl.replaceFirst("/aai_get_by_uri/", "").replaceFirst("^aai/v[\\d]+/", "");

        Response resp = doAaiGet(formattedUri, false);

        return convertResponseToResponseEntity(resp);
    }



    @RequestMapping(value = "/aai_get_configuration/{configuration_id}", method = RequestMethod.GET)
    public ResponseEntity<String> getSpecificConfiguration(@PathVariable("configuration_id") String configurationId) {

        Response resp = doAaiGet("network/configurations/configuration/"+configurationId, false);

        return convertResponseToResponseEntity(resp);
    }

    @RequestMapping(value = "/aai_get_service_instance_pnfs/{globalCustomerId}/{serviceType}/{serviceInstanceId}", method = RequestMethod.GET)
    public List<String> getServiceInstanceAssociatedPnfs(
            @PathVariable("globalCustomerId") String globalCustomerId,
            @PathVariable("serviceType") String serviceType,
            @PathVariable("serviceInstanceId") String serviceInstanceId) {

        return aaiService.getServiceInstanceAssociatedPnfs(globalCustomerId, serviceType, serviceInstanceId);
    }

    /**
     * PNF section
     */
    @RequestMapping(value = "/aai_get_pnfs/pnf/{pnf_id}", method = RequestMethod.GET)
    public ResponseEntity getSpecificPnf(@PathVariable("pnf_id") String pnfId) {
        //logger.trace(EELFLoggerDelegate.debugLogger, "start {}({})", getMethodName(), pnfId);
        AaiResponse<Pnf> resp;
        ResponseEntity<Pnf> re;
        try {
            resp = aaiService.getSpecificPnf(pnfId);
            re = new ResponseEntity<Pnf>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode()));
        } catch (Exception e){
            return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
        //logger.trace(EELFLoggerDelegate.debugLogger, "end {}() => {}", getMethodName(), resp.getHttpCode());
        return re;
    }


    /**
     * Obtain tenants for a given service type.
     *
     * @param globalCustomerId the global customer id
     * @param serviceType      the service type
     * @return ResponseEntity The response entity
     */
    @RequestMapping(value = "/aai_get_tenants/{global-customer-id}/{service-type}", method = RequestMethod.GET)
    public ResponseEntity<String> viewEditGetTenantsFromServiceType(HttpServletRequest request,
                                                                    @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) {

        ResponseEntity responseEntity;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            List<Role> roles = roleProvider.getUserRoles(request);
            RoleValidator roleValidator = new RoleValidator(roles);
            AaiResponse<GetTenantsResponse[]> response = aaiService.getTenants(globalCustomerId, serviceType, roleValidator);
            if (response.getHttpCode() == 200) {
                responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(response.getT()), HttpStatus.OK);
            } else {
                responseEntity = new ResponseEntity<String>(response.getErrorMessage(), HttpStatus.valueOf(response.getHttpCode()));
            }
        } catch (Exception e) {
            responseEntity = new ResponseEntity<String>("Unable to proccess getTenants reponse", HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return responseEntity;
    }

    @RequestMapping(value = "/aai_get_pnf_instances/{globalCustomerId}/{serviceType}/{modelVersionId}/{modelInvariantId}/{cloudRegion}/{equipVendor}/{equipModel}", method = RequestMethod.GET)
    public ResponseEntity<String> getPnfInstances(
            @PathVariable("globalCustomerId") String globalCustomerId,
            @PathVariable("serviceType") String serviceType,
            @PathVariable("modelVersionId") String modelVersionId,
            @PathVariable("modelInvariantId") String modelInvariantId,
            @PathVariable("cloudRegion") String cloudRegion,
            @PathVariable("equipVendor") String equipVendor,
            @PathVariable("equipModel") String equipModel) {

        AaiResponse<String> resp = aaiService.getPNFData(globalCustomerId, serviceType, modelVersionId, modelInvariantId, cloudRegion, equipVendor, equipModel);
        return new ResponseEntity<String>(resp.getT(), HttpStatus.valueOf(resp.getHttpCode()));
    }

    @RequestMapping(value = "/aai_getPortMirroringConfigsData", method = RequestMethod.GET)
    public Map<String, PortMirroringConfigData> getPortMirroringConfigsData(
            @RequestParam ("configurationIds") List<String> configurationIds) {

        return configurationIds.stream()
                .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringConfigData(id)))
                .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    }

    @RequestMapping(value = "/aai_getPortMirroringSourcePorts", method = RequestMethod.GET)
    public Map<String, Object> getPortMirroringSourcePorts(
            @RequestParam ("configurationIds") List<String> configurationIds) {

        return configurationIds.stream()
                .map(id -> ImmutablePair.of(id, aaiService.getPortMirroringSourcePorts(id)))
                .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    }

    private ResponseEntity<String> convertResponseToResponseEntity(Response resp) {
        ResponseEntity<String> respEnt;
        ObjectMapper objectMapper = new ObjectMapper();
        if (resp == null) {
            respEnt = new ResponseEntity<String>("Failed to fetch data from A&AI, check server logs for details.", HttpStatus.INTERNAL_SERVER_ERROR);
        } else {
            respEnt = new ResponseEntity<String>(resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));
        }
        return respEnt;
    }

    /**
     * Gets the subscribers.
     *
     * @param isFullSet the is full set
     * @return the subscribers
     */
    private Response getSubscribers(boolean isFullSet) {

        String depth = "0";

        Response resp = doAaiGet("business/customers?subscriber-type=INFRA&depth=" + depth, false);
        if (resp != null) {
            LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString());
        }
        return resp;
    }

    /**
     * Gets the subscriber details.
     *
     * @param subscriberId the subscriber id
     * @return the subscriber details
     */
    private Response getSubscriberDetails(String subscriberId) {
        Response resp = doAaiGet("business/customers/customer/" + subscriberId + "?depth=2", false);
        //String resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId, false);
        LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscriberDetails() resp=" + resp.getStatusInfo().toString());
        return resp;
    }

    /**
     * Send a GET request to a&ai.
     *
     * @param uri       the uri
     * @param xml       the xml
     * @return String The response
     */
    protected Response doAaiGet(String uri, boolean xml) {
        String methodName = "getSubscriberList";
        String transId = UUID.randomUUID().toString();
        LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");

        Response resp = null;
        try {


            resp = aaiRestInterface.RestGet(fromAppId, transId, uri, xml).getResponse();

        } catch (WebApplicationException e) {
            final String message = e.getResponse().readEntity(String.class);
            LOGGER.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
            LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);
        } catch (Exception e) {
            LOGGER.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
            LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
        }

        return resp;
    }

    /**
     * Send a POST request to a&ai.
     *
     * @param uri       the uri
     * @param payload   the payload
     * @param xml       the xml
     * @return String The response
     */
    protected Response doAaiPost(String uri, String payload, boolean xml) {
        String methodName = "getSubscriberList";
        String transId = UUID.randomUUID().toString();
        LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");

        Response resp = null;
        try {

            resp = aaiRestInterface.RestPost(fromAppId, uri, payload, xml);

        } catch (Exception e) {
            LOGGER.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
            LOGGER.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());
        }

        return resp;
    }

    /**
     * Gets the component list put payload.
     *
     * @param namedQueryId     the named query id
     * @param globalCustomerId the global customer id
     * @param serviceType      the service type
     * @param serviceInstance  the service instance
     * @return the component list put payload
     */
    private String getComponentListPutPayload(String namedQueryId, String globalCustomerId, String serviceType, String serviceInstance) {
        return
                "		{" +
                        "    \"instance-filters\": {" +
                        "        \"instance-filter\": [" +
                        "            {" +
                        "                \"customer\": {" +
                        "                    \"global-customer-id\": \"" + globalCustomerId + "\"" +
                        "                }," +
                        "                \"service-instance\": {" +
                        "                    \"service-instance-id\": \"" + serviceInstance + "\"" +
                        "                }," +
                        "                \"service-subscription\": {" +
                        "                    \"service-type\": \"" + serviceType + "\"" +
                        "                }" +
                        "            }" +
                        "        ]" +
                        "    }," +
                        "    \"query-parameters\": {" +
                        "        \"named-query\": {" +
                        "            \"named-query-uuid\": \"" + namedQueryId + "\"" +
                        "        }" +
                        "    }" +
                        "}";

    }

    private String getModelsByServiceTypePayload(String namedQueryId, String globalCustomerId, String serviceType) {
        // TODO Auto-generated method stub
        return "		{" +
                "    \"instance-filters\": {" +
                "        \"instance-filter\": [" +
                "            {" +
                "                \"customer\": {" +
                "                    \"global-customer-id\": \"" + globalCustomerId + "\"" +
                "                }," +
                "                \"service-subscription\": {" +
                "                    \"service-type\": \"" + serviceType + "\"" +
                "                }" +
                "            }" +
                "        ]" +
                "    }," +
                "    \"query-parameters\": {" +
                "        \"named-query\": {" +
                "            \"named-query-uuid\": \"" + namedQueryId + "\"" +
                "        }" +
                "    }" +
                "}";

    }

    private String getAaiErrorMessage(String message) {
        try {
            org.json.JSONObject json = new org.json.JSONObject(message);
            json = json.getJSONObject("requestError").getJSONObject("serviceException");

            return json.getString("messageId") + ": " + json.getString("text");

        } catch (Exception e) {
            return null;
        }
    }
}