Global Read only role, Support VID specific Roles
[vid.git] / vid-app-common / src / main / java / org / openecomp / vid / controller / AaiController.java
1 /*-\r
2  * ============LICENSE_START=======================================================\r
3  * VID\r
4  * ================================================================================\r
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.\r
6  * ================================================================================\r
7  * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * you may not use this file except in compliance with the License.\r
9  * You may obtain a copy of the License at\r
10  * \r
11  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * \r
13  * Unless required by applicable law or agreed to in writing, software\r
14  * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * See the License for the specific language governing permissions and\r
17  * limitations under the License.\r
18  * ============LICENSE_END=========================================================\r
19  */\r
20 \r
21 package org.openecomp.vid.controller;\r
22 \r
23 import org.codehaus.jackson.JsonGenerationException;\r
24 import org.codehaus.jackson.map.JsonMappingException;\r
25 import org.codehaus.jackson.map.ObjectMapper;\r
26 import org.json.simple.JSONArray;\r
27 import org.json.simple.JSONObject;\r
28 import org.json.simple.parser.JSONParser;\r
29 import org.openecomp.aai.util.AAIRestInterface;\r
30 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;\r
31 import org.openecomp.portalsdk.core.domain.User;\r
32 import org.openecomp.portalsdk.core.logging.logic.EELFLoggerDelegate;\r
33 import org.openecomp.portalsdk.core.util.SystemProperties;\r
34 import org.openecomp.vid.aai.AaiResponse;\r
35 import org.openecomp.vid.aai.SubscriberData;\r
36 import org.openecomp.vid.aai.SubscriberFilteredResults;\r
37 import org.openecomp.vid.aai.model.AaiGetTenatns.GetTenantsResponse;\r
38 import org.openecomp.vid.roles.Role;\r
39 import org.openecomp.vid.roles.RoleProvider;\r
40 import org.openecomp.vid.roles.RoleValidator;\r
41 import org.openecomp.vid.services.AaiService;\r
42 import org.springframework.beans.factory.annotation.Autowired;\r
43 import org.springframework.http.HttpStatus;\r
44 import org.springframework.http.MediaType;\r
45 import org.springframework.http.ResponseEntity;\r
46 import org.springframework.web.bind.annotation.PathVariable;\r
47 import org.springframework.web.bind.annotation.RequestMapping;\r
48 import org.springframework.web.bind.annotation.RequestMethod;\r
49 import org.springframework.web.bind.annotation.RestController;\r
50 import org.springframework.web.servlet.ModelAndView;\r
51 \r
52 \r
53 import javax.servlet.ServletContext;\r
54 import javax.servlet.http.HttpServletRequest;\r
55 import javax.servlet.http.HttpSession;\r
56 import javax.ws.rs.BadRequestException;\r
57 import javax.ws.rs.DefaultValue;\r
58 import javax.ws.rs.QueryParam;\r
59 import javax.ws.rs.WebApplicationException;\r
60 import javax.ws.rs.core.Response;\r
61 import java.io.File;\r
62 import java.io.IOException;\r
63 import java.text.DateFormat;\r
64 import java.text.SimpleDateFormat;\r
65 import java.util.*;\r
66 \r
67 /**\r
68  * Controller to handle a&ai requests.\r
69  */\r
70 \r
71 @RestController\r
72 public class AaiController extends RestrictedBaseController {\r
73         \r
74         public AaiController() {\r
75                 \r
76         }\r
77 public  AaiController(ServletContext servletContext) {\r
78         this.servletContext = servletContext;\r
79                 \r
80         }\r
81         \r
82         \r
83         \r
84 \r
85         /**\r
86          * The Constant dateFormat.\r
87          */\r
88         final static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss:SSSS");\r
89         /**\r
90          * The from app id.\r
91          */\r
92         protected String fromAppId = "VidAaiController";\r
93         /**\r
94          * The view name.\r
95          */\r
96         String viewName;\r
97         /**\r
98          * The logger.\r
99          */\r
100         EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(AaiController.class);\r
101 \r
102 \r
103         /**\r
104          * The model.\r
105          */\r
106         private Map<String, Object> model = new HashMap<String, Object>();\r
107         /**\r
108          * The servlet context.\r
109          */\r
110         @Autowired\r
111         private ServletContext servletContext;\r
112 \r
113         /**\r
114          * aai service\r
115          */\r
116         @Autowired\r
117         private AaiService aaiService;\r
118         \r
119         \r
120 \r
121         /**\r
122          * Return tenant details.\r
123          *\r
124          * @param jsonObject the json object\r
125          * @return String The parsing results\r
126          */\r
127         public static String parseCustomerObjectForTenants(JSONObject jsonObject) {\r
128 \r
129                 JSONArray tenantArray = new JSONArray();\r
130                 boolean bconvert = false;\r
131 \r
132                 try {\r
133 \r
134                         JSONObject serviceSubsObj = (JSONObject) jsonObject.get("service-subscriptions");\r
135 \r
136                         if (serviceSubsObj != null) {\r
137                                 JSONArray srvcSubArray = (JSONArray) serviceSubsObj.get("service-subscription");\r
138 \r
139                                 if (srvcSubArray != null) {\r
140                                         Iterator i = srvcSubArray.iterator();\r
141 \r
142                                         while (i.hasNext()) {\r
143 \r
144                                                 JSONObject innerObj = (JSONObject) i.next();\r
145 \r
146                                                 if (innerObj == null)\r
147                                                         continue;\r
148 \r
149                                                 JSONObject relationShipListsObj = (JSONObject) innerObj.get("relationship-list");\r
150                                                 if (relationShipListsObj != null) {\r
151                                                         JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");\r
152                                                         if (rShipArray != null) {\r
153                                                                 Iterator i1 = rShipArray.iterator();\r
154 \r
155                                                                 while (i1.hasNext()) {\r
156 \r
157                                                                         JSONObject inner1Obj = (JSONObject) i1.next();\r
158 \r
159                                                                         if (inner1Obj == null)\r
160                                                                                 continue;\r
161 \r
162                                                                         String relatedTo = checkForNull((String) inner1Obj.get("related-to"));\r
163                                                                         if (relatedTo.equalsIgnoreCase("tenant")) {\r
164                                                                                 JSONObject tenantNewObj = new JSONObject();\r
165 \r
166                                                                                 String relatedLink = checkForNull((String) inner1Obj.get("related-link"));\r
167                                                                                 tenantNewObj.put("link", relatedLink);\r
168 \r
169                                                                                 JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");\r
170                                                                                 if (rDataArray != null) {\r
171                                                                                         Iterator i2 = rDataArray.iterator();\r
172 \r
173                                                                                         while (i2.hasNext()) {\r
174                                                                                                 JSONObject inner2Obj = (JSONObject) i2.next();\r
175 \r
176                                                                                                 if (inner2Obj == null)\r
177                                                                                                         continue;\r
178 \r
179                                                                                                 String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));\r
180                                                                                                 String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));\r
181                                                                                                 if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {\r
182                                                                                                         tenantNewObj.put("cloudOwner", rShipVal);\r
183                                                                                                 } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {\r
184                                                                                                         tenantNewObj.put("cloudRegionID", rShipVal);\r
185                                                                                                 }\r
186 \r
187                                                                                                 if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {\r
188                                                                                                         tenantNewObj.put("tenantID", rShipVal);\r
189                                                                                                 }\r
190                                                                                         }\r
191                                                                                 }\r
192 \r
193                                                                                 JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");\r
194                                                                                 if (relatedTPropArray != null) {\r
195                                                                                         Iterator i3 = relatedTPropArray.iterator();\r
196 \r
197                                                                                         while (i3.hasNext()) {\r
198                                                                                                 JSONObject inner3Obj = (JSONObject) i3.next();\r
199 \r
200                                                                                                 if (inner3Obj == null)\r
201                                                                                                         continue;\r
202 \r
203                                                                                                 String propKey = checkForNull((String) inner3Obj.get("property-key"));\r
204                                                                                                 String propVal = checkForNull((String) inner3Obj.get("property-value"));\r
205                                                                                                 if (propKey.equalsIgnoreCase("tenant.tenant-name")) {\r
206                                                                                                         tenantNewObj.put("tenantName", propVal);\r
207                                                                                                 }\r
208                                                                                         }\r
209                                                                                 }\r
210                                                                                 bconvert = true;\r
211                                                                                 tenantArray.add(tenantNewObj);\r
212                                                                         }\r
213                                                                 }\r
214                                                         }\r
215                                                 }\r
216                                         }\r
217                                 }\r
218                         }\r
219                 } catch (NullPointerException ex) {\r
220 \r
221 \r
222                 }\r
223 \r
224                 if (bconvert)\r
225                         return tenantArray.toJSONString();\r
226                 else\r
227                         return "";\r
228 \r
229         }\r
230 \r
231 \r
232 \r
233         /**\r
234          * Retrieve the service subscription from the jsonObject.\r
235          *\r
236          * @param jsonObject the json object\r
237          * @return String\r
238          */\r
239         public static String parseServiceSubscriptionObjectForTenants(JSONObject jsonObject) {\r
240 \r
241                 JSONArray tenantArray = new JSONArray();\r
242                 boolean bconvert = false;\r
243 \r
244                 try {\r
245                         JSONObject relationShipListsObj = (JSONObject) jsonObject.get("relationship-list");\r
246                         if (relationShipListsObj != null) {\r
247                                 JSONArray rShipArray = (JSONArray) relationShipListsObj.get("relationship");\r
248                                 if (rShipArray != null) {\r
249                                         Iterator i1 = rShipArray.iterator();\r
250 \r
251                                         while (i1.hasNext()) {\r
252 \r
253                                                 JSONObject inner1Obj = (JSONObject) i1.next();\r
254 \r
255                                                 if (inner1Obj == null)\r
256                                                         continue;\r
257 \r
258                                                 String relatedTo = checkForNull((String) inner1Obj.get("related-to"));\r
259                                                 if (relatedTo.equalsIgnoreCase("tenant")) {\r
260                                                         JSONObject tenantNewObj = new JSONObject();\r
261 \r
262                                                         String relatedLink = checkForNull((String) inner1Obj.get("related-link"));\r
263                                                         tenantNewObj.put("link", relatedLink);\r
264 \r
265                                                         JSONArray rDataArray = (JSONArray) inner1Obj.get("relationship-data");\r
266                                                         if (rDataArray != null) {\r
267                                                                 Iterator i2 = rDataArray.iterator();\r
268 \r
269                                                                 while (i2.hasNext()) {\r
270                                                                         JSONObject inner2Obj = (JSONObject) i2.next();\r
271 \r
272                                                                         if (inner2Obj == null)\r
273                                                                                 continue;\r
274 \r
275                                                                         String rShipKey = checkForNull((String) inner2Obj.get("relationship-key"));\r
276                                                                         String rShipVal = checkForNull((String) inner2Obj.get("relationship-value"));\r
277                                                                         if (rShipKey.equalsIgnoreCase("cloud-region.cloud-owner")) {\r
278                                                                                 tenantNewObj.put("cloudOwner", rShipVal);\r
279                                                                         } else if (rShipKey.equalsIgnoreCase("cloud-region.cloud-region-id")) {\r
280                                                                                 tenantNewObj.put("cloudRegionID", rShipVal);\r
281                                                                         }\r
282 \r
283                                                                         if (rShipKey.equalsIgnoreCase("tenant.tenant-id")) {\r
284                                                                                 tenantNewObj.put("tenantID", rShipVal);\r
285                                                                         }\r
286                                                                 }\r
287                                                         }\r
288 \r
289                                                         JSONArray relatedTPropArray = (JSONArray) inner1Obj.get("related-to-property");\r
290                                                         if (relatedTPropArray != null) {\r
291                                                                 Iterator i3 = relatedTPropArray.iterator();\r
292 \r
293                                                                 while (i3.hasNext()) {\r
294                                                                         JSONObject inner3Obj = (JSONObject) i3.next();\r
295 \r
296                                                                         if (inner3Obj == null)\r
297                                                                                 continue;\r
298 \r
299                                                                         String propKey = checkForNull((String) inner3Obj.get("property-key"));\r
300                                                                         String propVal = checkForNull((String) inner3Obj.get("property-value"));\r
301                                                                         if (propKey.equalsIgnoreCase("tenant.tenant-name")) {\r
302                                                                                 tenantNewObj.put("tenantName", propVal);\r
303                                                                         }\r
304                                                                 }\r
305                                                         }\r
306                                                         bconvert = true;\r
307                                                         tenantArray.add(tenantNewObj);\r
308                                                 }\r
309                                         }\r
310 \r
311                                 }\r
312                         }\r
313                 } catch (NullPointerException ex) {\r
314 \r
315 \r
316                 }\r
317 \r
318                 if (bconvert)\r
319                         return tenantArray.toJSONString();\r
320                 else\r
321                         return "";\r
322 \r
323         }\r
324 \r
325         /**\r
326          * Check for null.\r
327          *\r
328          * @param local the local\r
329          * @return the string\r
330          */\r
331         private static String checkForNull(String local) {\r
332                 if (local != null)\r
333                         return local;\r
334                 else\r
335                         return "";\r
336 \r
337         }\r
338 \r
339         /**\r
340          * Welcome method.\r
341          *\r
342          * @param request the request\r
343          * @return ModelAndView The view\r
344          */\r
345         @RequestMapping(value = {"/subscriberSearch"}, method = RequestMethod.GET)\r
346         public ModelAndView welcome(HttpServletRequest request) {\r
347                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== AaiController welcome start");\r
348                 return new ModelAndView(getViewName());\r
349         }\r
350 \r
351         @RequestMapping(value = {"/aai_get_aic_zones"}, method = RequestMethod.GET)\r
352         public  ResponseEntity<String> getAicZones(HttpServletRequest request) throws JsonGenerationException, JsonMappingException, IOException {\r
353                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== getAicZones controller start");\r
354                 AaiResponse response = aaiService.getAaiZones();\r
355                 return aaiResponseToResponseEntity(response);\r
356                         \r
357         }\r
358 \r
359         /* (non-Javadoc)\r
360          * @see org.openecomp.portalsdk.core.controller.RestrictedBaseController#getViewName()\r
361          */\r
362         public String getViewName() {\r
363                 return viewName;\r
364         }\r
365 \r
366         /* (non-Javadoc)\r
367          * @see org.openecomp.portalsdk.core.controller.RestrictedBaseController#setViewName(java.lang.String)\r
368          */\r
369         public void setViewName(String viewName) {\r
370                 this.viewName = viewName;\r
371         }\r
372 \r
373         /**\r
374          * Get services from a&ai.\r
375          *\r
376          * @return ResponseEntity<String> The response entity with the logged in user uuid.\r
377          * @throws IOException          Signals that an I/O exception has occurred.\r
378          * @throws InterruptedException the interrupted exception\r
379          */\r
380         @RequestMapping(value = {"/getuserID"}, method = RequestMethod.GET)\r
381         public ResponseEntity<String> getUserID(HttpServletRequest request) throws IOException, InterruptedException {\r
382 \r
383                 String userId = "";\r
384                 HttpSession session = request.getSession();\r
385                 if (session != null) {\r
386                         User user = (User) session.getAttribute(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME));\r
387                         if (user != null) {\r
388                                 //userId = user.getHrid();\r
389                                 userId = user.getLoginId();\r
390                                 if (userId == null)\r
391                                         userId = user.getOrgUserId();\r
392                         }\r
393                 }\r
394 \r
395                 return new ResponseEntity<String>(userId, HttpStatus.OK);\r
396         }\r
397 \r
398         /**\r
399          * Get services from a&ai.\r
400          *\r
401          * @return ResponseEntity<String> The response entity\r
402          * @throws IOException          Signals that an I/O exception has occurred.\r
403          * @throws InterruptedException the interrupted exception\r
404          */\r
405         @RequestMapping(value = "/aai_get_services", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)\r
406         public ResponseEntity<String> doGetServices(HttpServletRequest request) throws IOException, InterruptedException {\r
407         \r
408                 RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request));\r
409 \r
410                 AaiResponse subscriberList = aaiService.getServices(roleValidator);\r
411                 ResponseEntity<String> responseEntity = aaiResponseToResponseEntity( subscriberList);\r
412 \r
413                 return responseEntity;\r
414         }\r
415 \r
416 \r
417 \r
418         private ResponseEntity<String> aaiResponseToResponseEntity( AaiResponse aaiResponseData)\r
419                         throws IOException, JsonGenerationException, JsonMappingException {\r
420                 ResponseEntity<String> responseEntity;\r
421                 ObjectMapper objectMapper = new ObjectMapper();\r
422                 if (aaiResponseData.getHttpCode() == 200) {\r
423                         responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(aaiResponseData.getT()), HttpStatus.OK);\r
424                 } else {\r
425                         responseEntity = new ResponseEntity<String>(aaiResponseData.getErrorMessage(), HttpStatus.valueOf(aaiResponseData.getHttpCode()));\r
426                 }\r
427                 return responseEntity;\r
428         }\r
429 \r
430         /**\r
431          * Lookup single service instance in a&ai.  Get the service-subscription and customer, too, i guess?\r
432          *\r
433          * @param serviceInstanceId the service instance Id\r
434          * @return ResponseEntity The response entity\r
435          * @throws IOException          Signals that an I/O exception has occurred.\r
436          * @throws InterruptedException the interrupted exception\r
437          */\r
438         @RequestMapping(value = "/aai_get_service_instance/{service-instance-id}/{service-instance-type}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)\r
439         public ResponseEntity<String> doGetServiceInstance(@PathVariable("service-instance-id") String serviceInstanceId, @PathVariable("service-instance-type") String serviceInstanceType) throws IOException, InterruptedException {\r
440                 File certiPath = GetCertificatesPath();\r
441                 Response resp = null;\r
442 \r
443                 if (serviceInstanceType.equalsIgnoreCase("Service Instance Id")) {\r
444                         resp = doAaiGet(certiPath.getAbsolutePath(),\r
445                                         "search/nodes-query?search-node-type=service-instance&filter=service-instance-id:EQUALS:"\r
446                                                         + serviceInstanceId, false);\r
447                 } else {\r
448                         resp = doAaiGet(certiPath.getAbsolutePath(),\r
449                                         "search/nodes-query?search-node-type=service-instance&filter=service-instance-name:EQUALS:"\r
450                                                         + serviceInstanceId, false);\r
451                 }\r
452                 return convertResponseToResponseEntity(resp);\r
453         }\r
454 \r
455         /**\r
456          * Get services from a&ai.\r
457          *\r
458          * @param globalCustomerId      the global customer id\r
459          * @param serviceSubscriptionId the service subscription id\r
460          * @return ResponseEntity The response entity\r
461          * @throws IOException          Signals that an I/O exception has occurred.\r
462          * @throws InterruptedException the interrupted exception\r
463          */\r
464         @RequestMapping(value = "/aai_get_service_subscription/{global-customer-id}/{service-subscription-id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)\r
465         public ResponseEntity<String> doGetServices(@PathVariable("global-customer-id") String globalCustomerId,\r
466                         @PathVariable("service-subscription-id") String serviceSubscriptionId) throws IOException, InterruptedException {\r
467                 File certiPath = GetCertificatesPath();\r
468                 Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + globalCustomerId\r
469                                 + "/service-subscriptions/service-subscription/" + serviceSubscriptionId + "?depth=0", false);\r
470                 return convertResponseToResponseEntity(resp);\r
471         }\r
472 \r
473         /**\r
474          * Obtain the subscriber list from a&ai.\r
475          *\r
476          * @param fullSet the full set\r
477          * @return ResponseEntity The response entity\r
478          * @throws IOException          Signals that an I/O exception has occurred.\r
479          * @throws InterruptedException the interrupted exception\r
480          */\r
481         @RequestMapping(value = "/aai_get_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)\r
482         public ResponseEntity<String> doGetSubscriberList(HttpServletRequest request,@DefaultValue("n") @QueryParam("fullSet") String fullSet) throws IOException, InterruptedException {\r
483                 return getFullSubscriberList(request);\r
484         }\r
485 \r
486         /**\r
487          * Obtain the Target Prov Status from the System.Properties file.\r
488          *\r
489          * @return ResponseEntity The response entity\r
490          * @throws IOException          Signals that an I/O exception has occurred.\r
491          * @throws InterruptedException the interrupted exception\r
492          */\r
493         @RequestMapping(value = "/get_system_prop_vnf_prov_status", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)\r
494         public ResponseEntity<String> getTargetProvStatus() throws IOException, InterruptedException {\r
495                 String p = SystemProperties.getProperty("aai.vnf.provstatus");\r
496                 return new ResponseEntity<String>(p, HttpStatus.OK);\r
497         }\r
498 \r
499         /**\r
500          * Obtain the full subscriber list from a&ai.\r
501          * <p>\r
502          * g @return ResponseEntity The response entity\r
503          *\r
504          * @throws IOException          Signals that an I/O exception has occurred.\r
505          * @throws InterruptedException the interrupted exception\r
506          */\r
507         @RequestMapping(value = "/aai_get_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)\r
508         public ResponseEntity<String> getFullSubscriberList(HttpServletRequest request) throws IOException, InterruptedException {\r
509                 ObjectMapper objectMapper = new ObjectMapper();\r
510                 ResponseEntity<String> responseEntity;\r
511                 RoleValidator roleValidator = new RoleValidator(new RoleProvider().getUserRoles(request));\r
512                 SubscriberFilteredResults subscriberList = aaiService.getFullSubscriberList(roleValidator);\r
513                 if (subscriberList.getHttpCode() == 200) {\r
514                         responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(subscriberList.getSubscriberList()), HttpStatus.OK);\r
515                 } else {\r
516                         responseEntity = new ResponseEntity<String>(subscriberList.getErrorMessage(), HttpStatus.valueOf(subscriberList.getHttpCode()));\r
517                 }\r
518 \r
519 \r
520                 return responseEntity;\r
521         }\r
522 \r
523         /**\r
524          * Refresh the subscriber list from a&ai.\r
525          *\r
526          * @return ResponseEntity The response entity\r
527          * @throws IOException Signals that an I/O exception has occurred.\r
528          */\r
529         @RequestMapping(value = "/aai_refresh_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)\r
530         public ResponseEntity<String> doRefreshSubscriberList() throws IOException {\r
531                 Response resp = getSubscribers(false);\r
532                 return convertResponseToResponseEntity(resp);\r
533         }\r
534 \r
535         /**\r
536          * Refresh the full subscriber list from a&ai.\r
537          *\r
538          * @return ResponseEntity The response entity\r
539          * @throws IOException Signals that an I/O exception has occurred.\r
540          */\r
541         @RequestMapping(value = "/aai_refresh_full_subscribers", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)\r
542         public ResponseEntity<String> doRefreshFullSubscriberList() throws IOException {\r
543                 Response resp = getSubscribers(false);\r
544                 return convertResponseToResponseEntity(resp);\r
545         }\r
546 \r
547         /**\r
548          * Get subscriber details from a&ai.\r
549          *\r
550          * @param subscriberId the subscriber id\r
551          * @return ResponseEntity The response entity\r
552          */\r
553         @RequestMapping(value = "/aai_sub_details/{subscriberId}", method = RequestMethod.GET)\r
554         public ResponseEntity<String> GetSubscriberDetails(HttpServletRequest request,@PathVariable("subscriberId") String subscriberId) throws IOException {\r
555                 ObjectMapper objectMapper = new ObjectMapper();\r
556                 ResponseEntity responseEntity;\r
557                 List<Role> roles = new RoleProvider().getUserRoles(request);\r
558                 RoleValidator roleValidator = new RoleValidator(roles);\r
559                 AaiResponse<SubscriberData> subscriberData = aaiService.getSubscriberData(subscriberId,roleValidator);\r
560                 String httpMessage = subscriberData.getT() != null ?\r
561                                 objectMapper.writeValueAsString(subscriberData.getT()) :\r
562                                         subscriberData.getErrorMessage();\r
563 \r
564                                 responseEntity = new ResponseEntity<String>(httpMessage, HttpStatus.valueOf(subscriberData.getHttpCode()));\r
565                                 return responseEntity;\r
566         }\r
567 \r
568         /**\r
569          * Issue a named query to a&ai.\r
570          *\r
571          * @param namedQueryId     the named query id\r
572          * @param globalCustomerId the global customer id\r
573          * @param serviceType      the service type\r
574          * @param serviceInstance  the service instance\r
575          * @return ResponseEntity The response entity\r
576          */\r
577         @RequestMapping(value = "/aai_sub_viewedit/{namedQueryId}/{globalCustomerId}/{serviceType}/{serviceInstance}", method = RequestMethod.GET)\r
578         public ResponseEntity<String> viewEditGetComponentList(\r
579                         @PathVariable("namedQueryId") String namedQueryId,\r
580                         @PathVariable("globalCustomerId") String globalCustomerId,\r
581                         @PathVariable("serviceType") String serviceType,\r
582                         @PathVariable("serviceInstance") String serviceInstance) {\r
583 \r
584                 String componentListPayload = getComponentListPutPayload(namedQueryId, globalCustomerId, serviceType, serviceInstance);\r
585                 File certiPath = GetCertificatesPath();\r
586 \r
587                 Response resp = doAaiPost(certiPath.getAbsolutePath(), "search/named-query", componentListPayload, false);\r
588                 return convertResponseToResponseEntity(resp);\r
589         }\r
590 \r
591 \r
592         //      @RequestMapping(value="/aai_get_tenants/{global-customer-id}", method = RequestMethod.GET)\r
593         //      public ResponseEntity<String> viewEditGetComponentList(\r
594         //                      @PathVariable("global-customer-id") String globalCustomerId) {\r
595         //              return new ResponseEntity<String>(getTenants(globalCustomerId), HttpStatus.OK);\r
596         //      }\r
597 \r
598         /**\r
599          * Issue a named query to a&ai.\r
600          *\r
601          * @param namedQueryId     the named query id\r
602          * @param globalCustomerId the global customer id\r
603          * @param serviceType      the service type\r
604          * @return ResponseEntity The response entity\r
605          */\r
606         @RequestMapping(value = "/aai_get_models_by_service_type/{namedQueryId}/{globalCustomerId}/{serviceType}", method = RequestMethod.GET)\r
607         public ResponseEntity<String> viewEditGetComponentList(\r
608                         @PathVariable("namedQueryId") String namedQueryId,\r
609                         @PathVariable("globalCustomerId") String globalCustomerId,\r
610                         @PathVariable("serviceType") String serviceType) {\r
611 \r
612                 String componentListPayload = getModelsByServiceTypePayload(namedQueryId, globalCustomerId, serviceType);\r
613                 File certiPath = GetCertificatesPath();\r
614 \r
615                 Response resp = doAaiPost(certiPath.getAbsolutePath(), "search/named-query", componentListPayload, false);\r
616                 return convertResponseToResponseEntity(resp);\r
617         }\r
618 \r
619         /**\r
620          * Parses the for tenants.\r
621          *\r
622          * @param resp the resp\r
623          * @return the string\r
624          */\r
625         private String parseForTenants(String resp) {\r
626                 String tenantList = "";\r
627 \r
628                 try {\r
629                         JSONParser jsonParser = new JSONParser();\r
630 \r
631                         JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);\r
632 \r
633                         return parseCustomerObjectForTenants(jsonObject);\r
634                 } catch (Exception ex) {\r
635 \r
636                 }\r
637 \r
638                 return tenantList;\r
639         }\r
640 \r
641         /**\r
642          * Parses the for tenants by service subscription.\r
643          *\r
644          * @param resp the resp\r
645          * @return the string\r
646          */\r
647         private String parseForTenantsByServiceSubscription(String resp) {\r
648                 String tenantList = "";\r
649 \r
650                 try {\r
651                         JSONParser jsonParser = new JSONParser();\r
652 \r
653                         JSONObject jsonObject = (JSONObject) jsonParser.parse(resp);\r
654 \r
655                         return parseServiceSubscriptionObjectForTenants(jsonObject);\r
656                 } catch (Exception ex) {\r
657 \r
658                 }\r
659 \r
660                 return tenantList;\r
661         }\r
662 \r
663         /**\r
664          * Obtain tenants for a given service type.\r
665          *\r
666          * @param globalCustomerId the global customer id\r
667          * @param serviceType      the service type\r
668          * @return ResponseEntity The response entity\r
669          */\r
670         @RequestMapping(value = "/aai_get_tenants/{global-customer-id}/{service-type}", method = RequestMethod.GET)\r
671         public ResponseEntity<String> viewEditGetTenantsFromServiceType(HttpServletRequest request,\r
672                         @PathVariable("global-customer-id") String globalCustomerId, @PathVariable("service-type") String serviceType) {\r
673 \r
674                 ResponseEntity responseEntity;\r
675                 try {\r
676                         ObjectMapper objectMapper = new ObjectMapper();\r
677                         List<Role> roles = new RoleProvider().getUserRoles(request);\r
678                         RoleValidator roleValidator = new RoleValidator(roles);\r
679                         AaiResponse<GetTenantsResponse[]> response = aaiService.getTenants(globalCustomerId, serviceType, roleValidator);\r
680                         if (response.getHttpCode() == 200) {\r
681                                 responseEntity = new ResponseEntity<String>(objectMapper.writeValueAsString(response.getT()), HttpStatus.OK);\r
682                         } else {\r
683                                 responseEntity = new ResponseEntity<String>(response.getErrorMessage(), HttpStatus.valueOf(response.getHttpCode()));\r
684                         }\r
685                 }\r
686                 catch (Exception e){\r
687                         responseEntity = new ResponseEntity<String>("Unable to proccess getTenants reponse", HttpStatus.INTERNAL_SERVER_ERROR);\r
688                 }\r
689                 return responseEntity;\r
690         }\r
691 \r
692 \r
693         private ResponseEntity<String> convertResponseToResponseEntity(Response resp) {\r
694                 ResponseEntity<String> respEnt;\r
695                 ObjectMapper objectMapper = new ObjectMapper();\r
696                 if (resp == null) {\r
697                         respEnt = new ResponseEntity<String>("Failed to fetch data from A&AI, check server logs for details.", HttpStatus.INTERNAL_SERVER_ERROR);\r
698                 } else {\r
699                         respEnt = new ResponseEntity<String>(resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));\r
700                 }\r
701                 return respEnt;\r
702         }\r
703 \r
704         /**\r
705          * Gets the tenants.\r
706          *\r
707          * @param globalCustomerId the global customer id\r
708          * @return the tenants\r
709          */\r
710         private ResponseEntity<String> getTenants(String globalCustomerId) {\r
711                 File certiPath = GetCertificatesPath();\r
712                 Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + globalCustomerId, false);\r
713 \r
714                 ResponseEntity<String> respEnt;\r
715                 if (resp.getStatus() >= 200 && resp.getStatus() <= 299) {\r
716                         respEnt = new ResponseEntity<String>(parseForTenants((String) resp.readEntity(String.class)), HttpStatus.OK);\r
717                 } else {\r
718                         respEnt = new ResponseEntity<String>((String) resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));\r
719                 }\r
720                 return respEnt;\r
721 \r
722         }\r
723 \r
724         /**\r
725          * Gets the tenants from service type.\r
726          *\r
727          * @param globalCustomerId the global customer id\r
728          * @param serviceType      the service type\r
729          * @return the tenants from service type\r
730          */\r
731         private ResponseEntity<String> getTenantsFromServiceType(String globalCustomerId, String serviceType) {\r
732 \r
733 \r
734 \r
735 \r
736 \r
737                 File certiPath = GetCertificatesPath();\r
738                 String url = "business/customers/customer/" + globalCustomerId + "/service-subscriptions/service-subscription/" + serviceType;\r
739 \r
740                 Response resp = doAaiGet(certiPath.getAbsolutePath(), url, false);\r
741 \r
742                 ResponseEntity<String> respEnt;\r
743                 if (resp.getStatus() >= 200 && resp.getStatus() <= 299) {\r
744                         respEnt = new ResponseEntity<String>(parseForTenantsByServiceSubscription((String) resp.readEntity(String.class)), HttpStatus.OK);\r
745                 } else {\r
746                         respEnt = new ResponseEntity<String>((String) resp.readEntity(String.class), HttpStatus.valueOf(resp.getStatus()));\r
747                 }\r
748                 return respEnt;\r
749 \r
750         }\r
751 \r
752         /**\r
753          * Gets the services.\r
754          *\r
755          * @return the services\r
756          */\r
757         private Response getServices() {\r
758                 File certiPath = GetCertificatesPath();\r
759                 Response resp = doAaiGet(certiPath.getAbsolutePath(), "service-design-and-creation/services", false);\r
760                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getServices() resp=" + resp.getStatusInfo());\r
761 \r
762                 //model.put("aai_get_services", resp);\r
763                 return resp;\r
764         }\r
765 \r
766         /**\r
767          * Gets the subscribers.\r
768          *\r
769          * @param isFullSet the is full set\r
770          * @return the subscribers\r
771          */\r
772         private Response getSubscribers(boolean isFullSet) {\r
773 \r
774                 File certiPath = GetCertificatesPath();\r
775                 String depth = "0";\r
776 \r
777                 Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers?subscriber-type=INFRA&depth=" + depth, false);\r
778                 if (resp != null) {\r
779                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscribers() resp=" + resp.getStatusInfo().toString());\r
780                 }\r
781                 return resp;\r
782         }\r
783 \r
784         /**\r
785          * Gets the subscriber details.\r
786          *\r
787          * @param subscriberId the subscriber id\r
788          * @return the subscriber details\r
789          */\r
790         private Response getSubscriberDetails(String subscriberId) {\r
791                 File certiPath = GetCertificatesPath();\r
792                 Response resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId + "?depth=2", false);\r
793                 //String resp = doAaiGet(certiPath.getAbsolutePath(), "business/customers/customer/" + subscriberId, false);\r
794                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "getSubscriberDetails() resp=" + resp.getStatusInfo().toString());\r
795                 return resp;\r
796         }\r
797 \r
798         /**\r
799          * Gets the certificates path.\r
800          *\r
801          * @return the file\r
802          */\r
803         private File GetCertificatesPath() {\r
804                 if (servletContext != null)\r
805                         return new File(servletContext.getRealPath("/WEB-INF/cert/"));\r
806                 return null;\r
807         }\r
808 \r
809         /**\r
810          * Send a GET request to a&ai.\r
811          *\r
812          * @param certiPath the certi path\r
813          * @param uri       the uri\r
814          * @param xml       the xml\r
815          * @return String The response\r
816          */\r
817         protected Response doAaiGet(String certiPath, String uri, boolean xml) {\r
818                 String methodName = "getSubscriberList";\r
819                 String transId = UUID.randomUUID().toString();\r
820                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");\r
821 \r
822                 Response resp = null;\r
823                 try {\r
824 \r
825                         AAIRestInterface restContrller = new AAIRestInterface(certiPath);\r
826                         resp = restContrller.RestGet(fromAppId, transId, uri, xml);\r
827 \r
828                 } catch (WebApplicationException e) {\r
829                         final String message = ((BadRequestException) e).getResponse().readEntity(String.class);\r
830                         logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);\r
831                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + message);\r
832                 } catch (Exception e) {\r
833                         logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());\r
834                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());\r
835                 }\r
836 \r
837                 return resp;\r
838         }\r
839 \r
840         /**\r
841          * Send a POST request to a&ai.\r
842          *\r
843          * @param certiPath the certi path\r
844          * @param uri       the uri\r
845          * @param payload   the payload\r
846          * @param xml       the xml\r
847          * @return String The response\r
848          */\r
849         protected Response doAaiPost(String certiPath, String uri, String payload, boolean xml) {\r
850                 String methodName = "getSubscriberList";\r
851                 String transId = UUID.randomUUID().toString();\r
852                 logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + methodName + " start");\r
853 \r
854                 Response resp = null;\r
855                 try {\r
856 \r
857                         AAIRestInterface restContrller = new AAIRestInterface(certiPath);\r
858                         resp = restContrller.RestPost(fromAppId, transId, uri, payload, xml);\r
859 \r
860                 } catch (Exception e) {\r
861                         logger.info(EELFLoggerDelegate.errorLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());\r
862                         logger.debug(EELFLoggerDelegate.debugLogger, dateFormat.format(new Date()) + "<== " + "." + methodName + e.toString());\r
863                 }\r
864 \r
865                 return resp;\r
866         }\r
867 \r
868         /**\r
869          * Gets the component list put payload.\r
870          *\r
871          * @param namedQueryId     the named query id\r
872          * @param globalCustomerId the global customer id\r
873          * @param serviceType      the service type\r
874          * @param serviceInstance  the service instance\r
875          * @return the component list put payload\r
876          */\r
877         private String getComponentListPutPayload(String namedQueryId, String globalCustomerId, String serviceType, String serviceInstance) {\r
878                 return\r
879                                 "               {" +\r
880                                 "    \"instance-filters\": {" +\r
881                                 "        \"instance-filter\": [" +\r
882                                 "            {" +\r
883                                 "                \"customer\": {" +\r
884                                 "                    \"global-customer-id\": \"" + globalCustomerId + "\"" +\r
885                                 "                }," +\r
886                                 "                \"service-instance\": {" +\r
887                                 "                    \"service-instance-id\": \"" + serviceInstance + "\"" +\r
888                                 "                }," +\r
889                                 "                \"service-subscription\": {" +\r
890                                 "                    \"service-type\": \"" + serviceType + "\"" +\r
891                                 "                }" +\r
892                                 "            }" +\r
893                                 "        ]" +\r
894                                 "    }," +\r
895                                 "    \"query-parameters\": {" +\r
896                                 "        \"named-query\": {" +\r
897                                 "            \"named-query-uuid\": \"" + namedQueryId + "\"" +\r
898                                 "        }" +\r
899                                 "    }" +\r
900                                 "}";\r
901 \r
902         }\r
903 \r
904         private String getModelsByServiceTypePayload(String namedQueryId, String globalCustomerId, String serviceType) {\r
905                 // TODO Auto-generated method stub\r
906                 return "                {" +\r
907                 "    \"instance-filters\": {" +\r
908                 "        \"instance-filter\": [" +\r
909                 "            {" +\r
910                 "                \"customer\": {" +\r
911                 "                    \"global-customer-id\": \"" + globalCustomerId + "\"" +\r
912                 "                }," +\r
913                 "                \"service-subscription\": {" +\r
914                 "                    \"service-type\": \"" + serviceType + "\"" +\r
915                 "                }" +\r
916                 "            }" +\r
917                 "        ]" +\r
918                 "    }," +\r
919                 "    \"query-parameters\": {" +\r
920                 "        \"named-query\": {" +\r
921                 "            \"named-query-uuid\": \"" + namedQueryId + "\"" +\r
922                 "        }" +\r
923                 "    }" +\r
924                 "}";\r
925 \r
926         }\r
927 }\r
928 \r