ExternalAccessRolesController up
[portal.git] / portal-BE / src / main / java / org / onap / portal / controller / ExternalAccessRolesController.java
1 /*-
2  * ============LICENSE_START==========================================
3  * ONAP Portal
4  * ===================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ===================================================================
7  *
8  * Unless otherwise specified, all software contained herein is licensed
9  * under the Apache License, Version 2.0 (the "License");
10  * you may not use this software except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *             http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  *
21  * Unless otherwise specified, all documentation contained herein is licensed
22  * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
23  * you may not use this documentation except in compliance with the License.
24  * You may obtain a copy of the License at
25  *
26  *             https://creativecommons.org/licenses/by/4.0/
27  *
28  * Unless required by applicable law or agreed to in writing, documentation
29  * distributed under the License is distributed on an "AS IS" BASIS,
30  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31  * See the License for the specific language governing permissions and
32  * limitations under the License.
33  *
34  * ============LICENSE_END============================================
35  *
36  *
37  */
38
39 package org.onap.portal.controller;
40
41
42 import com.fasterxml.jackson.databind.DeserializationFeature;
43 import com.fasterxml.jackson.databind.ObjectMapper;
44 import com.fasterxml.jackson.databind.type.TypeFactory;
45 import io.swagger.annotations.ApiOperation;
46 import java.io.IOException;
47 import java.util.ArrayList;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Set;
52 import java.util.TreeSet;
53 import javax.servlet.http.HttpServletRequest;
54 import javax.servlet.http.HttpServletResponse;
55 import org.apache.commons.lang.StringUtils;
56 import org.onap.portal.domain.db.ep.EpAppFunction;
57 import org.onap.portal.domain.db.fn.FnApp;
58 import org.onap.portal.domain.db.fn.FnUser;
59 import org.onap.portal.domain.dto.PortalRestResponse;
60 import org.onap.portal.domain.dto.PortalRestStatusEnum;
61 import org.onap.portal.domain.dto.ecomp.EcompAuditLog;
62 import org.onap.portal.domain.dto.transport.CentralRole;
63 import org.onap.portal.domain.dto.transport.CentralRoleFunction;
64 import org.onap.portal.domain.dto.transport.CentralUser;
65 import org.onap.portal.domain.dto.transport.CentralV2Role;
66 import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
67 import org.onap.portal.exception.InvalidRoleException;
68 import org.onap.portal.logging.aop.EPAuditLog;
69 import org.onap.portal.logging.aop.EPEELFLoggerAdvice;
70 import org.onap.portal.logging.logic.EPLogUtil;
71 import org.onap.portal.service.ExternalAccessRolesService;
72 import org.onap.portal.service.user.FnUserService;
73 import org.onap.portal.utils.EPCommonSystemProperties;
74 import org.onap.portal.utils.EcompPortalUtils;
75 import org.onap.portal.utils.PortalConstants;
76 import org.onap.portal.validation.DataValidator;
77 import org.onap.portal.validation.SecureString;
78 import org.onap.portalsdk.core.domain.AuditLog;
79 import org.onap.portalsdk.core.domain.Role;
80 import org.onap.portalsdk.core.domain.User;
81 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
82 import org.onap.portalsdk.core.restful.domain.EcompRole;
83 import org.onap.portalsdk.core.restful.domain.EcompUser;
84 import org.onap.portalsdk.core.service.AuditService;
85 import org.onap.portalsdk.core.service.AuditServiceImpl;
86 import org.onap.portalsdk.core.service.UserServiceCentalizedImpl;
87 import org.onap.portalsdk.core.util.SystemProperties;
88 import org.onap.portalsdk.core.web.support.UserUtils;
89 import org.slf4j.MDC;
90 import org.springframework.beans.BeanUtils;
91 import org.springframework.beans.factory.annotation.Autowired;
92 import org.springframework.context.annotation.EnableAspectJAutoProxy;
93 import org.springframework.http.ResponseEntity;
94 import org.springframework.web.bind.annotation.PathVariable;
95 import org.springframework.web.bind.annotation.RequestBody;
96 import org.springframework.web.bind.annotation.RequestMapping;
97 import org.springframework.web.bind.annotation.RequestMethod;
98 import org.springframework.web.bind.annotation.RestController;
99
100 @RestController
101 @RequestMapping("/auxapi")
102 @EnableAspectJAutoProxy
103 @EPAuditLog
104 public class ExternalAccessRolesController {
105
106     private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
107     private static final String SUCCESSFULLY_DELETED = "Successfully Deleted";
108     private static final String INVALID_UEB_KEY = "Invalid credentials!";
109     private static final String LOGIN_ID = "LoginId";
110     private static final String UEBKEY = "uebkey";
111
112     private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesController.class);
113     private static final UserServiceCentalizedImpl userService = new UserServiceCentalizedImpl();
114     private static final AuditService auditService = new AuditServiceImpl();
115
116     private final ExternalAccessRolesService externalAccessRolesService;
117     private final FnUserService fnUserService;
118     private final DataValidator dataValidator;
119
120     @Autowired
121     public ExternalAccessRolesController(FnUserService fnUserService,
122         DataValidator dataValidator, ExternalAccessRolesService externalAccessRolesService) {
123         this.fnUserService = fnUserService;
124         this.dataValidator = dataValidator;
125         this.externalAccessRolesService = externalAccessRolesService;
126     }
127
128     @ApiOperation(value = "Gets user role for an application.", response = CentralUser.class, responseContainer = "List")
129     @RequestMapping(value = {
130         "/user/{loginId}"}, method = RequestMethod.GET, produces = "application/json")
131     public CentralUser getUser(HttpServletRequest request, HttpServletResponse response,
132         @PathVariable("loginId") String loginId) throws Exception {
133         if (!dataValidator.isValid(new SecureString(loginId))) {
134             sendErrorResponse(response, new Exception("Data is not valid"));
135             logger.error(EELFLoggerDelegate.errorLogger, "getUser not valid data");
136             return null;
137         }
138         CentralUser answer = null;
139         try {
140             fieldsValidation(request);
141             answer = externalAccessRolesService.getUserRoles(loginId, request.getHeader(UEBKEY));
142         } catch (Exception e) {
143             sendErrorResponse(response, e);
144             logger.error(EELFLoggerDelegate.errorLogger, "getUser failed", e);
145         }
146         return answer;
147     }
148
149     @ApiOperation(value = "Gets user roles for an application which is upgraded to newer version.", response = String.class, responseContainer = "List")
150     @RequestMapping(value = {
151         "/v1/user/{loginId}"}, method = RequestMethod.GET, produces = "application/json")
152     public String getV2UserList(HttpServletRequest request, HttpServletResponse response,
153         @PathVariable("loginId") String loginId) throws Exception {
154         if (!dataValidator.isValid(new SecureString(loginId))) {
155             sendErrorResponse(response, new Exception("Data is not valid"));
156             logger.error(EELFLoggerDelegate.errorLogger, "getV2UserList not valid data");
157             return "Data is not valid";
158         }
159         String answer = null;
160         try {
161             fieldsValidation(request);
162             answer = externalAccessRolesService.getV2UserWithRoles(loginId, request.getHeader(UEBKEY));
163         } catch (Exception e) {
164             sendErrorResponse(response, e);
165             logger.error(EELFLoggerDelegate.errorLogger, "getV2UserList failed", e);
166         }
167         return answer;
168     }
169
170     @ApiOperation(value = "Gets roles for an application.", response = CentralRole.class, responseContainer = "Json")
171     @RequestMapping(value = {
172         "/roles"}, method = RequestMethod.GET, produces = "application/json")
173     public List<CentralRole> getRolesForApp(HttpServletRequest request, HttpServletResponse response) throws Exception {
174         logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getRolesForApp");
175         List<CentralV2Role> v2CenRole;
176         List<CentralRole> cenRole = null;
177         try {
178             fieldsValidation(request);
179             FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
180             logger
181                 .debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into syncApplicationRolesWithEcompDB");
182             externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
183             logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished syncApplicationRolesWithEcompDB");
184             v2CenRole = externalAccessRolesService.getRolesForApp(request.getHeader(UEBKEY));
185             cenRole = externalAccessRolesService.convertV2CentralRoleListToOldVerisonCentralRoleList(v2CenRole);
186         } catch (Exception e) {
187             sendErrorResponse(response, e);
188             logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp failed", e);
189         }
190         logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getRolesForApp");
191         return cenRole;
192     }
193
194     @ApiOperation(value = "Gets roles for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer = "Json")
195     @RequestMapping(value = {
196         "/v1/roles"}, method = RequestMethod.GET, produces = "application/json")
197     public List<CentralV2Role> getV2RolesForApp(HttpServletRequest request, HttpServletResponse response)
198         throws Exception {
199         logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getV2RolesForApp");
200         List<CentralV2Role> answer = null;
201         try {
202             fieldsValidation(request);
203             FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
204             // Sync all roles from external system into ONAP portal DB
205             logger.debug(EELFLoggerDelegate.debugLogger,
206                 "getV2RolesForApp: Entering into syncApplicationRolesWithEcompDB");
207             externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
208             logger.debug(EELFLoggerDelegate.debugLogger, "getV2RolesForApp: Finished syncApplicationRolesWithEcompDB");
209             answer = externalAccessRolesService.getRolesForApp(request.getHeader(UEBKEY));
210         } catch (Exception e) {
211             sendErrorResponse(response, e);
212             logger.error(EELFLoggerDelegate.errorLogger, "getV2RolesForApp failed", e);
213         }
214         logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getV2RolesForApp");
215         return answer;
216     }
217
218     @ApiOperation(value = "Gets all role functions for an application for older version.", response = CentralRoleFunction.class, responseContainer = "Json")
219     @RequestMapping(value = {
220         "/functions"}, method = RequestMethod.GET, produces = "application/json")
221     public List<CentralRoleFunction> getRoleFunctionsList(HttpServletRequest request, HttpServletResponse response)
222         throws Exception {
223         List<EpAppFunction> answer;
224         List<CentralRoleFunction> roleFuncList = null;
225         logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getRoleFunctionsList");
226         try {
227             fieldsValidation(request);
228             FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
229             // Sync all functions from external system into ONAP portal DB
230             logger.debug(EELFLoggerDelegate.debugLogger,
231                 "getRoleFunctionsList: Entering into syncRoleFunctionFromExternalAccessSystem");
232             externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
233             logger.debug(EELFLoggerDelegate.debugLogger,
234                 "getRoleFunctionsList: Finished syncRoleFunctionFromExternalAccessSystem");
235             answer = externalAccessRolesService.getRoleFuncList(request.getHeader(UEBKEY));
236             roleFuncList = externalAccessRolesService.convertCentralRoleFunctionToRoleFunctionObject(answer);
237         } catch (Exception e) {
238             sendErrorResponse(response, e);
239             logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionsList failed", e);
240         }
241         logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getRoleFunctionsList");
242         return roleFuncList;
243     }
244
245     @ApiOperation(value = "Gets all role functions for an application which is upgraded to newer version.", response = EpAppFunction.class, responseContainer = "Json")
246     @RequestMapping(value = {
247         "/v1/functions"}, method = RequestMethod.GET, produces = "application/json")
248     public List<EpAppFunction> getV2RoleFunctionsList(HttpServletRequest request, HttpServletResponse response)
249         throws Exception {
250         List<EpAppFunction> cenRoleFuncList = null;
251         logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getV2RoleFunctionsList");
252         try {
253             fieldsValidation(request);
254             FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
255             // Sync all functions from external system into ONAP portal DB
256             logger.debug(EELFLoggerDelegate.debugLogger,
257                 "getV2RoleFunctionsList: Entering into syncRoleFunctionFromExternalAccessSystem");
258             externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
259             logger.debug(EELFLoggerDelegate.debugLogger,
260                 "getV2RoleFunctionsList: Finished syncRoleFunctionFromExternalAccessSystem");
261             cenRoleFuncList = externalAccessRolesService.getRoleFuncList(request.getHeader(UEBKEY));
262         } catch (Exception e) {
263             sendErrorResponse(response, e);
264             logger.error(EELFLoggerDelegate.errorLogger, "getV2RoleFunctionsList failed", e);
265         }
266         logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getV2RoleFunctionsList");
267         return cenRoleFuncList;
268     }
269
270
271     @ApiOperation(value = "Gets role information for an application.", response = CentralRole.class, responseContainer = "Json")
272     @RequestMapping(value = {
273         "/role/{role_id}"}, method = RequestMethod.GET, produces = "application/json")
274     public CentralRole getRoleInfo(HttpServletRequest request, HttpServletResponse response,
275         @PathVariable("role_id") Long roleId) throws Exception {
276         CentralV2Role answer;
277         CentralRole cenRole = null;
278         logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getRoleInfo");
279         try {
280             fieldsValidation(request);
281             answer = externalAccessRolesService.getRoleInfo(roleId, request.getHeader(UEBKEY));
282             cenRole = externalAccessRolesService.convertV2CentralRoleToOldVerisonCentralRole(answer);
283         } catch (Exception e) {
284             sendErrorResponse(response, e);
285             logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e);
286         }
287         logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getRoleInfo");
288         return cenRole;
289     }
290
291     @ApiOperation(value = "Gets v2 role information for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer = "Json")
292     @RequestMapping(value = {
293         "/v1/role/{role_id}"}, method = RequestMethod.GET, produces = "application/json")
294     public CentralV2Role getV2RoleInfo(HttpServletRequest request, HttpServletResponse response,
295         @PathVariable("role_id") Long roleId) throws Exception {
296         CentralV2Role answer = null;
297         logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getV2RoleInfo");
298         try {
299             fieldsValidation(request);
300             answer = externalAccessRolesService.getRoleInfo(roleId, request.getHeader(UEBKEY));
301         } catch (Exception e) {
302             sendErrorResponse(response, e);
303             logger.error(EELFLoggerDelegate.errorLogger, "getV2RoleInfo failed", e);
304         }
305         logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getV2RoleInfo");
306         return answer;
307     }
308
309     @ApiOperation(value = "Gets role information for an application provided by function code.", response = CentralRoleFunction.class, responseContainer = "Json")
310     @RequestMapping(value = {"/function/{code}"}, method = RequestMethod.GET, produces = "application/json")
311     public CentralRoleFunction getRoleFunction(HttpServletRequest request, HttpServletResponse response,
312         @PathVariable("code") String code) throws Exception {
313         EpAppFunction EpAppFunction;
314         CentralRoleFunction centralRoleFunction = new CentralRoleFunction();
315         if (!dataValidator.isValid(new SecureString(code))) {
316             sendErrorResponse(response, new Exception("Data is not valid"));
317             logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", new Exception("Data is not valid"));
318         }
319         try {
320             fieldsValidation(request);
321             EpAppFunction = externalAccessRolesService.getRoleFunction(code, request.getHeader(UEBKEY));
322             if (EpAppFunction != null && EcompPortalUtils.getFunctionCode(EpAppFunction.getFunctionCd()).equals(code)) {
323                 BeanUtils.copyProperties(EpAppFunction, centralRoleFunction, "type", "action");
324             }
325         } catch (Exception e) {
326             sendErrorResponse(response, e);
327             logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", e);
328         }
329         return centralRoleFunction;
330     }
331
332     @ApiOperation(value = "Gets role information for an application provided by function code.", response = EpAppFunction.class, responseContainer = "Json")
333     @RequestMapping(value = {"/v1/function/{code}"}, method = RequestMethod.GET, produces = "application/json")
334     public EpAppFunction getV2RoleFunction(HttpServletRequest request, HttpServletResponse response,
335         @PathVariable("code") String code) throws Exception {
336         EpAppFunction EpAppFunction = null;
337         if (!dataValidator.isValid(new SecureString(code))) {
338             sendErrorResponse(response, new Exception("Data is not valid"));
339             logger
340                 .error(EELFLoggerDelegate.errorLogger, "getV2RoleFunction failed", new Exception("Data is not valid"));
341         }
342         try {
343             fieldsValidation(request);
344             EpAppFunction = externalAccessRolesService.getRoleFunction(code, request.getHeader(UEBKEY));
345             if (EpAppFunction == null || !EcompPortalUtils.getFunctionCode(EpAppFunction.getFunctionCd())
346                 .equals(code)) {
347                 EpAppFunction = new EpAppFunction();
348             }
349         } catch (Exception e) {
350             sendErrorResponse(response, e);
351             logger.error(EELFLoggerDelegate.errorLogger, "getV2RoleFunction failed", e);
352         }
353         return EpAppFunction;
354     }
355
356     @ApiOperation(value = "Saves role function for an application.", response = PortalRestResponse.class, responseContainer = "Json")
357     @RequestMapping(value = {"/roleFunction"}, method = RequestMethod.POST, produces = "application/json")
358     public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response,
359         @RequestBody String roleFunc) {
360         String status = "Successfully saved!";
361         if (!dataValidator.isValid(new SecureString(roleFunc))) {
362             logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed");
363             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
364                 "Failed to roleFunc, not valid data.", "Failed");
365         }
366         try {
367             fieldsValidation(request);
368             ObjectMapper mapper = new ObjectMapper();
369             List<FnApp> applicationList = externalAccessRolesService.getApp(request.getHeader(UEBKEY));
370             FnApp requestedApp = applicationList.get(0);
371             mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
372             EpAppFunction availableRoleFunction = mapper.readValue(roleFunc, EpAppFunction.class);
373             EpAppFunction domainRoleFunction;
374             boolean isCentralV2Version = false;
375             if (availableRoleFunction.getType() != null && availableRoleFunction.getAction() != null) {
376                 isCentralV2Version = true;
377             }
378             if (isCentralV2Version) {
379                 String code = availableRoleFunction.getType() + "|" + availableRoleFunction.getFunctionCd() + "|"
380                     + availableRoleFunction.getAction();
381                 domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
382                     requestedApp.getUebKey());
383             } else {
384                 domainRoleFunction = externalAccessRolesService.getRoleFunction(availableRoleFunction.getFunctionCd(),
385                     requestedApp.getUebKey());
386             }
387
388             boolean saveOrUpdateResponse;
389             if (domainRoleFunction != null && isCentralV2Version && domainRoleFunction.getFunctionCd()
390                 .equals(availableRoleFunction.getFunctionCd())
391                 && domainRoleFunction.getType().equals(availableRoleFunction.getType())
392                 && domainRoleFunction.getAction().equals(availableRoleFunction.getAction())) {
393                 domainRoleFunction.setFunctionName(availableRoleFunction.getFunctionName());
394                 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
395                     requestedApp);
396             } else {
397                 availableRoleFunction.setAppId(requestedApp);
398                 saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(availableRoleFunction,
399                     requestedApp);
400             }
401
402             if (domainRoleFunction != null) {
403                 status = "Successfully updated!";
404             }
405             if (saveOrUpdateResponse) {
406                 FnUser user = fnUserService.loadUserByUsername(request.getHeader(LOGIN_ID));
407                 FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
408                 String activityCode = (!status.equals("Successfully updated!"))
409                     ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
410                     : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
411                 logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
412                     app.getId(), availableRoleFunction.getFunctionCd());
413                 AuditLog auditLog = new AuditLog();
414                 auditLog.setUserId(user.getId());
415                 auditLog.setActivityCode(activityCode);
416                 auditLog.setComments(
417                     EcompPortalUtils.truncateString(
418                         "saveRoleFunction role for app:" + app.getId() + " and function:'"
419                             + availableRoleFunction.getFunctionCd() + "'",
420                         PortalConstants.AUDIT_LOG_COMMENT_SIZE));
421                 auditLog.setAffectedRecordId(user.getOrgUserId());
422                 auditService.logActivity(auditLog, null);
423                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
424                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
425                 EcompPortalUtils.calculateDateTimeDifferenceForLog(
426                     MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
427                     MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
428                 logger.info(EELFLoggerDelegate.auditLogger,
429                     EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.saveRoleFunction", activityCode,
430                         String.valueOf(user.getId()), user.getOrgUserId(), availableRoleFunction.getFunctionCd()));
431                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
432                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
433                 MDC.remove(SystemProperties.MDC_TIMER);
434             } else {
435                 logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed");
436                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
437                     "Failed to saveRoleFunction for '" + availableRoleFunction.getFunctionCd() + "'", "Failed");
438             }
439         } catch (Exception e) {
440             if (e.getMessage() == null || e.getMessage().contains(INVALID_UEB_KEY)) {
441                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
442             } else {
443                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
444             }
445             logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e);
446             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
447         }
448         return new PortalRestResponse<>(PortalRestStatusEnum.OK, status, "Success");
449     }
450
451     @ApiOperation(value = "Deletes role function for an application.", response = PortalRestResponse.class, responseContainer = "Json")
452     @RequestMapping(value = {"/roleFunction/{code}"}, method = RequestMethod.DELETE, produces = "application/json")
453     public PortalRestResponse<String> deleteRoleFunction(HttpServletRequest request, HttpServletResponse response,
454         @PathVariable("code") String code) {
455         if (!dataValidator.isValid(new SecureString(code))) {
456             logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed");
457             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
458                 "Failed to deleteRoleFunction, not valid data.", "Failed");
459         }
460         try {
461             fieldsValidation(request);
462             FnUser user = fnUserService.loadUserByUsername(request.getHeader(LOGIN_ID));
463             FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
464             boolean getDelFuncResponse = externalAccessRolesService.deleteCentralRoleFunction(code, app);
465             if (getDelFuncResponse) {
466                 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRoleFunction: succeeded for app {}, role {}",
467                     app.getId(), code);
468                 AuditLog auditLog = new AuditLog();
469                 auditLog.setUserId(user.getId());
470                 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION);
471                 auditLog.setComments(EcompPortalUtils.truncateString(
472                     "Deleted function for app:" + app.getId() + " and function code:'" + code + "'",
473                     PortalConstants.AUDIT_LOG_COMMENT_SIZE));
474                 auditLog.setAffectedRecordId(user.getOrgUserId());
475                 auditService.logActivity(auditLog, null);
476                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
477                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
478                 EcompPortalUtils.calculateDateTimeDifferenceForLog(
479                     MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
480                     MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
481                 logger.info(EELFLoggerDelegate.auditLogger,
482                     EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.deleteRoleFunction",
483                         EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION, String.valueOf(user.getId()),
484                         user.getOrgUserId(), code));
485                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
486                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
487                 MDC.remove(SystemProperties.MDC_TIMER);
488             } else {
489                 logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed");
490                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
491                     "Failed to deleteRoleFunction for '" + code + "'", "Failed");
492             }
493         } catch (Exception e) {
494             if (e.getMessage().contains(INVALID_UEB_KEY)) {
495                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
496             } else {
497                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
498             }
499             logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed", e);
500             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
501         }
502         return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
503
504     }
505
506     @ApiOperation(value = "Saves role for an application.", response = PortalRestResponse.class, responseContainer = "Json")
507     @RequestMapping(value = {"/role"}, method = RequestMethod.POST, produces = "application/json")
508     public PortalRestResponse<String> saveRole(HttpServletRequest request, HttpServletResponse response,
509         @RequestBody Role role) {
510         try {
511             fieldsValidation(request);
512             ExternalRequestFieldsValidator saveRoleResult;
513             FnUser user = fnUserService.loadUserByUsername(request.getHeader(LOGIN_ID));
514             FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
515             if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
516                 throw new InvalidRoleException("Invalid role name found for '" + role.getName()
517                     + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
518             }
519             saveRoleResult = externalAccessRolesService.saveRoleForApplication(role, request.getHeader(UEBKEY));
520             if (saveRoleResult.isResult()) {
521                 String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
522                     : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
523                 logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
524                     app.getId(), role.getName());
525                 AuditLog auditLog = new AuditLog();
526                 auditLog.setUserId(user.getId());
527                 auditLog.setActivityCode(activityCode);
528                 auditLog.setComments(EcompPortalUtils.truncateString(
529                     "saveRole role for app:" + app.getId() + " and role:'" + role.getName() + "'",
530                     PortalConstants.AUDIT_LOG_COMMENT_SIZE));
531                 auditLog.setAffectedRecordId(user.getOrgUserId());
532                 auditService.logActivity(auditLog, null);
533                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
534                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
535                 EcompPortalUtils.calculateDateTimeDifferenceForLog(
536                     MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
537                     MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
538                 logger.info(EELFLoggerDelegate.auditLogger,
539                     EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.saveRole", activityCode,
540                         String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
541                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
542                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
543                 MDC.remove(SystemProperties.MDC_TIMER);
544             } else {
545                 if (saveRoleResult.getDetailMessage().contains("406")) {
546                     response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
547                     return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
548                         "Failed to create a role for '" + role.getName()
549                             + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed"
550                         , "Failed");
551                 } else {
552                     response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
553                     return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
554                         "Failed to saveRole for '" + role.getName() + "'", "Failed");
555                 }
556             }
557         } catch (Exception e) {
558             if (e.getMessage().contains(INVALID_UEB_KEY)) {
559                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
560             } else {
561                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
562             }
563             logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
564             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
565         }
566         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully Saved", "Success");
567     }
568
569     @ApiOperation(value = "Deletes role for an application.", response = PortalRestResponse.class, responseContainer = "Json")
570     @RequestMapping(value = {"/deleteRole/{code}"}, method = RequestMethod.DELETE, produces = "application/json")
571     public PortalRestResponse<String> deleteRole(HttpServletRequest request, HttpServletResponse response,
572         @PathVariable String code) {
573         if (!dataValidator.isValid(new SecureString(code))) {
574             logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed");
575             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
576                 "Failed to deleteRole, not valid data.", "Failed");
577         }
578         try {
579             fieldsValidation(request);
580             boolean deleteResponse = externalAccessRolesService.deleteRoleForApplication(code,
581                 request.getHeader(UEBKEY));
582             if (deleteResponse) {
583                 FnUser user = fnUserService.loadUserByUsername(request.getHeader(LOGIN_ID));
584                 FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
585                 logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
586                     app.getId(), code);
587                 AuditLog auditLog = new AuditLog();
588                 auditLog.setUserId(user.getId());
589                 auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE);
590                 auditLog.setComments(EcompPortalUtils.truncateString(
591                     "Deleted role for app:" + app.getId() + " and role:'" + code + "'",
592                     PortalConstants.AUDIT_LOG_COMMENT_SIZE));
593                 auditLog.setAffectedRecordId(user.getOrgUserId());
594                 auditService.logActivity(auditLog, null);
595                 MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
596                 MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
597                 EcompPortalUtils.calculateDateTimeDifferenceForLog(
598                     MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
599                     MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
600                 logger.info(EELFLoggerDelegate.auditLogger,
601                     EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.deleteRole",
602                         EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE, String.valueOf(user.getId()),
603                         user.getOrgUserId(), code));
604                 MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
605                 MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
606                 MDC.remove(SystemProperties.MDC_TIMER);
607             } else {
608                 logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed");
609                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
610                     "Failed to deleteRole for '" + code + "'", "Failed");
611             }
612         } catch (Exception e) {
613             if (e.getMessage().contains(INVALID_UEB_KEY)) {
614                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
615             } else {
616                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
617             }
618             logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed", e);
619             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
620         }
621         return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
622     }
623
624     @ApiOperation(value = "Gets active roles for an application.", response = CentralRole.class, responseContainer = "Json")
625     @RequestMapping(value = {"/activeRoles"}, method = RequestMethod.GET, produces = "application/json")
626     public List<CentralRole> getActiveRoles(HttpServletRequest request, HttpServletResponse response) throws Exception {
627         List<CentralRole> roles = null;
628         try {
629             fieldsValidation(request);
630             List<CentralV2Role> cenRoles = externalAccessRolesService.getActiveRoles(request.getHeader(UEBKEY));
631             roles = externalAccessRolesService.convertV2CentralRoleListToOldVerisonCentralRoleList(cenRoles);
632         } catch (Exception e) {
633             sendErrorResponse(response, e);
634             logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e);
635         }
636         return roles;
637
638     }
639
640     @ApiOperation(value = "Gets active roles for an application.", response = CentralV2Role.class, responseContainer = "Json")
641     @RequestMapping(value = {"/v1/activeRoles"}, method = RequestMethod.GET, produces = "application/json")
642     public List<CentralV2Role> getV2ActiveRoles(HttpServletRequest request, HttpServletResponse response)
643         throws Exception {
644         List<CentralV2Role> cenRole = null;
645         try {
646             fieldsValidation(request);
647             cenRole = externalAccessRolesService.getActiveRoles(request.getHeader(UEBKEY));
648         } catch (Exception e) {
649             sendErrorResponse(response, e);
650             logger.error(EELFLoggerDelegate.errorLogger, "getV2ActiveRoles failed", e);
651         }
652         return cenRole;
653
654     }
655
656     @ApiOperation(value = "deletes user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
657     @RequestMapping(value = {
658         "/deleteDependcyRoleRecord/{roleId}"}, method = RequestMethod.DELETE, produces = "application/json")
659     public PortalRestResponse<String> deleteDependencyRoleRecord(HttpServletRequest request,
660         HttpServletResponse response,
661         @PathVariable("roleId") Long roleId) {
662         ExternalRequestFieldsValidator removeResult;
663         try {
664             fieldsValidation(request);
665             removeResult = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
666                 request.getHeader(UEBKEY), request.getHeader(LOGIN_ID));
667             if (!removeResult.isResult()) {
668                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
669                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to deleteDependencyRoleRecord",
670                     "Failed");
671             }
672         } catch (Exception e) {
673             if (e.getMessage().contains(INVALID_UEB_KEY)) {
674                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
675             } else {
676                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
677             }
678             logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
679             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
680         }
681         return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
682     }
683
684
685     @ApiOperation(value = "deletes  roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
686     @RequestMapping(value = {"/v2/deleteRole/{roleId}"}, method = RequestMethod.DELETE, produces = "application/json")
687     public PortalRestResponse<String> deleteRole(HttpServletRequest request, HttpServletResponse response,
688         @PathVariable("roleId") Long roleId) {
689         ExternalRequestFieldsValidator removeResult;
690         try {
691             fieldsValidation(request);
692             removeResult = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
693                 request.getHeader(UEBKEY), request.getHeader(LOGIN_ID));
694             if (!removeResult.isResult()) {
695                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
696                 return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to deleteRole",
697                     "Failed");
698             }
699         } catch (Exception e) {
700             if (e.getMessage().contains(INVALID_UEB_KEY)) {
701                 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
702             } else {
703                 response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
704             }
705             logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed", e);
706             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
707         }
708         return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
709     }
710
711
712     @ApiOperation(value = "Bulk upload functions for an application.", response = PortalRestResponse.class, responseContainer = "Json")
713     @RequestMapping(value = {"/upload/portal/functions"}, method = RequestMethod.POST, produces = "application/json")
714     public PortalRestResponse<String> bulkUploadFunctions(HttpServletRequest request, HttpServletResponse response) {
715         Integer result;
716         try {
717             result = externalAccessRolesService.bulkUploadFunctions(request.getHeader(UEBKEY));
718         } catch (Exception e) {
719             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
720             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e);
721             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed");
722         }
723         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
724     }
725
726     @ApiOperation(value = "Bulk upload roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
727     @RequestMapping(value = {"/upload/portal/roles"}, method = RequestMethod.POST, produces = "application/json")
728     public PortalRestResponse<String> bulkUploadRoles(HttpServletRequest request, HttpServletResponse response) {
729         Integer result;
730         try {
731             result = externalAccessRolesService.bulkUploadRoles(request.getHeader(UEBKEY));
732         } catch (Exception e) {
733             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
734             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e);
735             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
736         }
737         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
738     }
739
740     @ApiOperation(value = "Bulk upload role functions for an application.", response = PortalRestResponse.class, responseContainer = "Json")
741     @RequestMapping(value = {
742         "/upload/portal/roleFunctions"}, method = RequestMethod.POST, produces = "application/json")
743     public PortalRestResponse<String> bulkUploadRoleFunctions(HttpServletRequest request,
744         HttpServletResponse response) {
745         Integer result;
746         try {
747             result = externalAccessRolesService.bulkUploadRolesFunctions(request.getHeader(UEBKEY));
748         } catch (Exception e) {
749             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
750             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoleFunctions failed", e);
751             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoleFunctions", "Failed");
752         }
753         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
754     }
755
756     @ApiOperation(value = "Bulk upload user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
757     @RequestMapping(value = {"/upload/portal/userRoles"}, method = RequestMethod.POST, produces = "application/json")
758     public PortalRestResponse<String> bulkUploadUserRoles(HttpServletRequest request, HttpServletResponse response) {
759         Integer result;
760         try {
761             result = externalAccessRolesService.bulkUploadUserRoles(request.getHeader(UEBKEY));
762         } catch (Exception e) {
763             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
764             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUserRoles failed", e);
765             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUserRoles", "Failed");
766         }
767         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
768     }
769
770     @ApiOperation(value = "Bulk upload users for renamed role of an application.", response = PortalRestResponse.class, responseContainer = "Json")
771     @RequestMapping(value = {
772         "/upload/portal/userRole/{roleId}"}, method = RequestMethod.POST, produces = "application/json")
773     public PortalRestResponse<String> bulkUploadUsersSingleRole(HttpServletRequest request,
774         HttpServletResponse response, @PathVariable Long roleId) {
775         Integer result;
776         try {
777             String roleName = request.getHeader("RoleName");
778             result = externalAccessRolesService.bulkUploadUsersSingleRole(request.getHeader(UEBKEY), roleId, roleName);
779         } catch (Exception e) {
780             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
781             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUsersSingleRole failed", e);
782             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUsersSingleRole",
783                 "Failed");
784         }
785         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
786     }
787
788     @ApiOperation(value = "Bulk upload functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json")
789     @RequestMapping(value = {"/upload/partner/functions"}, method = RequestMethod.POST, produces = "application/json")
790     public PortalRestResponse<String> bulkUploadPartnerFunctions(HttpServletRequest request,
791         HttpServletResponse response) {
792         Integer addedFunctions;
793         try {
794             addedFunctions = externalAccessRolesService.bulkUploadPartnerFunctions(request.getHeader(UEBKEY));
795         } catch (Exception e) {
796             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
797             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e);
798             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed");
799         }
800         return new PortalRestResponse<>(PortalRestStatusEnum.OK,
801             "Successfully added: '" + addedFunctions + "' functions", "Success");
802     }
803
804     @ApiOperation(value = "Bulk upload roles for an partner application.", response = PortalRestResponse.class, responseContainer = "Json")
805     @RequestMapping(value = {"/upload/partner/roles"}, method = RequestMethod.POST, produces = "application/json")
806     public PortalRestResponse<String> bulkUploadPartnerRoles(HttpServletRequest request, HttpServletResponse response,
807         @RequestBody List<Role> upload) {
808         try {
809             externalAccessRolesService.bulkUploadPartnerRoles(request.getHeader(UEBKEY), upload);
810         } catch (Exception e) {
811             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
812             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e);
813             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
814         }
815         return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added", "Success");
816     }
817
818     @ApiOperation(value = "Bulk upload role functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json")
819     @RequestMapping(value = {
820         "/upload/partner/roleFunctions"}, method = RequestMethod.POST, produces = "application/json")
821     public PortalRestResponse<String> bulkUploadPartnerRoleFunctions(HttpServletRequest request,
822         HttpServletResponse response) {
823         Integer addedRoleFunctions;
824         try {
825             addedRoleFunctions = externalAccessRolesService.bulkUploadPartnerRoleFunctions(request.getHeader(UEBKEY));
826         } catch (Exception e) {
827             response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
828             logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions failed", e);
829             return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadPartnerRoleFunctions",
830                 "Failed");
831         }
832         return new PortalRestResponse<>(PortalRestStatusEnum.OK,
833             "Successfully added: '" + addedRoleFunctions + "' role functions", "Success");
834     }
835
836     @ApiOperation(value = "Gets all functions along with global functions", response = List.class, responseContainer = "Json")
837     @RequestMapping(value = {"/menuFunctions"}, method = RequestMethod.GET, produces = "application/json")
838     public List<String> getMenuFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception {
839         List<String> functionsList = null;
840         try {
841             fieldsValidation(request);
842             functionsList = externalAccessRolesService.getMenuFunctionsList(request.getHeader(UEBKEY));
843         } catch (Exception e) {
844             sendErrorResponse(response, e);
845             logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctions failed", e);
846         }
847         return functionsList;
848     }
849
850     @ApiOperation(value = "Gets all active Users of application", response = String.class, responseContainer = "Json")
851     @RequestMapping(value = {"/users"}, method = RequestMethod.GET, produces = "application/json")
852     public List<EcompUser> getUsersOfApplication(HttpServletRequest request, HttpServletResponse response)
853         throws Exception {
854         List<EcompUser> users = null;
855         try {
856             fieldsValidation(request);
857             users = externalAccessRolesService.getAllAppUsers(request.getHeader(UEBKEY));
858         } catch (Exception e) {
859             sendErrorResponse(response, e);
860             logger.error(EELFLoggerDelegate.errorLogger, "getUsersOfApplication failed", e);
861         }
862         return users;
863     }
864
865     @ApiOperation(value = "Gets ecompUser of an application.", response = CentralUser.class, responseContainer = "List")
866     @RequestMapping(value = {"/v2/user/{loginId}"}, method = RequestMethod.GET, produces = "application/json")
867     public String getEcompUser(HttpServletRequest request, HttpServletResponse response,
868         @PathVariable("loginId") String loginId) throws Exception {
869         if (!dataValidator.isValid(new SecureString(loginId))) {
870             sendErrorResponse(response, new Exception("getEcompUser failed"));
871             logger.error(EELFLoggerDelegate.errorLogger, "getEcompUser failed", new Exception("getEcompUser failed"));
872         }
873         EcompUser user = new EcompUser();
874         ObjectMapper mapper = new ObjectMapper();
875         String answer;
876         try {
877             fieldsValidation(request);
878
879             answer = externalAccessRolesService.getV2UserWithRoles(loginId, request.getHeader(UEBKEY));
880             if (answer != null) {
881                 User ecompUser = userService.userMapper(answer);
882                 user = UserUtils.convertToEcompUser(ecompUser);
883                 List<EcompRole> missingRolesOfUser = externalAccessRolesService
884                     .missingUserApplicationRoles(request.getHeader(UEBKEY), loginId, user.getRoles());
885                 if (missingRolesOfUser.size() > 0) {
886                     Set<EcompRole> roles = new TreeSet<>(missingRolesOfUser);
887                     user.getRoles().addAll(roles);
888                 }
889             }
890         } catch (Exception e) {
891             sendErrorResponse(response, e);
892             logger.error(EELFLoggerDelegate.errorLogger, "getEcompUser failed", e);
893         }
894         return mapper.writeValueAsString(user);
895     }
896
897     @ApiOperation(value = "Gets user ecomp role for an application.", response = CentralUser.class, responseContainer = "List")
898     @RequestMapping(value = {"/v2/roles"}, method = RequestMethod.GET, produces = "application/json")
899     public List<EcompRole> getEcompRolesOfApplication(HttpServletRequest request, HttpServletResponse response)
900         throws Exception {
901         List<EcompRole> ecompRoles = null;
902         ObjectMapper mapper = new ObjectMapper();
903         List<CentralV2Role> cenRole = null;
904         try {
905             fieldsValidation(request);
906             FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
907             // Sync all roles from external system into ONAP portal DB
908             logger.debug(EELFLoggerDelegate.debugLogger,
909                 "getRolesForApp: Entering into syncApplicationRolesWithEcompDB");
910             externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
911             logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished syncApplicationRolesWithEcompDB");
912             cenRole = externalAccessRolesService.getActiveRoles(request.getHeader(UEBKEY));
913         } catch (Exception e) {
914             sendErrorResponse(response, e);
915             logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e);
916         }
917         if (cenRole != null) {
918             String res = mapper.writeValueAsString(cenRole);
919             ecompRoles = new ArrayList<>();
920             List<Role> roles = mapper.readValue(res,
921                 TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
922             for (Role role : roles) {
923                 ecompRoles.add(UserUtils.convertToEcompRole(role));
924             }
925             logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getEcompRolesOfApplication");
926         }
927         return ecompRoles;
928     }
929
930     private void sendErrorResponse(HttpServletResponse response, Exception e) throws IOException {
931         response.setContentType("application/json");
932         response.setCharacterEncoding("UTF-8");
933         final Map<String, String> uebkeyResponse = new HashMap<>();
934         ObjectMapper mapper = new ObjectMapper();
935         String reason;
936         if (e.getMessage().contains(INVALID_UEB_KEY)) {
937             uebkeyResponse.put("error", INVALID_UEB_KEY);
938             reason = mapper.writeValueAsString(uebkeyResponse);
939             response.getWriter().write(reason);
940             response.setStatus(HttpServletResponse.SC_NOT_FOUND);
941         } else {
942             uebkeyResponse.put("error", e.getMessage());
943             reason = mapper.writeValueAsString(uebkeyResponse);
944             response.getWriter().write(reason);
945             response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
946         }
947     }
948
949     private void fieldsValidation(HttpServletRequest request) throws Exception {
950         List<FnApp> app = externalAccessRolesService.getApp(request.getHeader(UEBKEY));
951         if (app.isEmpty()) {
952             throw new Exception(INVALID_UEB_KEY);
953         }
954         if (app.get(0).getAuthCentral()) {
955             ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(app.get(0));
956             if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND) {
957                 throw new Exception("Invalid NameSpace");
958             }
959         }
960     }
961 }