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