Merge "Updated DB scripts and Dockerfile.mariadb"
authorSunder Tattavarada <statta@research.att.com>
Wed, 18 Mar 2020 02:48:02 +0000 (02:48 +0000)
committerGerrit Code Review <gerrit@onap.org>
Wed, 18 Mar 2020 02:48:02 +0000 (02:48 +0000)
86 files changed:
portal-BE/pom.xml
portal-BE/src/main/java/org/onap/portal/controller/ExternalAccessRolesController.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/controller/MicroserviceController.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/controller/MicroserviceProxyController.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/controller/PortalAdminController.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/controller/RoleManageController.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemController.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemVersionController.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/controller/RolesController.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/controller/UserRolesController.java
portal-BE/src/main/java/org/onap/portal/controller/WidgetMSController.java
portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpAppFunction.java
portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpAppRoleFunction.java
portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpMicroserviceParameter.java
portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequest.java
portal-BE/src/main/java/org/onap/portal/domain/db/ep/EpUserRolesRequestDet.java
portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnApp.java
portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRole.java
portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnRoleFunction.java
portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUser.java
portal-BE/src/main/java/org/onap/portal/domain/db/fn/FnUserRole.java
portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/AppContactUs.java
portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPApp.java [deleted file]
portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPRole.java [deleted file]
portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUser.java [deleted file]
portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUserApp.java
portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/ExternalRoleDetails.java
portal-BE/src/main/java/org/onap/portal/domain/dto/fn/FnUserDto.java
portal-BE/src/main/java/org/onap/portal/domain/dto/model/ExternalSystemRoleApproval.java [moved from portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/PortalRestResponse.java with 83% similarity]
portal-BE/src/main/java/org/onap/portal/domain/dto/model/ExternalSystemUser.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralApp.java
portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralRole.java
portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralUser.java
portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2Role.java
portal-BE/src/main/java/org/onap/portal/domain/dto/transport/CentralV2User.java
portal-BE/src/main/java/org/onap/portal/domain/dto/transport/GlobalRoleWithApplicationRoleFunction.java
portal-BE/src/main/java/org/onap/portal/domain/dto/transport/PortalAdmin.java
portal-BE/src/main/java/org/onap/portal/domain/mapper/FnUserMapper.java
portal-BE/src/main/java/org/onap/portal/exception/DuplicateRecordException.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/exception/ExternalAuthSystemException.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/exception/InactiveApplicationException.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/exception/InvalidRoleException.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/exception/InvalidUserException.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/exception/NonCentralizedAppException.java [moved from portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/PortalRestStatusEnum.java with 79% similarity]
portal-BE/src/main/java/org/onap/portal/restTemplates/AAFTemplate.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/restTemplates/PortalWMSTemplate.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/service/AdminRolesService.java
portal-BE/src/main/java/org/onap/portal/service/BulkUploadUserRolesService.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/service/CentralizedAppService.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/service/ExternalAccessRolesService.java
portal-BE/src/main/java/org/onap/portal/service/LocalRoleService.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/service/MicroserviceProxyService.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/service/PortalAdminService.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/service/SearchService.java [new file with mode: 0644]
portal-BE/src/main/java/org/onap/portal/service/app/FnAppDao.java
portal-BE/src/main/java/org/onap/portal/service/app/FnAppService.java
portal-BE/src/main/java/org/onap/portal/service/appFunction/EpAppFunctionDao.java
portal-BE/src/main/java/org/onap/portal/service/appFunction/EpAppFunctionService.java
portal-BE/src/main/java/org/onap/portal/service/appRoleFunction/EpAppRoleFunctionDao.java
portal-BE/src/main/java/org/onap/portal/service/appRoleFunction/EpAppRoleFunctionService.java
portal-BE/src/main/java/org/onap/portal/service/microservice/EpMicroserviceService.java
portal-BE/src/main/java/org/onap/portal/service/microserviceParameter/EpMicroserviceParameterService.java
portal-BE/src/main/java/org/onap/portal/service/role/FnRoleDao.java
portal-BE/src/main/java/org/onap/portal/service/role/FnRoleService.java
portal-BE/src/main/java/org/onap/portal/service/roleFunction/FnRoleFunctionService.java
portal-BE/src/main/java/org/onap/portal/service/user/FnUserDao.java
portal-BE/src/main/java/org/onap/portal/service/user/FnUserService.java
portal-BE/src/main/java/org/onap/portal/service/userRole/FnUserRoleService.java
portal-BE/src/main/java/org/onap/portal/service/userRolesRequestDet/EpUserRolesRequestDetService.java
portal-BE/src/main/java/org/onap/portal/utils/EPSystemProperties.java [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/conf/cache.ccf [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/conf/quartz.properties [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/conf/raptor.properties [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/conf/raptor_app_fusion.properties [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/conf/raptor_db_fusion.properties [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/conf/raptor_pdf.properties [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/conf/scheduler.properties [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/conf/sql.properties [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/conf/system.properties [new file with mode: 0644]
portal-BE/src/main/resources/WEB-INF/fusion/conf/fusion.properties [new file with mode: 0644]
portal-BE/src/main/resources/application.properties
portal-BE/src/main/resources/test.properties
portal-BE/src/test/java/org/onap/portal/controller/UserControllerTest.java
portal-BE/src/test/java/org/onap/portal/controller/WidgetMSControllerTest.java
portal-BE/src/test/java/org/onap/portal/controller/WidgetsCatalogControllerTest.java
portal-BE/src/test/java/org/onap/portal/service/fn/FnUserServiceTest.java

index 77336be..cda52df 100644 (file)
           <version>2.10.0</version>
           <scope>compile</scope>
         </dependency>
+        <dependency>
+          <groupId>org.onap.portal.sdk</groupId>
+          <artifactId>epsdk-app-common</artifactId>
+          <version>2.6.0</version>
+          <scope>compile</scope>
+        </dependency>
       </dependencies>
       <properties>
             <docker.image.prefix>portal</docker.image.prefix>
+            <sonar.coverage.jacoco.xmlReportPaths>${project.reporting.outputDirectory}/jacoco-ut/jacoco.xml,${project.reporting.outputDirectory}/jacoco-it/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>
       </properties>
       <build>
             <plugins>
                               </execution>
                         </executions>
                   </plugin>
+                  <plugin>
+                        <groupId>org.jacoco</groupId>
+                        <artifactId>jacoco-maven-plugin</artifactId>
+                        <version>0.7.7.201606060606</version>
+                        <executions>
+                              <execution>
+                                    <goals>
+                                          <goal>prepare-agent</goal>
+                                    </goals>
+                              </execution>
+                              <execution>
+                                    <id>report</id>
+                                    <phase>prepare-package</phase>
+                                    <goals>
+                                          <goal>report</goal>
+                                    </goals>
+                              </execution>
+                        </executions>
+                  </plugin>
             </plugins>
             <resources>
                   <resource>
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/ExternalAccessRolesController.java b/portal-BE/src/main/java/org/onap/portal/controller/ExternalAccessRolesController.java
new file mode 100644 (file)
index 0000000..1e4b53e
--- /dev/null
@@ -0,0 +1,961 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+
+package org.onap.portal.controller;
+
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+import io.swagger.annotations.ApiOperation;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.apache.commons.lang.StringUtils;
+import org.onap.portal.domain.db.ep.EpAppFunction;
+import org.onap.portal.domain.db.fn.FnApp;
+import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.domain.dto.PortalRestResponse;
+import org.onap.portal.domain.dto.PortalRestStatusEnum;
+import org.onap.portal.domain.dto.ecomp.EcompAuditLog;
+import org.onap.portal.domain.dto.transport.CentralRole;
+import org.onap.portal.domain.dto.transport.CentralRoleFunction;
+import org.onap.portal.domain.dto.transport.CentralUser;
+import org.onap.portal.domain.dto.transport.CentralV2Role;
+import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
+import org.onap.portal.exception.InvalidRoleException;
+import org.onap.portal.logging.aop.EPAuditLog;
+import org.onap.portal.logging.aop.EPEELFLoggerAdvice;
+import org.onap.portal.logging.logic.EPLogUtil;
+import org.onap.portal.service.ExternalAccessRolesService;
+import org.onap.portal.service.user.FnUserService;
+import org.onap.portal.utils.EPCommonSystemProperties;
+import org.onap.portal.utils.EcompPortalUtils;
+import org.onap.portal.utils.PortalConstants;
+import org.onap.portal.validation.DataValidator;
+import org.onap.portal.validation.SecureString;
+import org.onap.portalsdk.core.domain.AuditLog;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.User;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.restful.domain.EcompRole;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+import org.onap.portalsdk.core.service.AuditService;
+import org.onap.portalsdk.core.service.AuditServiceImpl;
+import org.onap.portalsdk.core.service.UserServiceCentalizedImpl;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.UserUtils;
+import org.slf4j.MDC;
+import org.springframework.beans.BeanUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/auxapi")
+@EnableAspectJAutoProxy
+@EPAuditLog
+public class ExternalAccessRolesController {
+
+    private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
+    private static final String SUCCESSFULLY_DELETED = "Successfully Deleted";
+    private static final String INVALID_UEB_KEY = "Invalid credentials!";
+    private static final String LOGIN_ID = "LoginId";
+    private static final String UEBKEY = "uebkey";
+
+    private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesController.class);
+    private static final UserServiceCentalizedImpl userService = new UserServiceCentalizedImpl();
+    private static final AuditService auditService = new AuditServiceImpl();
+
+    private final ExternalAccessRolesService externalAccessRolesService;
+    private final FnUserService fnUserService;
+    private final DataValidator dataValidator;
+
+    @Autowired
+    public ExternalAccessRolesController(FnUserService fnUserService,
+        DataValidator dataValidator, ExternalAccessRolesService externalAccessRolesService) {
+        this.fnUserService = fnUserService;
+        this.dataValidator = dataValidator;
+        this.externalAccessRolesService = externalAccessRolesService;
+    }
+
+    @ApiOperation(value = "Gets user role for an application.", response = CentralUser.class, responseContainer = "List")
+    @RequestMapping(value = {
+        "/user/{loginId}"}, method = RequestMethod.GET, produces = "application/json")
+    public CentralUser getUser(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("loginId") String loginId) throws Exception {
+        if (!dataValidator.isValid(new SecureString(loginId))) {
+            sendErrorResponse(response, new Exception("Data is not valid"));
+            logger.error(EELFLoggerDelegate.errorLogger, "getUser not valid data");
+            return null;
+        }
+        CentralUser answer = null;
+        try {
+            fieldsValidation(request);
+            answer = externalAccessRolesService.getUserRoles(loginId, request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getUser failed", e);
+        }
+        return answer;
+    }
+
+    @ApiOperation(value = "Gets user roles for an application which is upgraded to newer version.", response = String.class, responseContainer = "List")
+    @RequestMapping(value = {
+        "/v1/user/{loginId}"}, method = RequestMethod.GET, produces = "application/json")
+    public String getV2UserList(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("loginId") String loginId) throws Exception {
+        if (!dataValidator.isValid(new SecureString(loginId))) {
+            sendErrorResponse(response, new Exception("Data is not valid"));
+            logger.error(EELFLoggerDelegate.errorLogger, "getV2UserList not valid data");
+            return "Data is not valid";
+        }
+        String answer = null;
+        try {
+            fieldsValidation(request);
+            answer = externalAccessRolesService.getV2UserWithRoles(loginId, request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getV2UserList failed", e);
+        }
+        return answer;
+    }
+
+    @ApiOperation(value = "Gets roles for an application.", response = CentralRole.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/roles"}, method = RequestMethod.GET, produces = "application/json")
+    public List<CentralRole> getRolesForApp(HttpServletRequest request, HttpServletResponse response) throws Exception {
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getRolesForApp");
+        List<CentralV2Role> v2CenRole;
+        List<CentralRole> cenRole = null;
+        try {
+            fieldsValidation(request);
+            FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
+            logger
+                .debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into syncApplicationRolesWithEcompDB");
+            externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
+            logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished syncApplicationRolesWithEcompDB");
+            v2CenRole = externalAccessRolesService.getRolesForApp(request.getHeader(UEBKEY));
+            cenRole = externalAccessRolesService.convertV2CentralRoleListToOldVerisonCentralRoleList(v2CenRole);
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp failed", e);
+        }
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getRolesForApp");
+        return cenRole;
+    }
+
+    @ApiOperation(value = "Gets roles for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/v1/roles"}, method = RequestMethod.GET, produces = "application/json")
+    public List<CentralV2Role> getV2RolesForApp(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getV2RolesForApp");
+        List<CentralV2Role> answer = null;
+        try {
+            fieldsValidation(request);
+            FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
+            // Sync all roles from external system into ONAP portal DB
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "getV2RolesForApp: Entering into syncApplicationRolesWithEcompDB");
+            externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
+            logger.debug(EELFLoggerDelegate.debugLogger, "getV2RolesForApp: Finished syncApplicationRolesWithEcompDB");
+            answer = externalAccessRolesService.getRolesForApp(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getV2RolesForApp failed", e);
+        }
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getV2RolesForApp");
+        return answer;
+    }
+
+    @ApiOperation(value = "Gets all role functions for an application for older version.", response = CentralRoleFunction.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/functions"}, method = RequestMethod.GET, produces = "application/json")
+    public List<CentralRoleFunction> getRoleFunctionsList(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        List<EpAppFunction> answer;
+        List<CentralRoleFunction> roleFuncList = null;
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getRoleFunctionsList");
+        try {
+            fieldsValidation(request);
+            FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
+            // Sync all functions from external system into ONAP portal DB
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "getRoleFunctionsList: Entering into syncRoleFunctionFromExternalAccessSystem");
+            externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "getRoleFunctionsList: Finished syncRoleFunctionFromExternalAccessSystem");
+            answer = externalAccessRolesService.getRoleFuncList(request.getHeader(UEBKEY));
+            roleFuncList = externalAccessRolesService.convertCentralRoleFunctionToRoleFunctionObject(answer);
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionsList failed", e);
+        }
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getRoleFunctionsList");
+        return roleFuncList;
+    }
+
+    @ApiOperation(value = "Gets all role functions for an application which is upgraded to newer version.", response = EpAppFunction.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/v1/functions"}, method = RequestMethod.GET, produces = "application/json")
+    public List<EpAppFunction> getV2RoleFunctionsList(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        List<EpAppFunction> cenRoleFuncList = null;
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getV2RoleFunctionsList");
+        try {
+            fieldsValidation(request);
+            FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
+            // Sync all functions from external system into ONAP portal DB
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "getV2RoleFunctionsList: Entering into syncRoleFunctionFromExternalAccessSystem");
+            externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "getV2RoleFunctionsList: Finished syncRoleFunctionFromExternalAccessSystem");
+            cenRoleFuncList = externalAccessRolesService.getRoleFuncList(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getV2RoleFunctionsList failed", e);
+        }
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getV2RoleFunctionsList");
+        return cenRoleFuncList;
+    }
+
+
+    @ApiOperation(value = "Gets role information for an application.", response = CentralRole.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/role/{role_id}"}, method = RequestMethod.GET, produces = "application/json")
+    public CentralRole getRoleInfo(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("role_id") Long roleId) throws Exception {
+        CentralV2Role answer;
+        CentralRole cenRole = null;
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getRoleInfo");
+        try {
+            fieldsValidation(request);
+            answer = externalAccessRolesService.getRoleInfo(roleId, request.getHeader(UEBKEY));
+            cenRole = externalAccessRolesService.convertV2CentralRoleToOldVerisonCentralRole(answer);
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo failed", e);
+        }
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getRoleInfo");
+        return cenRole;
+    }
+
+    @ApiOperation(value = "Gets v2 role information for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/v1/role/{role_id}"}, method = RequestMethod.GET, produces = "application/json")
+    public CentralV2Role getV2RoleInfo(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("role_id") Long roleId) throws Exception {
+        CentralV2Role answer = null;
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request received for getV2RoleInfo");
+        try {
+            fieldsValidation(request);
+            answer = externalAccessRolesService.getRoleInfo(roleId, request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getV2RoleInfo failed", e);
+        }
+        logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getV2RoleInfo");
+        return answer;
+    }
+
+    @ApiOperation(value = "Gets role information for an application provided by function code.", response = CentralRoleFunction.class, responseContainer = "Json")
+    @RequestMapping(value = {"/function/{code}"}, method = RequestMethod.GET, produces = "application/json")
+    public CentralRoleFunction getRoleFunction(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("code") String code) throws Exception {
+        EpAppFunction EpAppFunction;
+        CentralRoleFunction centralRoleFunction = new CentralRoleFunction();
+        if (!dataValidator.isValid(new SecureString(code))) {
+            sendErrorResponse(response, new Exception("Data is not valid"));
+            logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", new Exception("Data is not valid"));
+        }
+        try {
+            fieldsValidation(request);
+            EpAppFunction = externalAccessRolesService.getRoleFunction(code, request.getHeader(UEBKEY));
+            if (EpAppFunction != null && EcompPortalUtils.getFunctionCode(EpAppFunction.getFunctionCd()).equals(code)) {
+                BeanUtils.copyProperties(EpAppFunction, centralRoleFunction, "type", "action");
+            }
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction failed", e);
+        }
+        return centralRoleFunction;
+    }
+
+    @ApiOperation(value = "Gets role information for an application provided by function code.", response = EpAppFunction.class, responseContainer = "Json")
+    @RequestMapping(value = {"/v1/function/{code}"}, method = RequestMethod.GET, produces = "application/json")
+    public EpAppFunction getV2RoleFunction(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("code") String code) throws Exception {
+        EpAppFunction EpAppFunction = null;
+        if (!dataValidator.isValid(new SecureString(code))) {
+            sendErrorResponse(response, new Exception("Data is not valid"));
+            logger
+                .error(EELFLoggerDelegate.errorLogger, "getV2RoleFunction failed", new Exception("Data is not valid"));
+        }
+        try {
+            fieldsValidation(request);
+            EpAppFunction = externalAccessRolesService.getRoleFunction(code, request.getHeader(UEBKEY));
+            if (EpAppFunction == null || !EcompPortalUtils.getFunctionCode(EpAppFunction.getFunctionCd())
+                .equals(code)) {
+                EpAppFunction = new EpAppFunction();
+            }
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getV2RoleFunction failed", e);
+        }
+        return EpAppFunction;
+    }
+
+    @ApiOperation(value = "Saves role function for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/roleFunction"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response,
+        @RequestBody String roleFunc) {
+        String status = "Successfully saved!";
+        if (!dataValidator.isValid(new SecureString(roleFunc))) {
+            logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed");
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                "Failed to roleFunc, not valid data.", "Failed");
+        }
+        try {
+            fieldsValidation(request);
+            ObjectMapper mapper = new ObjectMapper();
+            List<FnApp> applicationList = externalAccessRolesService.getApp(request.getHeader(UEBKEY));
+            FnApp requestedApp = applicationList.get(0);
+            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+            EpAppFunction availableRoleFunction = mapper.readValue(roleFunc, EpAppFunction.class);
+            EpAppFunction domainRoleFunction;
+            boolean isCentralV2Version = false;
+            if (availableRoleFunction.getType() != null && availableRoleFunction.getAction() != null) {
+                isCentralV2Version = true;
+            }
+            if (isCentralV2Version) {
+                String code = availableRoleFunction.getType() + "|" + availableRoleFunction.getFunctionCd() + "|"
+                    + availableRoleFunction.getAction();
+                domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
+                    requestedApp.getUebKey());
+            } else {
+                domainRoleFunction = externalAccessRolesService.getRoleFunction(availableRoleFunction.getFunctionCd(),
+                    requestedApp.getUebKey());
+            }
+
+            boolean saveOrUpdateResponse;
+            if (domainRoleFunction != null && isCentralV2Version && domainRoleFunction.getFunctionCd()
+                .equals(availableRoleFunction.getFunctionCd())
+                && domainRoleFunction.getType().equals(availableRoleFunction.getType())
+                && domainRoleFunction.getAction().equals(availableRoleFunction.getAction())) {
+                domainRoleFunction.setFunctionName(availableRoleFunction.getFunctionName());
+                saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
+                    requestedApp);
+            } else {
+                availableRoleFunction.setAppId(requestedApp);
+                saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(availableRoleFunction,
+                    requestedApp);
+            }
+
+            if (domainRoleFunction != null) {
+                status = "Successfully updated!";
+            }
+            if (saveOrUpdateResponse) {
+                FnUser user = fnUserService.loadUserByUsername(request.getHeader(LOGIN_ID));
+                FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
+                String activityCode = (!status.equals("Successfully updated!"))
+                    ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
+                    : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
+                logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
+                    app.getId(), availableRoleFunction.getFunctionCd());
+                AuditLog auditLog = new AuditLog();
+                auditLog.setUserId(user.getId());
+                auditLog.setActivityCode(activityCode);
+                auditLog.setComments(
+                    EcompPortalUtils.truncateString(
+                        "saveRoleFunction role for app:" + app.getId() + " and function:'"
+                            + availableRoleFunction.getFunctionCd() + "'",
+                        PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+                auditLog.setAffectedRecordId(user.getOrgUserId());
+                auditService.logActivity(auditLog, null);
+                MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.saveRoleFunction", activityCode,
+                        String.valueOf(user.getId()), user.getOrgUserId(), availableRoleFunction.getFunctionCd()));
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                MDC.remove(SystemProperties.MDC_TIMER);
+            } else {
+                logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                    "Failed to saveRoleFunction for '" + availableRoleFunction.getFunctionCd() + "'", "Failed");
+            }
+        } catch (Exception e) {
+            if (e.getMessage() == null || e.getMessage().contains(INVALID_UEB_KEY)) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            } else {
+                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            }
+            logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, status, "Success");
+    }
+
+    @ApiOperation(value = "Deletes role function for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/roleFunction/{code}"}, method = RequestMethod.DELETE, produces = "application/json")
+    public PortalRestResponse<String> deleteRoleFunction(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("code") String code) {
+        if (!dataValidator.isValid(new SecureString(code))) {
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed");
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                "Failed to deleteRoleFunction, not valid data.", "Failed");
+        }
+        try {
+            fieldsValidation(request);
+            FnUser user = fnUserService.loadUserByUsername(request.getHeader(LOGIN_ID));
+            FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
+            boolean getDelFuncResponse = externalAccessRolesService.deleteCentralRoleFunction(code, app);
+            if (getDelFuncResponse) {
+                logger.info(EELFLoggerDelegate.applicationLogger, "deleteRoleFunction: succeeded for app {}, role {}",
+                    app.getId(), code);
+                AuditLog auditLog = new AuditLog();
+                auditLog.setUserId(user.getId());
+                auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION);
+                auditLog.setComments(EcompPortalUtils.truncateString(
+                    "Deleted function for app:" + app.getId() + " and function code:'" + code + "'",
+                    PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+                auditLog.setAffectedRecordId(user.getOrgUserId());
+                auditService.logActivity(auditLog, null);
+                MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.deleteRoleFunction",
+                        EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION, String.valueOf(user.getId()),
+                        user.getOrgUserId(), code));
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                MDC.remove(SystemProperties.MDC_TIMER);
+            } else {
+                logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                    "Failed to deleteRoleFunction for '" + code + "'", "Failed");
+            }
+        } catch (Exception e) {
+            if (e.getMessage().contains(INVALID_UEB_KEY)) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            } else {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            }
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleFunction failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
+
+    }
+
+    @ApiOperation(value = "Saves role for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/role"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> saveRole(HttpServletRequest request, HttpServletResponse response,
+        @RequestBody Role role) {
+        try {
+            fieldsValidation(request);
+            ExternalRequestFieldsValidator saveRoleResult;
+            FnUser user = fnUserService.loadUserByUsername(request.getHeader(LOGIN_ID));
+            FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
+            if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
+                throw new InvalidRoleException("Invalid role name found for '" + role.getName()
+                    + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
+            }
+            saveRoleResult = externalAccessRolesService.saveRoleForApplication(role, request.getHeader(UEBKEY));
+            if (saveRoleResult.isResult()) {
+                String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
+                    : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
+                logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
+                    app.getId(), role.getName());
+                AuditLog auditLog = new AuditLog();
+                auditLog.setUserId(user.getId());
+                auditLog.setActivityCode(activityCode);
+                auditLog.setComments(EcompPortalUtils.truncateString(
+                    "saveRole role for app:" + app.getId() + " and role:'" + role.getName() + "'",
+                    PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+                auditLog.setAffectedRecordId(user.getOrgUserId());
+                auditService.logActivity(auditLog, null);
+                MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.saveRole", activityCode,
+                        String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                MDC.remove(SystemProperties.MDC_TIMER);
+            } else {
+                if (saveRoleResult.getDetailMessage().contains("406")) {
+                    response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
+                    return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                        "Failed to create a role for '" + role.getName()
+                            + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed"
+                        , "Failed");
+                } else {
+                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                    return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                        "Failed to saveRole for '" + role.getName() + "'", "Failed");
+                }
+            }
+        } catch (Exception e) {
+            if (e.getMessage().contains(INVALID_UEB_KEY)) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            } else {
+                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            }
+            logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully Saved", "Success");
+    }
+
+    @ApiOperation(value = "Deletes role for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/deleteRole/{code}"}, method = RequestMethod.DELETE, produces = "application/json")
+    public PortalRestResponse<String> deleteRole(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable String code) {
+        if (!dataValidator.isValid(new SecureString(code))) {
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed");
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                "Failed to deleteRole, not valid data.", "Failed");
+        }
+        try {
+            fieldsValidation(request);
+            boolean deleteResponse = externalAccessRolesService.deleteRoleForApplication(code,
+                request.getHeader(UEBKEY));
+            if (deleteResponse) {
+                FnUser user = fnUserService.loadUserByUsername(request.getHeader(LOGIN_ID));
+                FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
+                logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
+                    app.getId(), code);
+                AuditLog auditLog = new AuditLog();
+                auditLog.setUserId(user.getId());
+                auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE);
+                auditLog.setComments(EcompPortalUtils.truncateString(
+                    "Deleted role for app:" + app.getId() + " and role:'" + code + "'",
+                    PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+                auditLog.setAffectedRecordId(user.getOrgUserId());
+                auditService.logActivity(auditLog, null);
+                MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    EPLogUtil.formatAuditLogMessage("ExternalAccessRolesController.deleteRole",
+                        EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE, String.valueOf(user.getId()),
+                        user.getOrgUserId(), code));
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                MDC.remove(SystemProperties.MDC_TIMER);
+            } else {
+                logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                    "Failed to deleteRole for '" + code + "'", "Failed");
+            }
+        } catch (Exception e) {
+            if (e.getMessage().contains(INVALID_UEB_KEY)) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            } else {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            }
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
+    }
+
+    @ApiOperation(value = "Gets active roles for an application.", response = CentralRole.class, responseContainer = "Json")
+    @RequestMapping(value = {"/activeRoles"}, method = RequestMethod.GET, produces = "application/json")
+    public List<CentralRole> getActiveRoles(HttpServletRequest request, HttpServletResponse response) throws Exception {
+        List<CentralRole> roles = null;
+        try {
+            fieldsValidation(request);
+            List<CentralV2Role> cenRoles = externalAccessRolesService.getActiveRoles(request.getHeader(UEBKEY));
+            roles = externalAccessRolesService.convertV2CentralRoleListToOldVerisonCentralRoleList(cenRoles);
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e);
+        }
+        return roles;
+
+    }
+
+    @ApiOperation(value = "Gets active roles for an application.", response = CentralV2Role.class, responseContainer = "Json")
+    @RequestMapping(value = {"/v1/activeRoles"}, method = RequestMethod.GET, produces = "application/json")
+    public List<CentralV2Role> getV2ActiveRoles(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        List<CentralV2Role> cenRole = null;
+        try {
+            fieldsValidation(request);
+            cenRole = externalAccessRolesService.getActiveRoles(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getV2ActiveRoles failed", e);
+        }
+        return cenRole;
+
+    }
+
+    @ApiOperation(value = "deletes user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/deleteDependcyRoleRecord/{roleId}"}, method = RequestMethod.DELETE, produces = "application/json")
+    public PortalRestResponse<String> deleteDependencyRoleRecord(HttpServletRequest request,
+        HttpServletResponse response,
+        @PathVariable("roleId") Long roleId) {
+        ExternalRequestFieldsValidator removeResult;
+        try {
+            fieldsValidation(request);
+            removeResult = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
+                request.getHeader(UEBKEY), request.getHeader(LOGIN_ID));
+            if (!removeResult.isResult()) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to deleteDependencyRoleRecord",
+                    "Failed");
+            }
+        } catch (Exception e) {
+            if (e.getMessage().contains(INVALID_UEB_KEY)) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            } else {
+                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            }
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
+    }
+
+
+    @ApiOperation(value = "deletes  roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/v2/deleteRole/{roleId}"}, method = RequestMethod.DELETE, produces = "application/json")
+    public PortalRestResponse<String> deleteRole(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("roleId") Long roleId) {
+        ExternalRequestFieldsValidator removeResult;
+        try {
+            fieldsValidation(request);
+            removeResult = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
+                request.getHeader(UEBKEY), request.getHeader(LOGIN_ID));
+            if (!removeResult.isResult()) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to deleteRole",
+                    "Failed");
+            }
+        } catch (Exception e) {
+            if (e.getMessage().contains(INVALID_UEB_KEY)) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            } else {
+                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            }
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteRole failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, SUCCESSFULLY_DELETED, "Success");
+    }
+
+
+    @ApiOperation(value = "Bulk upload functions for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/upload/portal/functions"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> bulkUploadFunctions(HttpServletRequest request, HttpServletResponse response) {
+        Integer result;
+        try {
+            result = externalAccessRolesService.bulkUploadFunctions(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
+    }
+
+    @ApiOperation(value = "Bulk upload roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/upload/portal/roles"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> bulkUploadRoles(HttpServletRequest request, HttpServletResponse response) {
+        Integer result;
+        try {
+            result = externalAccessRolesService.bulkUploadRoles(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
+    }
+
+    @ApiOperation(value = "Bulk upload role functions for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/upload/portal/roleFunctions"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> bulkUploadRoleFunctions(HttpServletRequest request,
+        HttpServletResponse response) {
+        Integer result;
+        try {
+            result = externalAccessRolesService.bulkUploadRolesFunctions(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoleFunctions failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoleFunctions", "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
+    }
+
+    @ApiOperation(value = "Bulk upload user roles for an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/upload/portal/userRoles"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> bulkUploadUserRoles(HttpServletRequest request, HttpServletResponse response) {
+        Integer result;
+        try {
+            result = externalAccessRolesService.bulkUploadUserRoles(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUserRoles failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUserRoles", "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
+    }
+
+    @ApiOperation(value = "Bulk upload users for renamed role of an application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/upload/portal/userRole/{roleId}"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> bulkUploadUsersSingleRole(HttpServletRequest request,
+        HttpServletResponse response, @PathVariable Long roleId) {
+        Integer result;
+        try {
+            String roleName = request.getHeader("RoleName");
+            result = externalAccessRolesService.bulkUploadUsersSingleRole(request.getHeader(UEBKEY), roleId, roleName);
+        } catch (Exception e) {
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadUsersSingleRole failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadUsersSingleRole",
+                "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added: " + result, "Success");
+    }
+
+    @ApiOperation(value = "Bulk upload functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/upload/partner/functions"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> bulkUploadPartnerFunctions(HttpServletRequest request,
+        HttpServletResponse response) {
+        Integer addedFunctions;
+        try {
+            addedFunctions = externalAccessRolesService.bulkUploadPartnerFunctions(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadFunctions", "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK,
+            "Successfully added: '" + addedFunctions + "' functions", "Success");
+    }
+
+    @ApiOperation(value = "Bulk upload roles for an partner application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {"/upload/partner/roles"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> bulkUploadPartnerRoles(HttpServletRequest request, HttpServletResponse response,
+        @RequestBody List<Role> upload) {
+        try {
+            externalAccessRolesService.bulkUploadPartnerRoles(request.getHeader(UEBKEY), upload);
+        } catch (Exception e) {
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadRoles", "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Successfully added", "Success");
+    }
+
+    @ApiOperation(value = "Bulk upload role functions for an partner application.", response = PortalRestResponse.class, responseContainer = "Json")
+    @RequestMapping(value = {
+        "/upload/partner/roleFunctions"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> bulkUploadPartnerRoleFunctions(HttpServletRequest request,
+        HttpServletResponse response) {
+        Integer addedRoleFunctions;
+        try {
+            addedRoleFunctions = externalAccessRolesService.bulkUploadPartnerRoleFunctions(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerRoleFunctions failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Failed to bulkUploadPartnerRoleFunctions",
+                "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK,
+            "Successfully added: '" + addedRoleFunctions + "' role functions", "Success");
+    }
+
+    @ApiOperation(value = "Gets all functions along with global functions", response = List.class, responseContainer = "Json")
+    @RequestMapping(value = {"/menuFunctions"}, method = RequestMethod.GET, produces = "application/json")
+    public List<String> getMenuFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception {
+        List<String> functionsList = null;
+        try {
+            fieldsValidation(request);
+            functionsList = externalAccessRolesService.getMenuFunctionsList(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctions failed", e);
+        }
+        return functionsList;
+    }
+
+    @ApiOperation(value = "Gets all active Users of application", response = String.class, responseContainer = "Json")
+    @RequestMapping(value = {"/users"}, method = RequestMethod.GET, produces = "application/json")
+    public List<EcompUser> getUsersOfApplication(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        List<EcompUser> users = null;
+        try {
+            fieldsValidation(request);
+            users = externalAccessRolesService.getAllAppUsers(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getUsersOfApplication failed", e);
+        }
+        return users;
+    }
+
+    @ApiOperation(value = "Gets ecompUser of an application.", response = CentralUser.class, responseContainer = "List")
+    @RequestMapping(value = {"/v2/user/{loginId}"}, method = RequestMethod.GET, produces = "application/json")
+    public String getEcompUser(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("loginId") String loginId) throws Exception {
+        if (!dataValidator.isValid(new SecureString(loginId))) {
+            sendErrorResponse(response, new Exception("getEcompUser failed"));
+            logger.error(EELFLoggerDelegate.errorLogger, "getEcompUser failed", new Exception("getEcompUser failed"));
+        }
+        EcompUser user = new EcompUser();
+        ObjectMapper mapper = new ObjectMapper();
+        String answer;
+        try {
+            fieldsValidation(request);
+
+            answer = externalAccessRolesService.getV2UserWithRoles(loginId, request.getHeader(UEBKEY));
+            if (answer != null) {
+                User ecompUser = userService.userMapper(answer);
+                user = UserUtils.convertToEcompUser(ecompUser);
+                List<EcompRole> missingRolesOfUser = externalAccessRolesService
+                    .missingUserApplicationRoles(request.getHeader(UEBKEY), loginId, user.getRoles());
+                if (missingRolesOfUser.size() > 0) {
+                    Set<EcompRole> roles = new TreeSet<>(missingRolesOfUser);
+                    user.getRoles().addAll(roles);
+                }
+            }
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getEcompUser failed", e);
+        }
+        return mapper.writeValueAsString(user);
+    }
+
+    @ApiOperation(value = "Gets user ecomp role for an application.", response = CentralUser.class, responseContainer = "List")
+    @RequestMapping(value = {"/v2/roles"}, method = RequestMethod.GET, produces = "application/json")
+    public List<EcompRole> getEcompRolesOfApplication(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        List<EcompRole> ecompRoles = null;
+        ObjectMapper mapper = new ObjectMapper();
+        List<CentralV2Role> cenRole = null;
+        try {
+            fieldsValidation(request);
+            FnApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0);
+            // Sync all roles from external system into ONAP portal DB
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "getRolesForApp: Entering into syncApplicationRolesWithEcompDB");
+            externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
+            logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished syncApplicationRolesWithEcompDB");
+            cenRole = externalAccessRolesService.getActiveRoles(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            sendErrorResponse(response, e);
+            logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles failed", e);
+        }
+        if (cenRole != null) {
+            String res = mapper.writeValueAsString(cenRole);
+            ecompRoles = new ArrayList<>();
+            List<Role> roles = mapper.readValue(res,
+                TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
+            for (Role role : roles) {
+                ecompRoles.add(UserUtils.convertToEcompRole(role));
+            }
+            logger.debug(EELFLoggerDelegate.debugLogger, "Request completed for getEcompRolesOfApplication");
+        }
+        return ecompRoles;
+    }
+
+    private void sendErrorResponse(HttpServletResponse response, Exception e) throws IOException {
+        response.setContentType("application/json");
+        response.setCharacterEncoding("UTF-8");
+        final Map<String, String> uebkeyResponse = new HashMap<>();
+        ObjectMapper mapper = new ObjectMapper();
+        String reason;
+        if (e.getMessage().contains(INVALID_UEB_KEY)) {
+            uebkeyResponse.put("error", INVALID_UEB_KEY);
+            reason = mapper.writeValueAsString(uebkeyResponse);
+            response.getWriter().write(reason);
+            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+        } else {
+            uebkeyResponse.put("error", e.getMessage());
+            reason = mapper.writeValueAsString(uebkeyResponse);
+            response.getWriter().write(reason);
+            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+        }
+    }
+
+    private void fieldsValidation(HttpServletRequest request) throws Exception {
+        List<FnApp> app = externalAccessRolesService.getApp(request.getHeader(UEBKEY));
+        if (app.isEmpty()) {
+            throw new Exception(INVALID_UEB_KEY);
+        }
+        if (app.get(0).getAuthCentral()) {
+            ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(app.get(0));
+            if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND) {
+                throw new Exception("Invalid NameSpace");
+            }
+        }
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/MicroserviceController.java b/portal-BE/src/main/java/org/onap/portal/controller/MicroserviceController.java
new file mode 100644 (file)
index 0000000..b20452b
--- /dev/null
@@ -0,0 +1,148 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+package org.onap.portal.controller;
+
+import java.util.List;
+import java.util.stream.Collectors;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.validation.Valid;
+import org.onap.portal.domain.db.ep.EpMicroservice;
+import org.onap.portal.domain.dto.PortalRestResponse;
+import org.onap.portal.domain.dto.PortalRestStatusEnum;
+import org.onap.portal.domain.dto.ecomp.WidgetCatalog;
+import org.onap.portal.restTemplates.PortalWMSTemplate;
+import org.onap.portal.service.microservice.EpMicroserviceService;
+import org.onap.portal.validation.DataValidator;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.core.ParameterizedTypeReference;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@SuppressWarnings("unchecked")
+@RestController
+@Configuration
+@EnableAspectJAutoProxy
+public class MicroserviceController {
+
+    private final DataValidator dataValidator = new DataValidator();
+
+    private final PortalWMSTemplate template;
+    private final EpMicroserviceService microserviceService;
+
+    @Autowired
+    public MicroserviceController(PortalWMSTemplate template, EpMicroserviceService microserviceService) {
+        this.template = template;
+        this.microserviceService = microserviceService;
+    }
+
+    @RequestMapping(value = {"/portalApi/microservices"}, method = RequestMethod.POST)
+    public PortalRestResponse<String> createMicroservice(HttpServletRequest request, HttpServletResponse response,
+        @Valid @RequestBody EpMicroservice newServiceData) {
+        if (newServiceData == null) {
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE",
+                "MicroserviceData cannot be null or empty");
+        } else {
+            if (!dataValidator.isValid(newServiceData)) {
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                    "ERROR", "MicroserviceData is not valid");
+            }
+        }
+        EpMicroservice serviceId = microserviceService.saveOne(newServiceData);
+        try {
+            microserviceService.saveServiceParameters(serviceId.getId(), newServiceData.getEpMicroserviceParameters());
+        } catch (Exception e) {
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", "");
+    }
+
+    @RequestMapping(value = {"/portalApi/microservices"}, method = RequestMethod.GET)
+    public List<EpMicroservice> getMicroservice(HttpServletRequest request, HttpServletResponse response) {
+        return microserviceService.getAll();
+    }
+
+    @RequestMapping(value = {"/portalApi/microservices/{serviceId}"}, method = RequestMethod.PUT)
+    public PortalRestResponse<String> updateMicroservice(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("serviceId") long serviceId, @Valid @RequestBody EpMicroservice newServiceData) {
+
+        if (newServiceData == null) {
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE",
+                "MicroserviceData cannot be null or empty");
+        } else {
+            if (!dataValidator.isValid(newServiceData)) {
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                    "ERROR", "MicroserviceData is not valid");
+            }
+        }
+        try {
+            microserviceService.updateMicroservice(serviceId, newServiceData);
+        } catch (Exception e) {
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", "");
+    }
+
+    @RequestMapping(value = {"/portalApi/microservices/{serviceId}"}, method = RequestMethod.DELETE)
+    public PortalRestResponse<String> deleteMicroservice(HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("serviceId") long serviceId) {
+        try {
+            ParameterizedTypeReference<List<WidgetCatalog>> typeRef = new ParameterizedTypeReference<List<WidgetCatalog>>() {
+            };
+            // If this service is assoicated with widgets, cannnot be deleted
+            ResponseEntity<List<WidgetCatalog>> ans = template.getWidgets(serviceId, typeRef);
+            List<WidgetCatalog> widgets = ans.getBody();
+            if (widgets.size() == 0) {
+                microserviceService.deleteById(serviceId);
+            } else {
+                String sb = widgets.stream().map(WidgetCatalog::getName).collect(Collectors.joining("' "));
+                return new PortalRestResponse<>(PortalRestStatusEnum.WARN, "SOME WIDGETS ASSOICATE WITH THIS SERVICE",
+                    sb);
+            }
+        } catch (Exception e) {
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "FAILURE", e.getMessage());
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "SUCCESS", "");
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/MicroserviceProxyController.java b/portal-BE/src/main/java/org/onap/portal/controller/MicroserviceProxyController.java
new file mode 100644 (file)
index 0000000..3a4fd96
--- /dev/null
@@ -0,0 +1,116 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+package org.onap.portal.controller;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.io.IOException;
+import java.security.Principal;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.service.MicroserviceProxyService;
+import org.onap.portal.service.user.FnUserService;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.client.HttpClientErrorException;
+
+@RestController
+@Configuration
+@EnableAspectJAutoProxy
+public class MicroserviceProxyController {
+
+    private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyController.class);
+
+    private final MicroserviceProxyService microserviceProxyService;
+    private final FnUserService fnUserService;
+
+    @Autowired
+    public MicroserviceProxyController(MicroserviceProxyService microserviceProxyService,
+        FnUserService fnUserService) {
+        this.microserviceProxyService = microserviceProxyService;
+        this.fnUserService = fnUserService;
+    }
+
+    @RequestMapping(value = {"/portalApi/microservice/proxy/{serviceId}"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public String getMicroserviceProxy(Principal principal, HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("serviceId") long serviceId) throws Exception {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        String answer = "";
+        try {
+            answer = microserviceProxyService.proxyToDestination(serviceId, user, request);
+        } catch (HttpClientErrorException e) {
+            answer = e.getResponseBodyAsString();
+        }
+        return isValidJSON(answer) ? answer
+            : "{\"error\":\"" + answer.replace(System.getProperty("line.separator"), "") + "\"}";
+    }
+
+    @RequestMapping(value = {"/portalApi/microservice/proxy/parameter/{widgetId}"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public String getMicroserviceProxyByWidgetId(Principal principal, HttpServletRequest request,
+        HttpServletResponse response,
+        @PathVariable("widgetId") long widgetId) throws Exception {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        String answer = "";
+        try {
+            answer = microserviceProxyService.proxyToDestinationByWidgetId(widgetId, user, request);
+        } catch (HttpClientErrorException e) {
+            answer = e.getResponseBodyAsString();
+        }
+        return isValidJSON(answer) ? answer
+            : "{\"error\":\"" + answer.replace(System.getProperty("line.separator"), "") + "\"}";
+    }
+
+    private boolean isValidJSON(String response) {
+        try {
+            final ObjectMapper mapper = new ObjectMapper();
+            mapper.readTree(response);
+            return true;
+        } catch (IOException e) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "isValidJSON failed", e);
+            return false;
+        }
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/PortalAdminController.java b/portal-BE/src/main/java/org/onap/portal/controller/PortalAdminController.java
new file mode 100644 (file)
index 0000000..b947718
--- /dev/null
@@ -0,0 +1,236 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+package org.onap.portal.controller;
+
+import java.security.Principal;
+import java.util.List;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.onap.portal.domain.db.fn.FnRole;
+import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.domain.dto.ecomp.EcompAuditLog;
+import org.onap.portal.domain.dto.transport.FieldsValidator;
+import org.onap.portal.domain.dto.transport.PortalAdmin;
+import org.onap.portal.logging.aop.EPEELFLoggerAdvice;
+import org.onap.portal.logging.logic.EPLogUtil;
+import org.onap.portal.service.AdminRolesService;
+import org.onap.portal.service.PortalAdminService;
+import org.onap.portal.service.user.FnUserService;
+import org.onap.portal.utils.EPCommonSystemProperties;
+import org.onap.portal.utils.EcompPortalUtils;
+import org.onap.portal.validation.DataValidator;
+import org.onap.portal.validation.SecureString;
+import org.onap.portalsdk.core.domain.AuditLog;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.AuditService;
+import org.onap.portalsdk.core.service.AuditServiceImpl;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@Configuration
+@EnableAspectJAutoProxy
+public class PortalAdminController {
+
+    private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminController.class);
+    private static final DataValidator DATA_VALIDATOR = new DataValidator();
+
+    private PortalAdminService portalAdminService;
+    private final FnUserService fnUserService;
+    private AdminRolesService adminRolesService;
+    private AuditServiceImpl auditService = new AuditServiceImpl();
+
+    @Autowired
+    public PortalAdminController(PortalAdminService portalAdminService,
+        FnUserService fnUserService, AdminRolesService adminRolesService) {
+        this.portalAdminService = portalAdminService;
+        this.fnUserService = fnUserService;
+        this.adminRolesService = adminRolesService;
+    }
+
+    @RequestMapping(value = {"/portalApi/portalAdmins"}, method = RequestMethod.GET, produces = "application/json")
+    public List<PortalAdmin> getPortalAdmins(Principal principal, HttpServletRequest request,
+        HttpServletResponse response) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        List<PortalAdmin> portalAdmins = null;
+        if (user == null) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, null user");
+            EcompPortalUtils.setBadPermissions(user, response, "getPortalAdmins");
+        } else if (!adminRolesService.isSuperAdmin(user.getLoginId())) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.getPortalAdmins, bad permissions");
+            EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+        } else {
+            // return the list of portal admins
+            portalAdmins = portalAdminService.getPortalAdmins();
+            logger.debug(EELFLoggerDelegate.debugLogger, "portalAdmins: called getPortalAdmins()");
+            EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/getPortalAdmins", "result =", portalAdmins);
+        }
+
+        return portalAdmins;
+    }
+
+    @RequestMapping(value = {"/portalApi/portalAdmin"}, method = RequestMethod.POST)
+    public FieldsValidator createPortalAdmin(Principal principal, HttpServletRequest request,
+        @RequestBody String userId,
+        HttpServletResponse response) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        FieldsValidator fieldsValidator = null;
+        if (!DATA_VALIDATOR.isValid(new SecureString(userId))) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin not valid userId");
+            EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+        } else if (user == null) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin, null user");
+            EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+        } else if (!adminRolesService.isSuperAdmin(user.getLoginId())) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.createPortalAdmin bad permissions");
+            EcompPortalUtils.setBadPermissions(user, response, "createPortalAdmin");
+        } else {
+            fieldsValidator = portalAdminService.createPortalAdmin(userId);
+            int statusCode = fieldsValidator.getHttpStatusCode().intValue();
+            response.setStatus(statusCode);
+            if (statusCode == 200) {
+                AuditLog auditLog = new AuditLog();
+                auditLog.setUserId(user.getId());
+                auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN);
+                auditLog.setAffectedRecordId(userId);
+                try {
+                    auditService.logActivity(auditLog, null);
+                } catch (Exception e) {
+                    logger.error(EELFLoggerDelegate.errorLogger, "createPortalAdmin: failed for save audit log", e);
+                }
+                MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    EPLogUtil.formatAuditLogMessage("PortalAdminController.createPortalAdmin",
+                        EcompAuditLog.CD_ACTIVITY_ADD_PORTAL_ADMIN, user.getOrgUserId(), userId,
+                        "A new Portal Admin has been added"));
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                MDC.remove(SystemProperties.MDC_TIMER);
+            }
+        }
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "POST result =", response.getStatus());
+
+        return fieldsValidator;
+    }
+
+    @RequestMapping(value = {"/portalApi/portalAdmin/{userInfo}"}, method = RequestMethod.DELETE)
+    public FieldsValidator deletePortalAdmin(Principal principal, HttpServletRequest request,
+        @PathVariable("userInfo") String userInfo,
+        HttpServletResponse response) {
+        if (!DATA_VALIDATOR.isValid(new SecureString(userInfo))) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "PortalAdminController.deletePortalAdmin not valid userId");
+            return null;
+        }
+        int userIdIdx = userInfo.indexOf("-");
+        Long userId = null;
+        String sbcid = null;
+        FieldsValidator fieldsValidator = null;
+        try {
+            if (userIdIdx == -1) {
+                logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin missing userId");
+                return fieldsValidator;
+            } else {
+                String userIdStr = userInfo.substring(0, userIdIdx);
+                userId = Long.valueOf(userIdStr);
+                sbcid = userInfo.substring(userIdIdx + 1, userInfo.length());
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin error while parsing the userInfo", e);
+        }
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        if (!adminRolesService.isSuperAdmin(user.getLoginId())) {
+            EcompPortalUtils.setBadPermissions(user, response, "deletePortalAdmin");
+        } else {
+            fieldsValidator = portalAdminService.deletePortalAdmin(userId);
+            int statusCode = fieldsValidator.getHttpStatusCode().intValue();
+            response.setStatus(statusCode);
+            if (statusCode == 200) {
+                AuditLog auditLog = new AuditLog();
+                auditLog.setUserId(user.getId());
+                auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN);
+                auditLog.setAffectedRecordId(sbcid);
+                auditService.logActivity(auditLog, null);
+                MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                    MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    EPLogUtil.formatAuditLogMessage("PortalAdminController.deletePortalAdmin",
+                        EcompAuditLog.CD_ACTIVITY_DELETE_PORTAL_ADMIN, user.getOrgUserId(), sbcid,
+                        "A Portal Admin has been deleted"));
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                MDC.remove(SystemProperties.MDC_TIMER);
+            }
+        }
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalAdmin", "DELETE result =", response.getStatus());
+
+        return fieldsValidator;
+    }
+
+    @RequestMapping(value = {
+        "/portalApi/adminAppsRoles/{appId}"}, method = RequestMethod.GET, produces = "application/json")
+    public List<FnRole> getRolesByApp(Principal principal, HttpServletRequest request,
+        @PathVariable("appId") Long appId, HttpServletResponse response) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        List<FnRole> rolesByApp = null;
+        try {
+            if (user == null) {
+                EcompPortalUtils.setBadPermissions(user, response, "getUserApps");
+            } else {
+                rolesByApp = adminRolesService.getRolesByApp(appId);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getRolesByApp failed", e);
+        }
+        return rolesByApp;
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/RoleManageController.java b/portal-BE/src/main/java/org/onap/portal/controller/RoleManageController.java
new file mode 100644 (file)
index 0000000..dc4a575
--- /dev/null
@@ -0,0 +1,851 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+package org.onap.portal.controller;
+
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+import java.io.IOException;
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import javax.management.InvalidApplicationException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.validation.ConstraintViolation;
+import javax.validation.Valid;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import org.apache.commons.lang.StringUtils;
+import org.json.JSONObject;
+import org.onap.portal.domain.db.ep.EpAppFunction;
+import org.onap.portal.domain.db.fn.FnApp;
+import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.domain.dto.PortalRestResponse;
+import org.onap.portal.domain.dto.PortalRestStatusEnum;
+import org.onap.portal.domain.dto.ecomp.CentralizedApp;
+import org.onap.portal.domain.dto.ecomp.EcompAuditLog;
+import org.onap.portal.domain.dto.ecomp.UploadRoleFunctionExtSystem;
+import org.onap.portal.domain.dto.transport.CentralV2Role;
+import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
+import org.onap.portal.exception.DuplicateRecordException;
+import org.onap.portal.exception.InvalidRoleException;
+import org.onap.portal.exception.NonCentralizedAppException;
+import org.onap.portal.logging.aop.EPEELFLoggerAdvice;
+import org.onap.portal.logging.logic.EPLogUtil;
+import org.onap.portal.service.AdminRolesService;
+import org.onap.portal.service.CentralizedAppService;
+import org.onap.portal.service.ExternalAccessRolesService;
+import org.onap.portal.service.app.FnAppService;
+import org.onap.portal.service.user.FnUserService;
+import org.onap.portal.utils.EPCommonSystemProperties;
+import org.onap.portal.utils.EcompPortalUtils;
+import org.onap.portal.utils.PortalConstants;
+import org.onap.portal.validation.SecureString;
+import org.onap.portalapp.controller.core.RoleController;
+import org.onap.portalapp.controller.core.RoleListController;
+import org.onap.portalsdk.core.domain.AuditLog;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.service.AuditService;
+import org.onap.portalsdk.core.service.AuditServiceImpl;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.onap.portalsdk.core.web.support.JsonMessage;
+import org.slf4j.MDC;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PathVariable;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.servlet.ModelAndView;
+
+@RestController
+@Configuration
+public class RoleManageController {
+
+    private static final ValidatorFactory VALIDATOR_FACTORY = Validation.buildDefaultValidatorFactory();
+    private static final String PIPE = "|";
+    private static final String ROLE_INVALID_CHARS = "%=():,\"\"";
+
+    private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class);
+
+    private RoleListController roleListController = new RoleListController();
+    private RoleController roleController = new RoleController();
+    private final AuditService auditService = new AuditServiceImpl();
+
+    private final CentralizedAppService centralizedAppService;
+    private final FnUserService fnUserService;
+    private final FnAppService fnAppService;
+    private final AdminRolesService adminRolesService;
+    private final ExternalAccessRolesService externalAccessRolesService;
+
+    @Autowired
+    public RoleManageController(CentralizedAppService centralizedAppService, FnUserService fnUserService,
+        FnAppService fnAppService,
+        AdminRolesService adminRolesService,
+        ExternalAccessRolesService externalAccessRolesService) {
+        this.centralizedAppService = centralizedAppService;
+        this.fnUserService = fnUserService;
+        this.fnAppService = fnAppService;
+        this.adminRolesService = adminRolesService;
+        this.externalAccessRolesService = externalAccessRolesService;
+    }
+
+    @RequestMapping(value = {"/portalApi/get_roles/{appId}"}, method = RequestMethod.GET)
+    public void getRoles(Principal principal, HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("appId") Long appId) {
+        try {
+            FnUser user = fnUserService.loadUserByUsername(principal.getName());
+            FnApp requestedApp = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, requestedApp)) {
+                fieldsValidation(requestedApp);
+                if (requestedApp.getAuthCentral()) {
+                    Map<String, Object> model = new HashMap<>();
+                    ObjectMapper mapper = new ObjectMapper();
+                    List<CentralV2Role> answer = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
+                    model.put("availableRoles", answer);
+                    JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+                    JSONObject j = new JSONObject(msg);
+                    response.getWriter().write(j.toString());
+                } else {
+                    throw new NonCentralizedAppException(requestedApp.getAppName());
+                }
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.getRoles, Unauthorized user");
+                SendErrorForUnauthorizedUser(response, user);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getRoles failed", e);
+        }
+    }
+
+    @RequestMapping(value = {"/portalApi/role_list/toggleRole/{appId}/{roleId}"}, method = RequestMethod.POST)
+    public Map<String, Object> toggleRole(Principal principal, HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
+        FnApp requestedApp;
+        String restcallStatus;
+        HashMap<String, Object> responseMap = new HashMap<>();
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        try {
+            requestedApp = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, requestedApp)) {
+                fieldsValidation(requestedApp);
+                ObjectMapper mapper = new ObjectMapper();
+                mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+                CentralV2Role domainRole = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
+                boolean active = domainRole.isActive();
+                domainRole.setActive(!active);
+                String result = mapper.writeValueAsString(domainRole);
+                Role newRole = externalAccessRolesService.convertCentralRoleToRole(result);
+                ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
+                    .saveRoleForApplication(newRole, requestedApp.getUebKey());
+                boolean getAddResponse = externalRequestFieldsValidator.isResult();
+                if (getAddResponse) {
+                    restcallStatus = "Success";
+                    logger.info(EELFLoggerDelegate.auditLogger, "Toggle active status for role " + domainRole.getId());
+                } else {
+                    restcallStatus = "Toggle Role Failed";
+                    logger.info(EELFLoggerDelegate.auditLogger, "Toggle Role Failed " + domainRole.getId());
+                }
+                responseMap.put("restcallStatus", restcallStatus);
+                responseMap.put("availableRoles", externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.toggleRole, Unauthorized user");
+                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                responseMap.put("restcallStatus", " Unauthorized user");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "toggleRole failed", e);
+            throw e;
+        }
+        return responseMap;
+    }
+
+    @RequestMapping(value = {"/portalApi/role_list/removeRole/{appId}/{roleId}"}, method = RequestMethod.POST)
+    public Map<String, Object> removeRole(Principal principal, HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("appId") Long appId, @PathVariable("roleId") Long roleId) throws Exception {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        FnApp requestedApp;
+        String restCallStatus;
+        HashMap<String, Object> responseMap = new HashMap<>();
+        ExternalRequestFieldsValidator externalRequestFieldsValidator;
+        try {
+            requestedApp = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, requestedApp)) {
+                fieldsValidation(requestedApp);
+                if (requestedApp.getAuthCentral()) {
+                    externalRequestFieldsValidator = externalAccessRolesService.deleteDependencyRoleRecord(roleId,
+                        requestedApp.getUebKey(), user.getOrgUserId());
+                    boolean deleteResponse = externalRequestFieldsValidator.isResult();
+                    if (deleteResponse) {
+                        restCallStatus = "Success";
+                        FnUser requestedUser = (FnUser) externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
+                        FnApp app = (FnApp) externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
+                        logger.info(EELFLoggerDelegate.applicationLogger, "deleteRole: succeeded for app {}, role {}",
+                            app.getId(), roleId);
+                        String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE;
+                        AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
+                        auditLog.setComments(EcompPortalUtils.truncateString(
+                            "Deleted role for app:" + app.getId() + " and role:'" + roleId + "'",
+                            PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+                        auditService.logActivity(auditLog, null);
+                        MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
+                            EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                        MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
+                            EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                        EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                            MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                            MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                        logger.info(EELFLoggerDelegate.auditLogger,
+                            EPLogUtil.formatAuditLogMessage("RoleManageController.removeRole",
+                                EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_ROLE,
+                                String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(),
+                                roleId.toString()));
+                        MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                        MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                        MDC.remove(SystemProperties.MDC_TIMER);
+                    } else {
+                        restCallStatus = "Remove Role failed";
+                        responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
+                        logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed");
+                    }
+                    responseMap.put("restCallStatus", restCallStatus);
+                    responseMap.put("availableRoles",
+                        externalAccessRolesService.getRolesForApp(requestedApp.getUebKey()));
+                } else {
+                    throw new NonCentralizedAppException(requestedApp.getAppName());
+                }
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.removeRole, Unauthorized user");
+                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                responseMap.put("restCallStatus", " Unauthorized user");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "removeRole failed", e);
+            throw e;
+        }
+        return responseMap;
+    }
+
+    @RequestMapping(value = {"/portalApi/role/saveRole/{appId}"}, method = RequestMethod.POST)
+    public Map<String, Object> saveRole(Principal principal, HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("appId") Long appId) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        String responseString = null;
+        HashMap<String, Object> responseMap = new HashMap<>();
+        try {
+            FnApp requestedApp = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, requestedApp)) {
+                fieldsValidation(requestedApp);
+                if (requestedApp.getAuthCentral().equals(true)) {
+                    ObjectMapper mapper = new ObjectMapper();
+                    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+                    JsonNode root = mapper.readTree(request.getReader());
+                    CentralV2Role role = mapper.readValue(root.get("role").toString(), CentralV2Role.class);
+                    List<CentralV2Role> childRoles = mapper.readValue(root.get("childRoles").toString(),
+                        TypeFactory.defaultInstance().constructCollectionType(List.class, CentralV2Role.class));
+                    List<EpAppFunction> roleFunctions = mapper.readValue(root.get("roleFunctions").toString(),
+                        TypeFactory.defaultInstance().constructCollectionType(List.class,
+                            EpAppFunction.class));
+                    if (role.getId() != null && StringUtils.containsAny(role.getName(), ROLE_INVALID_CHARS)) {
+                        throw new InvalidRoleException("Invalid role name found for '" + role.getName()
+                            + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
+                    }
+                    CentralV2Role domainRole;
+                    if (role.getId() != null) {
+                        domainRole = externalAccessRolesService.getRoleInfo(role.getId(), requestedApp.getUebKey());
+                        domainRole.setName(role.getName());
+                        domainRole.setPriority(role.getPriority());
+                    } else {
+                        List<CentralV2Role> roles = externalAccessRolesService.getRolesForApp(requestedApp.getUebKey());
+                        for (CentralV2Role existRole : roles) {
+                            if (existRole.getName().equalsIgnoreCase(role.getName())) {
+                                throw new DuplicateRecordException("Role already exists: " + existRole.getName());
+                            }
+                        }
+                        domainRole = CentralV2Role.builder().build();
+                        domainRole.setName(role.getName());
+                        domainRole.setPriority(role.getPriority());
+                        domainRole.setActive(role.isActive());
+                        if (role.getChildRoles() != null && role.getChildRoles().size() > 0) {
+                            for (Object childRole : childRoles) {
+                                domainRole.addChildRole((CentralV2Role) childRole);
+                            }
+                        }
+                    }
+                    if (role.getRoleFunctions() != null && role.getRoleFunctions().size() > 0) {
+                        domainRole.setRoleFunctions(new TreeSet<>());
+                        for (EpAppFunction roleFunction : roleFunctions) {
+                            if (roleFunction.getType() == null && roleFunction.getAction() == null) {
+                                throw new InvalidRoleException("Invalid role function type:" + roleFunction.getType()
+                                    + " and action: " + roleFunction.getAction() + " found while saving!");
+                            }
+                            if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(roleFunction.getFunctionCd())) {
+                                roleFunction.setFunctionCd(roleFunction.getType() + PIPE
+                                    + EcompPortalUtils.encodeFunctionCode(roleFunction.getFunctionCd()) + PIPE
+                                    + roleFunction.getAction());
+                            } else {
+                                roleFunction
+                                    .setFunctionCd(roleFunction.getType() + PIPE + roleFunction.getFunctionCd() + PIPE
+                                        + roleFunction.getAction());
+                            }
+                            domainRole.addRoleFunction(roleFunction);
+                        }
+                    } else {
+                        domainRole.setRoleFunctions(new TreeSet<>());
+                    }
+                    String result = mapper.writeValueAsString(domainRole);
+                    Role newRole = externalAccessRolesService.convertCentralRoleToRole(result);
+                    ExternalRequestFieldsValidator externalRequestFieldsValidator = externalAccessRolesService
+                        .saveRoleForApplication(newRole, requestedApp.getUebKey());
+                    boolean getAddResponse = externalRequestFieldsValidator.isResult();
+                    if (getAddResponse) {
+                        String activityCode = (role.getId() == null) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_ROLE
+                            : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
+                        logger.info(EELFLoggerDelegate.applicationLogger, "saveRole: succeeded for app {}, role {}",
+                            requestedApp.getId(), role.getName());
+                        AuditLog auditLog = new AuditLog();
+                        auditLog.setUserId(user.getId());
+                        auditLog.setActivityCode(activityCode);
+                        auditLog.setComments(EcompPortalUtils.truncateString(
+                            "saveRole role for app:" + requestedApp.getId() + " and role:'" + role.getName() + "'",
+                            PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+                        auditLog.setAffectedRecordId(user.getOrgUserId());
+                        auditService.logActivity(auditLog, null);
+                        MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
+                            EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                        MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
+                            EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                        EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                            MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                            MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                        logger.info(EELFLoggerDelegate.auditLogger,
+                            EPLogUtil.formatAuditLogMessage("RoleManageController.saveRole", activityCode,
+                                String.valueOf(user.getId()), user.getOrgUserId(), role.getName()));
+                        MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                        MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                        MDC.remove(SystemProperties.MDC_TIMER);
+                        responseMap.put("status", "Success");
+                        responseMap.put("role", domainRole);
+                    } else {
+                        if (externalRequestFieldsValidator.getDetailMessage().contains("406")) {
+                            externalRequestFieldsValidator.setDetailMessage("Failed to save role for '" + role.getName()
+                                + "'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed");
+                        }
+                        responseMap.put("status", "SaveRole Failed");
+                        responseMap.put("role", responseString);
+                        responseMap.put("error", externalRequestFieldsValidator.getDetailMessage());
+                        logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed");
+                    }
+                }
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRole, Unauthorized user");
+                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                responseMap.put("error", " Unauthorized user");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "saveRole failed", e);
+            responseMap.put("error", e.getMessage());
+        }
+        return responseMap;
+    }
+
+    @RequestMapping(value = {"/portalApi/role/removeRoleFunction"}, method = RequestMethod.POST)
+    public ModelAndView removeRoleRoleFunction(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return getRoleController().removeRoleFunction(request, response);
+    }
+
+    @RequestMapping(value = {"/portalApi/role/addRoleFunction"}, method = RequestMethod.POST)
+    public ModelAndView addRoleRoRoleFunction(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return getRoleController().addRoleFunction(request, response);
+    }
+
+    @RequestMapping(value = {"/portalApi/role/removeChildRole"}, method = RequestMethod.POST)
+    public ModelAndView removeChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+        return getRoleController().removeChildRole(request, response);
+    }
+
+    @RequestMapping(value = {"/portalApi/role/addChildRole"}, method = RequestMethod.POST)
+    public ModelAndView addChildRole(HttpServletRequest request, HttpServletResponse response) throws Exception {
+        return getRoleController().addChildRole(request, response);
+    }
+
+    @RequestMapping(value = {"/portalApi/get_role/{appId}/{roleId}"}, method = RequestMethod.GET)
+    public void getRole(Principal principal, HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("appId") Long appId,
+        @PathVariable("roleId") Long roleId) throws Exception {
+        try {
+            FnUser user = fnUserService.loadUserByUsername(principal.getName());
+            ObjectMapper mapper = new ObjectMapper();
+            FnApp requestedApp = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, requestedApp)) {
+                fieldsValidation(requestedApp);
+                if (requestedApp.getAuthCentral()) {
+                    CentralV2Role answer = externalAccessRolesService.getRoleInfo(roleId, requestedApp.getUebKey());
+                    logger.info(EELFLoggerDelegate.applicationLogger, "role_id" + roleId);
+                    Map<String, Object> model = new HashMap<>();
+                    model.put("availableRoleFunctions", mapper
+                        .writeValueAsString(externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey())));
+                    model.put("availableRoles",
+                        mapper.writeValueAsString(getAvailableChildRoles(requestedApp.getUebKey(), roleId)));
+                    model.put("role", mapper.writeValueAsString(answer));
+                    JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+                    JSONObject j = new JSONObject(msg);
+                    response.getWriter().write(j.toString());
+                } else {
+                    throw new NonCentralizedAppException(requestedApp.getAppName());
+                }
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    "RoleManageController.getRoleFunctionList, Unauthorized user");
+                SendErrorForUnauthorizedUser(response, user);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getRole failed", e);
+            throw e;
+        }
+    }
+
+    @RequestMapping(value = {"/portalApi/get_role_functions/{appId}"}, method = RequestMethod.GET)
+    public void getRoleFunctionList(Principal principal, HttpServletRequest request, HttpServletResponse response,
+        @PathVariable("appId") Long appId) throws Exception {
+        try {
+            FnUser user = fnUserService.loadUserByUsername(principal.getName());
+            FnApp requestedApp = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, requestedApp)) {
+                fieldsValidation(requestedApp);
+                if (requestedApp.getAuthCentral()) {
+                    List<EpAppFunction> answer = null;
+                    Map<String, Object> model = new HashMap<>();
+                    ObjectMapper mapper = new ObjectMapper();
+                    answer = externalAccessRolesService.getRoleFuncList(requestedApp.getUebKey());
+                    model.put("availableRoleFunctions", answer);
+                    JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model));
+                    JSONObject j = new JSONObject(msg);
+                    response.getWriter().write(j.toString());
+                } else {
+                    throw new NonCentralizedAppException(requestedApp.getAppName());
+                }
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    "RoleManageController.getRoleFunctionList, Unauthorized user");
+                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                response.getWriter().write("Unauthorized User");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunctionList failed", e);
+            throw e;
+        }
+    }
+
+    @RequestMapping(value = {"/portalApi/role_function_list/saveRoleFunction/{appId}"}, method = RequestMethod.POST)
+    public PortalRestResponse<String> saveRoleFunction(Principal principal, HttpServletRequest request,
+        HttpServletResponse response, @Valid @RequestBody EpAppFunction roleFunc, @PathVariable("appId") Long appId) {
+        if (roleFunc != null) {
+            Validator validator = VALIDATOR_FACTORY.getValidator();
+            Set<ConstraintViolation<EpAppFunction>> constraintViolations = validator.validate(roleFunc);
+
+            if (!constraintViolations.isEmpty()) {
+                logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
+            }
+        }
+
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        boolean saveOrUpdateResponse;
+        try {
+            FnApp requestedApp = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, requestedApp)) {
+                fieldsValidation(requestedApp);
+                if (requestedApp.getAuthCentral() && roleFunc != null) {
+                    String code = roleFunc.getType() + PIPE + roleFunc.getFunctionCd() + PIPE + roleFunc.getAction();
+                    EpAppFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
+                        requestedApp.getUebKey());
+                    if (domainRoleFunction != null
+                        && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) {
+                        addIfTypeActionDoesNotExits(domainRoleFunction);
+                    }
+                    boolean isSave = true;
+                    if (domainRoleFunction != null && domainRoleFunction.getFunctionCd()
+                        .equals(roleFunc.getFunctionCd())
+                        && domainRoleFunction.getType().equals(roleFunc.getType())
+                        && domainRoleFunction.getAction().equals(roleFunc.getAction())) {
+                        domainRoleFunction.setFunctionName(roleFunc.getFunctionName());
+                        saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction,
+                            requestedApp);
+                        isSave = false;
+                    } else {
+                        roleFunc.setAppId(requestedApp);
+                        saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc,
+                            requestedApp);
+                    }
+                    if (saveOrUpdateResponse) {
+                        FnUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0);
+                        FnApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0);
+                        String activityCode = (isSave) ? EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_ADD_FUNCTION
+                            : EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_FUNCTION;
+                        logExterlaAuthRoleFunctionActivity(code, requestedUser, app, activityCode);
+                    }
+                } else {
+                    throw new NonCentralizedAppException(requestedApp.getAppName() + " is not Centralized Application");
+                }
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger, "RoleManageController.saveRoleFunction, Unauthorized user");
+                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "saveRoleFunction: Failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success");
+    }
+
+    private void logExterlaAuthRoleFunctionActivity(String code, FnUser requestedUser, FnApp app, String activityCode) {
+        logger.info(EELFLoggerDelegate.applicationLogger, "saveRoleFunction: succeeded for app {}, function {}",
+            app.getId(), code);
+        AuditLog auditLog = getAuditInfo(requestedUser, activityCode);
+        auditLog.setComments(EcompPortalUtils.truncateString(
+            "saveRoleFunction role for app:" + app.getId() + " and function:'" + code + "'",
+            PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+        auditService.logActivity(auditLog, null);
+        MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+        MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP, EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+        EcompPortalUtils.calculateDateTimeDifferenceForLog(MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+            MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+        logger.info(EELFLoggerDelegate.auditLogger,
+            EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode,
+                String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), code));
+        MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+        MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+        MDC.remove(SystemProperties.MDC_TIMER);
+    }
+
+    private void addIfTypeActionDoesNotExits(EpAppFunction domainRoleFunction) {
+        if (domainRoleFunction.getFunctionCd().contains(PIPE)) {
+            String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getFunctionCd());
+            String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getFunctionCd());
+            String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getFunctionCd());
+            domainRoleFunction.setType(newfunctionTypeFormat);
+            domainRoleFunction.setAction(newfunctionActionFormat);
+            domainRoleFunction.setFunctionCd(newfunctionCodeFormat);
+        } else {
+            String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getFunctionCd());
+            String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getFunctionCd());
+            domainRoleFunction.setType(type);
+            domainRoleFunction.setAction(action);
+        }
+    }
+
+    @RequestMapping(value = {"/portalApi/role_function_list/removeRoleFunction/{appId}"}, method = RequestMethod.POST)
+    public PortalRestResponse<String> removeRoleFunction(Principal principal,
+        HttpServletRequest request, HttpServletResponse response,
+        @RequestBody String roleFunc, @PathVariable("appId") Long appId) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        if (roleFunc != null) {
+            SecureString secureString = new SecureString(roleFunc);
+
+            Validator validator = VALIDATOR_FACTORY.getValidator();
+            Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
+
+            if (!constraintViolations.isEmpty()) {
+                logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Data is not valid", "ERROR");
+            }
+        }
+
+        try {
+            FnApp requestedApp = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, requestedApp)) {
+                fieldsValidation(requestedApp);
+                if (requestedApp.getAuthCentral()) {
+                    ObjectMapper mapper = new ObjectMapper();
+                    boolean getDelFuncResponse;
+                    EpAppFunction availableRoleFunction = mapper.readValue(roleFunc, EpAppFunction.class);
+                    String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getFunctionCd() + PIPE
+                        + availableRoleFunction.getAction();
+                    EpAppFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code,
+                        requestedApp.getUebKey());
+                    getDelFuncResponse = externalAccessRolesService
+                        .deleteCentralRoleFunction(domainRoleFunction.getFunctionCd(), requestedApp);
+                    if (getDelFuncResponse) {
+                        logger.info(EELFLoggerDelegate.applicationLogger,
+                            "deleteRoleFunction: succeeded for app {}, role {}", requestedApp.getId(),
+                            domainRoleFunction.getFunctionCd());
+                        String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION;
+                        AuditLog auditLog = getAuditInfo(user, activityCode);
+                        auditLog.setComments(
+                            EcompPortalUtils.truncateString(
+                                "Deleted function for app:" + requestedApp.getId() + " and function code:'"
+                                    + domainRoleFunction.getFunctionCd() + "'",
+                                PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+                        auditService.logActivity(auditLog, null);
+                        MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
+                            EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                        MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
+                            EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                        EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                            MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                            MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                        logger.info(EELFLoggerDelegate.auditLogger,
+                            EPLogUtil.formatAuditLogMessage("RoleManageController.removeRoleFunction",
+                                EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_DELETE_FUNCTION,
+                                String.valueOf(user.getId()), user.getOrgUserId(),
+                                domainRoleFunction.getFunctionCd()));
+                        MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                        MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                        MDC.remove(SystemProperties.MDC_TIMER);
+                        logger.info(EELFLoggerDelegate.auditLogger,
+                            "Remove role function " + domainRoleFunction.getFunctionName());
+                    }
+                } else {
+                    throw new NonCentralizedAppException(requestedApp.getAppName() + " is not Centralized Application");
+                }
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    "RoleManageController.removeRoleFunction, Unauthorized user");
+                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failure");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Deleted Successfully!", "Success");
+    }
+
+    @RequestMapping(value = {"/portalApi/centralizedApps"}, method = RequestMethod.GET)
+    public List<CentralizedApp> getCentralizedAppRoles(Principal principal, HttpServletRequest request,
+        HttpServletResponse response,
+        String userId) {
+        if (userId != null) {
+            SecureString secureString = new SecureString(userId);
+
+            Validator validator = VALIDATOR_FACTORY.getValidator();
+            Set<ConstraintViolation<SecureString>> constraintViolations = validator.validate(secureString);
+
+            if (!constraintViolations.isEmpty()) {
+                logger.error(EELFLoggerDelegate.errorLogger, "removeRoleFunction: Failed");
+                return null;
+            }
+        }
+
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        List<CentralizedApp> applicationsList = null;
+        if (adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()) || adminRolesService
+            .isSuperAdmin(user.getLoginId())
+            || adminRolesService.isRoleAdmin(user.getId())) {
+            applicationsList = centralizedAppService.getCentralizedAppsOfUser(userId);
+        } else {
+            logger.info(EELFLoggerDelegate.auditLogger,
+                "RoleManageController.getCentralizedAppRoles, Unauthorized user");
+            EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+        }
+        return applicationsList;
+    }
+
+    public List<CentralizedApp> getCentralizedAppsOfUser(String userId) {
+        List<CentralizedApp> centralizedAppsList = new ArrayList<>();
+        try {
+            centralizedAppsList = centralizedAppService.getCentralizedAppsOfUser(userId);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
+        }
+        return centralizedAppsList;
+    }
+
+    public RoleListController getRoleListController() {
+        return roleListController;
+    }
+
+    public void setRoleListController(RoleListController roleListController) {
+        this.roleListController = roleListController;
+    }
+
+    public RoleController getRoleController() {
+        return roleController;
+    }
+
+    public void setRoleController(RoleController roleController) {
+        this.roleController = roleController;
+    }
+
+    @RequestMapping(value = {"/portalApi/syncRoles"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> syncRoles(Principal principal, HttpServletRequest request,
+        HttpServletResponse response,
+        @RequestBody Long appId) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        try {
+            FnApp app = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, app)) {
+                fieldsValidation(app);
+                externalAccessRolesService.syncApplicationRolesWithEcompDB(app);
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
+                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "failed syncRoles", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync roles completed successfully!", "Success");
+    }
+
+    @RequestMapping(value = {"/portalApi/syncFunctions"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> syncFunctions(Principal principal, HttpServletRequest request,
+        HttpServletResponse response,
+        @RequestBody Long appId) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        try {
+            FnApp app = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, app)) {
+                fieldsValidation(app);
+                externalAccessRolesService.syncRoleFunctionFromExternalAccessSystem(app);
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    "RoleManageController.syncFunctions, Unauthorized user:{}",
+                    user != null ? user.getOrgUserId() : "");
+                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "failed syncFunctions", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Sync Functions completed successfully!", "Success");
+    }
+
+    public List<CentralV2Role> getAvailableChildRoles(String uebKey, Long roleId) throws Exception {
+        List<CentralV2Role> availableChildRoles = externalAccessRolesService.getRolesForApp(uebKey);
+        if (roleId == null || roleId == 0) {
+            return availableChildRoles;
+        }
+        CentralV2Role currentRole = externalAccessRolesService.getRoleInfo(roleId, uebKey);
+        Set<CentralV2Role> allParentRoles = new TreeSet<>();
+        getAllParentRolesAsList(currentRole, allParentRoles);
+        availableChildRoles
+            .removeIf(role -> !role.isActive() || allParentRoles.contains(role) || role.getId().equals(roleId));
+        return availableChildRoles;
+    }
+
+    private void getAllParentRolesAsList(CentralV2Role role, Set<CentralV2Role> allParentRoles) {
+        Set<CentralV2Role> parentRoles = role.getParentRoles();
+        allParentRoles.addAll(parentRoles);
+        for (CentralV2Role parentRole : parentRoles) {
+            getAllParentRolesAsList(parentRole, allParentRoles);
+        }
+    }
+
+    public AuditLog getAuditInfo(FnUser user, String activityCode) {
+        AuditLog auditLog = new AuditLog();
+        auditLog.setUserId(user.getId());
+        auditLog.setActivityCode(activityCode);
+        auditLog.setAffectedRecordId(user.getOrgUserId());
+
+        return auditLog;
+    }
+
+    private void fieldsValidation(FnApp app) throws Exception {
+        List<FnApp> appInfo = externalAccessRolesService.getApp(app.getUebKey());
+        if (appInfo.isEmpty()) {
+            throw new InvalidApplicationException("Invalid credentials");
+        }
+        if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()
+            && appInfo.get(0).getAuthCentral()) {
+            ResponseEntity<String> response = externalAccessRolesService.getNameSpaceIfExists(appInfo.get(0));
+            if (response.getStatusCode().value() == HttpServletResponse.SC_NOT_FOUND) {
+                throw new InvalidApplicationException("Invalid NameSpace");
+            }
+        }
+    }
+
+    private boolean isAuthorizedUser(FnUser user, FnApp requestedApp) {
+        return user != null && (adminRolesService.isAccountAdminOfApplication(user.getId(), requestedApp)
+            || (adminRolesService.isSuperAdmin(user.getLoginId()) && requestedApp.getId()
+            .equals(PortalConstants.PORTAL_APP_ID)));
+    }
+
+    private void SendErrorForUnauthorizedUser(HttpServletResponse response, FnUser user) throws IOException {
+        EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+        response.getWriter().write("Unauthorized User");
+    }
+
+    @RequestMapping(value = {
+        "/portalApi/uploadRoleFunction/{appId}"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> bulkUploadRoleFunc(Principal principal, HttpServletRequest request,
+        HttpServletResponse response,
+        @RequestBody UploadRoleFunctionExtSystem data, @PathVariable("appId") Long appId) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        try {
+            FnApp app = fnAppService.getById(appId);
+            if (isAuthorizedUser(user, app)) {
+                fieldsValidation(app);
+                externalAccessRolesService.bulkUploadRoleFunc(data, app);
+                String activityCode = EcompAuditLog.CD_ACTIVITY_EXTERNAL_AUTH_UPDATE_ROLE_AND_FUNCTION;
+                String code = data.getName() + "," + data.getType() + PIPE + data.getInstance() + PIPE
+                    + data.getAction();
+                logExterlaAuthRoleFunctionActivity(code, user, app, activityCode);
+            } else {
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    "RoleManageController.syncRoles, Unauthorized user:{}", user != null ? user.getOrgUserId() : "");
+                EcompPortalUtils.setBadPermissions(user, response, "createAdmin");
+                return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, "Unauthorized User", "Failure");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "Failed bulkUploadRoleFunc!", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), "Failed");
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Uploaded Role Function successfully!", "Success");
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemController.java b/portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemController.java
new file mode 100644 (file)
index 0000000..3a54523
--- /dev/null
@@ -0,0 +1,210 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+
+package org.onap.portal.controller;
+
+import io.swagger.annotations.ApiOperation;
+import java.util.ArrayList;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.onap.portal.domain.dto.PortalRestResponse;
+import org.onap.portal.domain.dto.PortalRestStatusEnum;
+import org.onap.portal.domain.dto.model.ExternalSystemRoleApproval;
+import org.onap.portal.domain.dto.model.ExternalSystemUser;
+import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
+import org.onap.portal.service.AdminRolesService;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestMethod;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@RequestMapping("/auxapi")
+@Configuration
+@EnableAspectJAutoProxy
+public class RolesApprovalSystemController {
+
+    private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RolesApprovalSystemController.class);
+
+    private final AdminRolesService userRolesService;
+
+    @Autowired
+    public RolesApprovalSystemController(AdminRolesService userRolesService) {
+        this.userRolesService = userRolesService;
+    }
+
+    @ApiOperation(value = "Creates an application user with the specified roles.", response = PortalRestResponse.class)
+    @RequestMapping(value = {"/userProfile"}, method = RequestMethod.POST, produces = "application/json")
+    public PortalRestResponse<String> postUserProfile(HttpServletRequest request,
+        @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
+        ExternalRequestFieldsValidator reqResult = null;
+        try {
+            logger.info(EELFLoggerDelegate.debugLogger, "postUserProfile: request received for app {}, user {}",
+                extSysUser.getApplicationName(), extSysUser.getLoginId());
+
+            validateExtSystemUser(extSysUser, true);
+            reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "POST");
+            if (!reqResult.isResult()) {
+                throw new Exception(reqResult.getDetailMessage());
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "postUserProfile: failed for app {}, user {}",
+                extSysUser.getApplicationName(), extSysUser.getLoginId(), e);
+            if (reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404") && !e.getMessage()
+                .contains("405"))) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "save user profile failed");
+            } else if (e.getMessage().contains("404")) {
+                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "save user profile failed");
+            } else if (e.getMessage().contains("500")) {
+                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "save user profile failed");
+            } else if (e.getMessage().contains("405")) {
+                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(),
+                    "save user profile failed");
+            } else {
+                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(),
+                    "save user profile failed");
+            }
+        }
+        return new PortalRestResponse<String>(PortalRestStatusEnum.OK, reqResult.getDetailMessage(), "Success");
+    }
+
+    @ApiOperation(value = "Updates an application user to have only the specified roles.", response = PortalRestResponse.class)
+    @RequestMapping(value = {"/userProfile"}, method = RequestMethod.PUT, produces = "application/json")
+    public PortalRestResponse<String> putUserProfile(HttpServletRequest request,
+        @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
+        ExternalRequestFieldsValidator reqResult = null;
+        try {
+            logger.info(EELFLoggerDelegate.debugLogger, "putUserProfile: request received for app {}, user {}",
+                extSysUser.getApplicationName(), extSysUser.getLoginId());
+            validateExtSystemUser(extSysUser, true);
+            reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "PUT");
+            if (!reqResult.isResult()) {
+                throw new Exception(reqResult.getDetailMessage());
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "putUserProfile: failed for app {}, user {}",
+                extSysUser.getApplicationName(), extSysUser.getLoginId(), e);
+            if (reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404") && !e.getMessage()
+                .contains("405"))) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "save user profile failed");
+            } else if (e.getMessage().contains("404")) {
+                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "save user profile failed");
+            } else if (e.getMessage().contains("500")) {
+                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "save user profile failed");
+            } else if (e.getMessage().contains("405")) {
+                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, e.getMessage(),
+                    "save user profile failed");
+            } else {
+                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "save user profile failed");
+            }
+        }
+        return new PortalRestResponse<String>(PortalRestStatusEnum.OK, reqResult.getDetailMessage(), "Success");
+    }
+
+    @ApiOperation(value = "Processes a request to delete one or more application roles for one specified user who has roles.", response = PortalRestResponse.class)
+    @RequestMapping(value = {"/userProfile"}, method = RequestMethod.DELETE, produces = "application/json")
+    public PortalRestResponse<String> deleteUserProfile(HttpServletRequest request,
+        @RequestBody ExternalSystemUser extSysUser, HttpServletResponse response) {
+        ExternalRequestFieldsValidator reqResult = null;
+        try {
+            logger.info(EELFLoggerDelegate.debugLogger, "deleteUserProfile: request received for app {}, user {}",
+                extSysUser.getApplicationName(), extSysUser.getLoginId());
+            validateExtSystemUser(extSysUser, false);
+            // Ignore any roles that might be mistakenly present in the request
+            extSysUser.setRoles(new ArrayList<ExternalSystemRoleApproval>());
+            reqResult = userRolesService.setExternalRequestUserAppRole(extSysUser, "DELETE");
+            if (!reqResult.isResult()) {
+                throw new Exception(reqResult.getDetailMessage());
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteUserProfile: failed for app {}, user {}",
+                extSysUser.getApplicationName(), extSysUser.getLoginId(), e);
+            if (reqResult == null || (!reqResult.isResult() && !e.getMessage().contains("404"))) {
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "delete user profile failed");
+            } else if (e.getMessage().contains("404")) {
+                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "delete user profile failed");
+            } else {
+                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                return new PortalRestResponse<String>(PortalRestStatusEnum.ERROR,
+                    e.getMessage(), "delete user profile failed");
+            }
+        }
+        return new PortalRestResponse<String>(PortalRestStatusEnum.OK, "Deleted Successfully", "Success");
+    }
+
+    private void validateExtSystemUser(ExternalSystemUser extSysUser, boolean rolesRequired) throws Exception {
+        if (extSysUser.getLoginId() == null || extSysUser.getLoginId() == "") {
+            throw new Exception("Request has no login ID");
+        }
+        if (extSysUser.getApplicationName() == null || extSysUser.getApplicationName() == "") {
+            throw new Exception("Request has no application name");
+        }
+        if (extSysUser.getMyloginrequestId() == null) {
+            throw new Exception("Request has no request ID");
+        }
+        if (rolesRequired && (extSysUser.getRoles() == null || extSysUser.getRoles().size() == 0)) {
+            throw new Exception("Request has no roles");
+        }
+    }
+
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemVersionController.java b/portal-BE/src/main/java/org/onap/portal/controller/RolesApprovalSystemVersionController.java
new file mode 100644 (file)
index 0000000..7931188
--- /dev/null
@@ -0,0 +1,78 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ */
+package org.onap.portal.controller;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.onap.portal.annotation.ApiVersion;
+import org.onap.portal.domain.dto.PortalRestResponse;
+import org.onap.portal.domain.dto.model.ExternalSystemUser;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+
+@Configuration
+@EnableAspectJAutoProxy
+@ApiVersion
+public class RolesApprovalSystemVersionController {
+
+    private final RolesApprovalSystemController rolesApprovalSystemController;
+
+    @Autowired
+    public RolesApprovalSystemVersionController(
+        RolesApprovalSystemController rolesApprovalSystemController) {
+        this.rolesApprovalSystemController = rolesApprovalSystemController;
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/userProfile", min = 0, method = "POST")
+    public PortalRestResponse<String> postUserProfile(HttpServletRequest request,
+        HttpServletResponse response, ExternalSystemUser extSysUser) {
+        return rolesApprovalSystemController.postUserProfile(request, extSysUser, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/userProfile", min = 0, method = "PUT")
+    public PortalRestResponse<String> putUserProfile(HttpServletRequest request,
+        HttpServletResponse response, ExternalSystemUser extSysUser) {
+        return rolesApprovalSystemController.putUserProfile(request, extSysUser, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/userProfile", min = 0, method = "DELETE")
+    public PortalRestResponse<String> deleteUserProfile(HttpServletRequest request,
+        HttpServletResponse response, ExternalSystemUser extSysUser) {
+        return rolesApprovalSystemController.deleteUserProfile(request, extSysUser, response);
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/controller/RolesController.java b/portal-BE/src/main/java/org/onap/portal/controller/RolesController.java
new file mode 100644 (file)
index 0000000..c6fcd29
--- /dev/null
@@ -0,0 +1,241 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ */
+package org.onap.portal.controller;
+
+import io.swagger.annotations.ApiOperation;
+import java.util.List;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.onap.aaf.cadi.aaf.AAFPermission;
+import org.onap.portal.annotation.ApiVersion;
+import org.onap.portal.domain.db.ep.EpAppFunction;
+import org.onap.portal.domain.dto.PortalRestResponse;
+import org.onap.portal.domain.dto.PortalRestStatusEnum;
+import org.onap.portal.domain.dto.transport.CentralV2Role;
+import org.onap.portal.logging.aop.EPAuditLog;
+import org.onap.portal.service.ExternalAccessRolesService;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.util.AuthUtil;
+import org.onap.portalsdk.core.restful.domain.EcompRole;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.EnableAspectJAutoProxy;
+import org.springframework.web.bind.annotation.RestController;
+
+@RestController
+@EnableAspectJAutoProxy
+@EPAuditLog
+@ApiVersion
+public class RolesController {
+
+    private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RolesController.class);
+
+
+    final String LOGINID_PATTERN = "/v3/user/[a-zA-Z0-9]{1,25}$";
+    final String FUNCTION_CD_PATTERN = "/v3/function/[a-zA-Z0-9_-]{1,75}$";
+
+    final String DELETE_ROLEFUNCTION = "/v3/roleFunction/[a-zA-Z0-9_-]{1,75}$";
+
+    private static final String UEBKEY = "uebkey";
+
+    private final ExternalAccessRolesService externalAccessRolesService;
+    private final ExternalAccessRolesController externalAccessRolesController;
+
+    @Autowired
+    public RolesController(ExternalAccessRolesService externalAccessRolesService,
+        ExternalAccessRolesController externalAccessRolesController) {
+        this.externalAccessRolesService = externalAccessRolesService;
+        this.externalAccessRolesController = externalAccessRolesController;
+    }
+
+
+    @ApiOperation(value = "Gets roles for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer = "Json")
+    @ApiVersion(max = "v3", service = "/v3/roles", min = 0, method = "GET")
+    public List<CentralV2Role> getV2RolesForApp(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return externalAccessRolesController.getV2RolesForApp(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = LOGINID_PATTERN, min = 0, method = "GET")
+    public String getV2UserList(HttpServletRequest request, HttpServletResponse response, String loginId)
+        throws Exception {
+        return externalAccessRolesController.getV2UserList(request, response, loginId);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/role", min = 0, method = "POST")
+    public PortalRestResponse<String> saveRole(HttpServletRequest request, HttpServletResponse response, Role role)
+        throws Exception {
+        return externalAccessRolesController.saveRole(request, response, role);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/role/[0-9]{1,25}$", min = 0, method = "GET")
+    public CentralV2Role getV2RoleInfo(HttpServletRequest request, HttpServletResponse response, Long roleId)
+        throws Exception {
+        return externalAccessRolesController.getV2RoleInfo(request, response, roleId);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/users", min = 0, method = "GET")
+    public List<EcompUser> getUsersOfApplication(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return externalAccessRolesController.getUsersOfApplication(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/functions", min = 0, method = "GET")
+    public List<EpAppFunction> getRoleFunctionsList(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return externalAccessRolesController.getV2RoleFunctionsList(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = FUNCTION_CD_PATTERN, min = 0, method = "GET")
+    public EpAppFunction getRoleFunction(HttpServletRequest request, HttpServletResponse response, String code)
+        throws Exception {
+        return externalAccessRolesController.getV2RoleFunction(request, response, code);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/roleFunction", min = 0, method = "POST")
+    public PortalRestResponse<String> saveRoleFunction(HttpServletRequest request, HttpServletResponse response,
+        String roleFunc) throws Exception {
+        return externalAccessRolesController.saveRoleFunction(request, response, roleFunc);
+    }
+
+    @ApiVersion(max = "v3", service = DELETE_ROLEFUNCTION, min = 0, method = "DELETE")
+    public PortalRestResponse<String> deleteRoleFunction(HttpServletRequest request, HttpServletResponse response,
+        String code) throws Exception {
+        return externalAccessRolesController.deleteRoleFunction(request, response, code);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/deleteRole/[0-9]{1,25}$", min = 0, method = "DELETE")
+    public PortalRestResponse<String> deleteRole(HttpServletRequest request, HttpServletResponse response, Long roleId)
+        throws Exception {
+        return externalAccessRolesController.deleteRole(request, response, roleId);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/activeRoles", min = 0, method = "GET")
+    public List<CentralV2Role> getV2ActiveRoles(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return externalAccessRolesController.getV2ActiveRoles(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/upload/portal/functions", min = 0, method = "POST")
+    public PortalRestResponse<String> bulkUploadFunctions(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return externalAccessRolesController.bulkUploadFunctions(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/upload/portal/roles", min = 0, method = "POST")
+    public PortalRestResponse<String> bulkUploadRoles(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return externalAccessRolesController.bulkUploadRoles(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/upload/portal/roleFunctions", min = 0, method = "POST")
+    public PortalRestResponse<String> bulkUploadRoleFunctions(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return externalAccessRolesController.bulkUploadRoleFunctions(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/upload/portal/userRoles", min = 0, method = "POST")
+    public PortalRestResponse<String> bulkUploadUserRoles(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return externalAccessRolesController.bulkUploadUserRoles(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/upload/portal/userRole/[0-9]{1,25}$", min = 0, method = "POST")
+    public PortalRestResponse<String> bulkUploadUsersSingleRole(HttpServletRequest request,
+        HttpServletResponse response, Long roleId) throws Exception {
+        return externalAccessRolesController.bulkUploadUsersSingleRole(request, response, roleId);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/upload/partner/functions", min = 0, method = "POST")
+    public PortalRestResponse<String> bulkUploadPartnerFunctions(HttpServletRequest request,
+        HttpServletResponse response) throws Exception {
+        return externalAccessRolesController.bulkUploadPartnerFunctions(request, response);
+    }
+
+    //not using this
+    @ApiVersion(max = "v3", service = "/v3/upload/partner/roles", min = 0, method = "POST")
+    public PortalRestResponse<String> bulkUploadPartnerRoles(HttpServletRequest request, HttpServletResponse response,
+        List<Role> upload) throws Exception {
+        return externalAccessRolesController.bulkUploadPartnerRoles(request, response, upload);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/upload/partner/roleFunctions", min = 0, method = "POST")
+    public PortalRestResponse<String> bulkUploadPartnerRoleFunctions(HttpServletRequest request,
+        HttpServletResponse response) throws Exception {
+        return externalAccessRolesController.bulkUploadPartnerRoleFunctions(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/menuFunctions", min = 0, method = "GET")
+    public List<String> getMenuFunctions(HttpServletRequest request, HttpServletResponse response) throws Exception {
+        return externalAccessRolesController.getMenuFunctions(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/update/app/roleDescription", min = 0, method = "PUT")
+    public PortalRestResponse<String> updateAppRoleDescription(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        Integer updatedRoleDesc = 0;
+        try {
+            updatedRoleDesc = externalAccessRolesService.updateAppRoleDescription(request.getHeader(UEBKEY));
+        } catch (Exception e) {
+            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: failed!", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.ERROR,
+                "updateAppRoleDescription: " + e.getMessage(), "Failure");
+        }
+        return new PortalRestResponse<String>(PortalRestStatusEnum.OK,
+            "Successfully updated app role descriptions: '" + updatedRoleDesc + "'", "Success");
+    }
+
+    @ApiVersion(max = "v4", service = "/v4/user/[a-zA-Z0-9]{1,25}$", min = 0, method = "GET")
+    public String getEcompUser(HttpServletRequest request, HttpServletResponse response, String loginId)
+        throws Exception {
+        return externalAccessRolesController.getEcompUser(request, response, loginId);
+    }
+
+    @ApiVersion(max = "v4", service = "/v4/roles", min = 0, method = "GET")
+    public List<EcompRole> getEcompRolesOfApplication(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return externalAccessRolesController.getEcompRolesOfApplication(request, response);
+    }
+
+    @ApiVersion(max = "v3", service = "/v3/systemUser", min = 0, method = "GET")
+    public List<AAFPermission> getSystemUser(HttpServletRequest request, HttpServletResponse response)
+        throws Exception {
+        return AuthUtil.getAAFPermissions(request);
+    }
+}
index 9b29f5d..120b8bc 100644 (file)
@@ -50,11 +50,11 @@ import javax.servlet.http.HttpServletResponse;
 import org.apache.cxf.transport.http.HTTPException;
 import org.onap.portal.domain.db.fn.FnRole;
 import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.domain.dto.PortalRestResponse;
+import org.onap.portal.domain.dto.PortalRestStatusEnum;
 import org.onap.portal.domain.dto.ecomp.EPUserAppCatalogRoles;
 import org.onap.portal.domain.dto.ecomp.EcompAuditLog;
 import org.onap.portal.domain.dto.ecomp.ExternalSystemAccess;
-import org.onap.portal.domain.dto.ecomp.PortalRestResponse;
-import org.onap.portal.domain.dto.ecomp.PortalRestStatusEnum;
 import org.onap.portal.domain.dto.transport.AppNameIdIsAdmin;
 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
 import org.onap.portal.domain.dto.transport.AppsListWithAdminRole;
@@ -66,6 +66,7 @@ import org.onap.portal.logging.aop.EPEELFLoggerAdvice;
 import org.onap.portal.logging.logic.EPLogUtil;
 import org.onap.portal.service.AdminRolesService;
 import org.onap.portal.service.ApplicationsRestClientService;
+import org.onap.portal.service.SearchService;
 import org.onap.portal.service.userRole.FnUserRoleService;
 import org.onap.portal.service.user.FnUserService;
 import org.onap.portal.utils.EPCommonSystemProperties;
@@ -79,6 +80,7 @@ import org.onap.portalsdk.core.util.SystemProperties;
 import org.slf4j.MDC;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Configuration;
+import org.springframework.security.access.prepost.PreAuthorize;
 import org.springframework.web.bind.annotation.PathVariable;
 import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
@@ -90,481 +92,488 @@ import org.springframework.web.bind.annotation.RestController;
 @Configuration
 public class UserRolesController {
 
-  private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
-
-  private final FnUserService fnUserService;
-  private final FnUserRoleService fnUserRoleService;
-  private final AdminRolesService adminRolesService;
-  private final ApplicationsRestClientService applicationsRestClientService;
-  private final AuditServiceImpl auditService = new AuditServiceImpl();
-
-  private static final String FAILURE = "failure";
-
-  @Autowired
-  public UserRolesController(final FnUserService fnUserService,
-      FnUserRoleService fnUserRoleService,
-      final AdminRolesService adminRolesService,
-      ApplicationsRestClientService applicationsRestClientService) {
-    this.fnUserService = fnUserService;
-    this.fnUserRoleService = fnUserRoleService;
-    this.adminRolesService = adminRolesService;
-    this.applicationsRestClientService = applicationsRestClientService;
-  }
-
-
-  /*
-         @RequestMapping(value = {"/portalApi/queryUsers"}, method = RequestMethod.GET, produces = "application/json")
-         @PreAuthorize("hasRole('System_Administrator') and hasRole('Account_Administrator')")
-         public String getPhoneBookSearchResult(Principal principal, @RequestParam("search") String searchString,
-                 HttpServletResponse response) {
-                FnUser user = fnUserService.loadUserByUsername(principal.getName());
-
-                String searchResult = null;
-                if (!adminRolesService.isSuperAdmin(user) && !adminRolesService.isAccountAdmin(user)
-                        && !adminRolesService.isRoleAdmin(user)) {
-                       EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
-                } else {
-                       searchString = searchString.trim();
-                       if (searchString.length() > 2) {
-                              searchResult = searchService.searchUsersInPhoneBook(searchString);
-                       } else {
-                              logger.info(EELFLoggerDelegate.errorLogger,
-                                      "getPhoneBookSearchResult - too short search string: " + searchString);
-                       }
-                }
-                EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
-
-                return searchResult;
-         }
-
-
-         @RequestMapping(value = {"/portalApi/adminAppsRoles"}, method = {
-                 RequestMethod.GET}, produces = "application/json")
-         public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(Principal principal,
-                 @RequestParam("user") String orgUserId, HttpServletResponse response) {
-
-                FnUser user = fnUserService.loadUserByUsername(principal.getName());
-
-                AppsListWithAdminRole result = null;
-                if (!adminRolesService.isSuperAdmin(user)) {
-                       EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
-                } else {
-                       if (EcompPortalUtils.legitimateUserId(orgUserId)) {
-                              result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
-                       } else {
-                              logger.info(EELFLoggerDelegate.errorLogger,
-                                      "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
-                              response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
-                       }
-                }
+    private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(UserRolesController.class);
+
+    private final SearchService searchService;
+    private final FnUserService fnUserService;
+    private final FnUserRoleService fnUserRoleService;
+    private final AdminRolesService adminRolesService;
+    private final ApplicationsRestClientService applicationsRestClientService;
+    private final AuditServiceImpl auditService = new AuditServiceImpl();
+
+    private static final String FAILURE = "failure";
+
+    @Autowired
+    public UserRolesController(SearchService searchService, final FnUserService fnUserService,
+        FnUserRoleService fnUserRoleService,
+        final AdminRolesService adminRolesService,
+        ApplicationsRestClientService applicationsRestClientService) {
+        this.searchService = searchService;
+        this.fnUserService = fnUserService;
+        this.fnUserRoleService = fnUserRoleService;
+        this.adminRolesService = adminRolesService;
+        this.applicationsRestClientService = applicationsRestClientService;
+    }
 
-                StringBuilder adminAppRoles = new StringBuilder();
-                if (result != null) {
-                       if (!result.appsRoles.isEmpty()) {
-                              adminAppRoles.append("User '" + result.orgUserId + "' has admin role to the apps = {");
-                              for (AppNameIdIsAdmin adminAppRole : result.appsRoles) {
-                                     if (adminAppRole.isAdmin) {
-                                            adminAppRoles.append(adminAppRole.appName + ", ");
-                                     }
-                              }
-                              adminAppRoles.append("}.");
-                       } else {
-                              adminAppRoles.append("User '" + result.orgUserId + "' has no Apps with Admin Role.");
-                       }
-                } else {
-                       logger.error(EELFLoggerDelegate.errorLogger,
-                               "putAppWithUserRoleStateForUser: getAppsWithAdminRoleStateForUser result is null");
-                }
 
-                logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
-
-                EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result);
-
-                return result;
-         }
-*/
-  @RequestMapping(value = {"/portalApi/adminAppsRoles"}, method = {
-      RequestMethod.PUT}, produces = "application/json")
-  public FieldsValidator putAppsWithAdminRoleStateForUser(Principal principal,
-      @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) {
-    // newAppsListWithAdminRoles.appsRoles
-    FieldsValidator fieldsValidator = new FieldsValidator();
-    StringBuilder newAppRoles = new StringBuilder();
-    if (newAppsListWithAdminRoles != null) {
-      if (!newAppsListWithAdminRoles.getAppsRoles().isEmpty()) {
-        newAppRoles.append("User '").append(newAppsListWithAdminRoles.getOrgUserId())
-            .append("' has admin role to the apps = { ");
-        for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.getAppsRoles()) {
-          if (adminAppRole.getIsAdmin()) {
-            newAppRoles.append(adminAppRole.getAppName()).append(" ,");
-          }
+    @RequestMapping(value = {"/portalApi/queryUsers"}, method = RequestMethod.GET, produces = "application/json")
+    @PreAuthorize("hasRole('System_Administrator') and hasRole('Account_Administrator')")
+    public String getPhoneBookSearchResult(Principal principal, @RequestParam("search") String searchString,
+        HttpServletResponse response) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+
+        String searchResult = null;
+        if (!adminRolesService.isSuperAdmin(user.getLoginId()) && !adminRolesService
+            .isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps())
+            && !adminRolesService.isRoleAdmin(user.getId())) {
+            EcompPortalUtils.setBadPermissions(user, response, "getPhoneBookSearchResult");
+        } else {
+            searchString = searchString.trim();
+            if (searchString.length() > 2) {
+                searchResult = searchService.searchUsersInPhoneBook(searchString);
+            } else {
+                logger.info(EELFLoggerDelegate.errorLogger,
+                    "getPhoneBookSearchResult - too short search string: " + searchString);
+            }
         }
-        newAppRoles.deleteCharAt(newAppRoles.length() - 1);
-        newAppRoles.append("}.");
-      } else {
-        newAppRoles.append("User '").append(newAppsListWithAdminRoles.getOrgUserId())
-            .append("' has no Apps with Admin Role.");
-      }
-    } else {
-      logger.error(EELFLoggerDelegate.errorLogger,
-          "putAppWithUserRoleStateForUser: putAppsWithAdminRoleStateForUser result is null");
-      fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-    }
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/queryUsers", "result =", searchResult);
 
-    logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
-
-    FnUser user = fnUserService.loadUserByUsername(principal.getName());
-
-    boolean changesApplied = false;
-
-    if (!adminRolesService.isSuperAdmin(user.getLoginId())) {
-      EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
-    } else {
-      changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
-      AuditLog auditLog = new AuditLog();
-      auditLog.setUserId(user.getId());
-      auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN);
-      if (newAppsListWithAdminRoles != null) {
-        auditLog.setAffectedRecordId(newAppsListWithAdminRoles.getOrgUserId());
-      }
-      auditLog.setComments(
-          EcompPortalUtils
-              .truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE));
-      auditService.logActivity(auditLog, null);
-
-      MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
-          EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-      MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
-          EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-      EcompPortalUtils.calculateDateTimeDifferenceForLog(
-          MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
-          MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
-      if (newAppsListWithAdminRoles != null) {
-        logger.info(EELFLoggerDelegate.auditLogger,
-            EPLogUtil.formatAuditLogMessage(
-                "UserRolesController.putAppsWithAdminRoleStateForUser",
-                EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(),
-                newAppsListWithAdminRoles.getOrgUserId(), newAppRoles.toString()));
-      }
-      MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
-      MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
-      MDC.remove(SystemProperties.MDC_TIMER);
+        return searchResult;
     }
-    EcompPortalUtils
-        .logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
-
-    return fieldsValidator;
-  }
-
-  @RequestMapping(value = {"/portalApi/userAppRoles"}, method = {
-      RequestMethod.GET}, produces = "application/json")
-  public List<RoleInAppForUser> getAppRolesForUser(Principal principal,
-      @RequestParam("user") String orgUserId,
-      @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,
-      @RequestParam("isSystemUser") Boolean isSystemUser,
-      HttpServletResponse response) {
-    FnUser user = fnUserService.loadUserByUsername(principal.getName());
-    List<RoleInAppForUser> result = null;
-    String feErrorString = "";
-    if (!adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()) && !adminRolesService.isRoleAdmin(user.getId())) {
-      logger.debug(EELFLoggerDelegate.debugLogger,
-          "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}",
-          adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()), adminRolesService.isRoleAdmin(user.getId()));
-      EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
-      feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
-    } else {
-      if (isSystemUser || EcompPortalUtils.legitimateUserId(orgUserId)) {
-        result = adminRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user.getId());
-        logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}",
-            result, appid);
-        int responseCode = EcompPortalUtils.getExternalAppResponseCode();
-        if (responseCode != 0 && responseCode != 200) {
-          // external error
-          response.setStatus(responseCode);
-          feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
-        } else if (result == null) {
-          // If the result is null, there was an internal onap error
-          // in the service call.
-          response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
-          feErrorString = EcompPortalUtils.getFEErrorString(true,
-              HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+
+
+    @RequestMapping(value = {"/portalApi/adminAppsRoles"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(Principal principal,
+        @RequestParam("user") String orgUserId, HttpServletResponse response) {
+
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+
+        AppsListWithAdminRole result = null;
+        if (!adminRolesService.isSuperAdmin(user.getLoginId())) {
+            EcompPortalUtils.setBadPermissions(user, response, "getAppsWithAdminRoleStateForUser");
+        } else {
+            if (EcompPortalUtils.legitimateUserId(orgUserId)) {
+                result = adminRolesService.getAppsWithAdminRoleStateForUser(orgUserId);
+            } else {
+                logger.info(EELFLoggerDelegate.errorLogger,
+                    "getAppsWithAdminRoleStateForUser - parms error, no Organization User ID");
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+            }
         }
-      } else {
-        logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
-        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
-        feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
-      }
-    }
 
-    StringBuilder sbUserApps = new StringBuilder();
-    if (result != null && !result.isEmpty()) {
-      sbUserApps.append("User '").append(orgUserId).append("' has Roles={");
-      for (RoleInAppForUser appRole : result) {
-        if (appRole.getIsApplied()) {
-          sbUserApps.append(appRole.getRoleName()).append(", ");
+        StringBuilder adminAppRoles = new StringBuilder();
+        if (result != null) {
+            if (!result.getAppsRoles().isEmpty()) {
+                adminAppRoles.append("User '").append(result.getOrgUserId())
+                    .append("' has admin role to the apps = {");
+                for (AppNameIdIsAdmin adminAppRole : result.getAppsRoles()) {
+                    if (adminAppRole.getIsAdmin()) {
+                        adminAppRoles.append(adminAppRole.getAppName()).append(", ");
+                    }
+                }
+                adminAppRoles.append("}.");
+            } else {
+                adminAppRoles.append("User '").append(result.getOrgUserId())
+                    .append("' has no Apps with Admin Role.");
+            }
+        } else {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "putAppWithUserRoleStateForUser: getAppsWithAdminRoleStateForUser result is null");
         }
-      }
-      sbUserApps.append("} assigned to the appId '").append(appid).append("'.");
-    } else {
-      // Not sure creating an empty object will make any difference
-      // but would like to give it a shot for defect #DE221057
-      if (result == null) {
-        result = new ArrayList<>();
-      }
-      sbUserApps.append("User '").append(orgUserId).append("' and appid ").append(appid).append(" has no roles");
-    }
-    logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
 
-    EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
-    if (!feErrorString.isEmpty()) {
-      logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString);
+        logger.info(EELFLoggerDelegate.errorLogger, adminAppRoles.toString());
+
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "get result =", result);
 
-      response.addHeader("FEErrorString", feErrorString);
-      response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
+        return result;
     }
-    return result;
-  }
-
-
-  @RequestMapping(value = {"/portalApi/userAppRoles"}, method = {
-      RequestMethod.PUT}, produces = "application/json")
-  public PortalRestResponse<String> putAppWithUserRoleStateForUser(Principal principal,
-      @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
-    // FieldsValidator fieldsValidator = new FieldsValidator();
-    PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
-    StringBuilder sbUserApps = new StringBuilder();
-    if (newAppRolesForUser != null) {
-      sbUserApps.append("User '").append(newAppRolesForUser.getOrgUserId());
-      if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) {
-        sbUserApps.append("' has roles = { ");
-        for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) {
-          if (appRole.getIsApplied()) {
-            sbUserApps.append(appRole.getRoleName()).append(" ,");
-          }
+
+    @RequestMapping(value = {"/portalApi/adminAppsRoles"}, method = {
+        RequestMethod.PUT}, produces = "application/json")
+    public FieldsValidator putAppsWithAdminRoleStateForUser(Principal principal,
+        @RequestBody AppsListWithAdminRole newAppsListWithAdminRoles, HttpServletResponse response) {
+        // newAppsListWithAdminRoles.appsRoles
+        FieldsValidator fieldsValidator = new FieldsValidator();
+        StringBuilder newAppRoles = new StringBuilder();
+        if (newAppsListWithAdminRoles != null) {
+            if (!newAppsListWithAdminRoles.getAppsRoles().isEmpty()) {
+                newAppRoles.append("User '").append(newAppsListWithAdminRoles.getOrgUserId())
+                    .append("' has admin role to the apps = { ");
+                for (AppNameIdIsAdmin adminAppRole : newAppsListWithAdminRoles.getAppsRoles()) {
+                    if (adminAppRole.getIsAdmin()) {
+                        newAppRoles.append(adminAppRole.getAppName()).append(" ,");
+                    }
+                }
+                newAppRoles.deleteCharAt(newAppRoles.length() - 1);
+                newAppRoles.append("}.");
+            } else {
+                newAppRoles.append("User '").append(newAppsListWithAdminRoles.getOrgUserId())
+                    .append("' has no Apps with Admin Role.");
+            }
+        } else {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "putAppWithUserRoleStateForUser: putAppsWithAdminRoleStateForUser result is null");
+            fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+        }
+
+        logger.info(EELFLoggerDelegate.errorLogger, newAppRoles.toString());
+
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+
+        boolean changesApplied = false;
+
+        if (!adminRolesService.isSuperAdmin(user.getLoginId())) {
+            EcompPortalUtils.setBadPermissions(user, response, "putAppsWithAdminRoleStateForUser");
+        } else {
+            changesApplied = adminRolesService.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles);
+            AuditLog auditLog = new AuditLog();
+            auditLog.setUserId(user.getId());
+            auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN);
+            if (newAppsListWithAdminRoles != null) {
+                auditLog.setAffectedRecordId(newAppsListWithAdminRoles.getOrgUserId());
+            }
+            auditLog.setComments(
+                EcompPortalUtils
+                    .truncateString(newAppRoles.toString(), PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+            auditService.logActivity(auditLog, null);
+
+            MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
+                EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+            MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
+                EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+            EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+            if (newAppsListWithAdminRoles != null) {
+                logger.info(EELFLoggerDelegate.auditLogger,
+                    EPLogUtil.formatAuditLogMessage(
+                        "UserRolesController.putAppsWithAdminRoleStateForUser",
+                        EcompAuditLog.CD_ACTIVITY_UPDATE_ACCOUNT_ADMIN, user.getOrgUserId(),
+                        newAppsListWithAdminRoles.getOrgUserId(), newAppRoles.toString()));
+            }
+            MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+            MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+            MDC.remove(SystemProperties.MDC_TIMER);
         }
-        sbUserApps.deleteCharAt(sbUserApps.length() - 1);
-        sbUserApps.append("} assigned for the app ").append(newAppRolesForUser.getAppId());
-      } else {
-        sbUserApps.append("' has no roles assigned for app ").append(newAppRolesForUser.getAppId());
-      }
+        EcompPortalUtils
+            .logAndSerializeObject(logger, "/portalApi/adminAppsRoles", "put result =", changesApplied);
+
+        return fieldsValidator;
     }
-    logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}",
-        sbUserApps.toString());
-
-    FnUser user = fnUserService.loadUserByUsername(principal.getName());
-    // boolean changesApplied = false;
-    ExternalRequestFieldsValidator changesApplied = null;
-
-    if (!adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()) && !adminRolesService.isRoleAdmin(user.getId())) {
-      EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
-    } else if (newAppRolesForUser == null) {
-      logger.error(EELFLoggerDelegate.errorLogger,
-          "putAppWithUserRoleStateForUser: newAppRolesForUser is null");
-    } else {
-      changesApplied = adminRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
-      try {
-        if (changesApplied.isResult()) {
-          logger.info(EELFLoggerDelegate.applicationLogger,
-              "putAppWithUserRoleStateForUser: succeeded for app {}, user {}",
-              newAppRolesForUser.getAppId(),
-              newAppRolesForUser.getAppId());
-
-          MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
-              EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-          AuditLog auditLog = new AuditLog();
-          auditLog.setUserId(user.getId());
-          auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
-          auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId());
-          auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(),
-              PortalConstants.AUDIT_LOG_COMMENT_SIZE));
-          auditService.logActivity(auditLog, null);
-
-          MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
-              EPEELFLoggerAdvice.getCurrentDateTimeUTC());
-          EcompPortalUtils.calculateDateTimeDifferenceForLog(
-              MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
-              MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
-          logger.info(EELFLoggerDelegate.auditLogger,
-              EPLogUtil.formatAuditLogMessage(
-                  "UserRolesController.putAppWithUserRoleStateForUser",
-                  EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(),
-                  newAppRolesForUser.getOrgUserId(), sbUserApps.toString()));
-          MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
-          MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
-          MDC.remove(SystemProperties.MDC_TIMER);
-          portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
 
+    @RequestMapping(value = {"/portalApi/userAppRoles"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public List<RoleInAppForUser> getAppRolesForUser(Principal principal,
+        @RequestParam("user") String orgUserId,
+        @RequestParam("app") Long appid, @RequestParam("externalRequest") Boolean extRequestValue,
+        @RequestParam("isSystemUser") Boolean isSystemUser,
+        HttpServletResponse response) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        List<RoleInAppForUser> result = null;
+        String feErrorString = "";
+        if (!adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps())
+            && !adminRolesService.isRoleAdmin(user.getId())) {
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "getAppRolesForUser: Accountadminpermissioncheck {}, RoleAdmincheck {}",
+                adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps()),
+                adminRolesService.isRoleAdmin(user.getId()));
+            EcompPortalUtils.setBadPermissions(user, response, "getAppRolesForUser");
+            feErrorString = EcompPortalUtils.getFEErrorString(true, response.getStatus());
+        } else {
+            if (isSystemUser || EcompPortalUtils.legitimateUserId(orgUserId)) {
+                result = adminRolesService.getAppRolesForUser(appid, orgUserId, extRequestValue, user.getId());
+                logger.debug(EELFLoggerDelegate.debugLogger, "getAppRolesForUser: result {}, appId {}",
+                    result, appid);
+                int responseCode = EcompPortalUtils.getExternalAppResponseCode();
+                if (responseCode != 0 && responseCode != 200) {
+                    // external error
+                    response.setStatus(responseCode);
+                    feErrorString = EcompPortalUtils.getFEErrorString(false, responseCode);
+                } else if (result == null) {
+                    // If the result is null, there was an internal onap error
+                    // in the service call.
+                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                    feErrorString = EcompPortalUtils.getFEErrorString(true,
+                        HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+                }
+            } else {
+                logger.info(EELFLoggerDelegate.errorLogger, "getAppRolesForUser - no Organization User ID");
+                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
+                feErrorString = EcompPortalUtils.getFEErrorString(true, HttpServletResponse.SC_BAD_REQUEST);
+            }
         }
-        if (!changesApplied.isResult()) {
-          throw new Exception(changesApplied.getDetailMessage());
+
+        StringBuilder sbUserApps = new StringBuilder();
+        if (result != null && !result.isEmpty()) {
+            sbUserApps.append("User '").append(orgUserId).append("' has Roles={");
+            for (RoleInAppForUser appRole : result) {
+                if (appRole.getIsApplied()) {
+                    sbUserApps.append(appRole.getRoleName()).append(", ");
+                }
+            }
+            sbUserApps.append("} assigned to the appId '").append(appid).append("'.");
+        } else {
+            // Not sure creating an empty object will make any difference
+            // but would like to give it a shot for defect #DE221057
+            if (result == null) {
+                result = new ArrayList<>();
+            }
+            sbUserApps.append("User '").append(orgUserId).append("' and appid ").append(appid).append(" has no roles");
         }
+        logger.info(EELFLoggerDelegate.errorLogger, sbUserApps.toString());
+
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "get result =", result);
+        if (!feErrorString.isEmpty()) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "LR: FEErrorString to header: " + feErrorString);
 
-      } catch (Exception e) {
-        logger.error(EELFLoggerDelegate.errorLogger,
-            "putAppWithUserRoleStateForUser: failed for app {}, user {}",
-            newAppRolesForUser.getAppId(),
-            newAppRolesForUser.getOrgUserId(), e);
-        portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null);
-      }
+            response.addHeader("FEErrorString", feErrorString);
+            response.addHeader("Access-Control-Expose-Headers", "FEErrorString");
+        }
+        return result;
     }
 
-    EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
-    return portalResponse;
-  }
-
-  @RequestMapping(value = {"/portalApi/updateRemoteUserProfile"}, method = {
-      RequestMethod.GET}, produces = "application/json")
-  public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request) {
-
-    String updateRemoteUserFlag = FAILURE;
-    try {
-      // saveNewUser = userService.saveNewUser(newUser);
-      String orgUserId = request.getParameter("loginId");
-      long appId = Long.parseLong(request.getParameter("appId"));
-      fnUserRoleService.updateRemoteUserProfile(orgUserId, appId);
-    } catch (Exception e) {
-      logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
-      return new PortalRestResponse<>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
+
+    @RequestMapping(value = {"/portalApi/userAppRoles"}, method = {
+        RequestMethod.PUT}, produces = "application/json")
+    public PortalRestResponse<String> putAppWithUserRoleStateForUser(Principal principal,
+        @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
+        // FieldsValidator fieldsValidator = new FieldsValidator();
+        PortalRestResponse<String> portalResponse = new PortalRestResponse<>();
+        StringBuilder sbUserApps = new StringBuilder();
+        if (newAppRolesForUser != null) {
+            sbUserApps.append("User '").append(newAppRolesForUser.getOrgUserId());
+            if (newAppRolesForUser.getAppId() != null && !newAppRolesForUser.getAppRoles().isEmpty()) {
+                sbUserApps.append("' has roles = { ");
+                for (RoleInAppForUser appRole : newAppRolesForUser.getAppRoles()) {
+                    if (appRole.getIsApplied()) {
+                        sbUserApps.append(appRole.getRoleName()).append(" ,");
+                    }
+                }
+                sbUserApps.deleteCharAt(sbUserApps.length() - 1);
+                sbUserApps.append("} assigned for the app ").append(newAppRolesForUser.getAppId());
+            } else {
+                sbUserApps.append("' has no roles assigned for app ").append(newAppRolesForUser.getAppId());
+            }
+        }
+        logger.info(EELFLoggerDelegate.applicationLogger, "putAppWithUserRoleStateForUser: {}",
+            sbUserApps.toString());
+
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        // boolean changesApplied = false;
+        ExternalRequestFieldsValidator changesApplied = null;
+
+        if (!adminRolesService.isAccountAdmin(user.getId(), user.getOrgUserId(), user.getUserApps())
+            && !adminRolesService.isRoleAdmin(user.getId())) {
+            EcompPortalUtils.setBadPermissions(user, response, "putAppWithUserRoleStateForUser");
+        } else if (newAppRolesForUser == null) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "putAppWithUserRoleStateForUser: newAppRolesForUser is null");
+        } else {
+            changesApplied = adminRolesService.setAppWithUserRoleStateForUser(user, newAppRolesForUser);
+            try {
+                if (changesApplied.isResult()) {
+                    logger.info(EELFLoggerDelegate.applicationLogger,
+                        "putAppWithUserRoleStateForUser: succeeded for app {}, user {}",
+                        newAppRolesForUser.getAppId(),
+                        newAppRolesForUser.getAppId());
+
+                    MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP,
+                        EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                    AuditLog auditLog = new AuditLog();
+                    auditLog.setUserId(user.getId());
+                    auditLog.setActivityCode(EcompAuditLog.CD_ACTIVITY_UPDATE_USER);
+                    auditLog.setAffectedRecordId(newAppRolesForUser.getOrgUserId());
+                    auditLog.setComments(EcompPortalUtils.truncateString(sbUserApps.toString(),
+                        PortalConstants.AUDIT_LOG_COMMENT_SIZE));
+                    auditService.logActivity(auditLog, null);
+
+                    MDC.put(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP,
+                        EPEELFLoggerAdvice.getCurrentDateTimeUTC());
+                    EcompPortalUtils.calculateDateTimeDifferenceForLog(
+                        MDC.get(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP),
+                        MDC.get(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP));
+                    logger.info(EELFLoggerDelegate.auditLogger,
+                        EPLogUtil.formatAuditLogMessage(
+                            "UserRolesController.putAppWithUserRoleStateForUser",
+                            EcompAuditLog.CD_ACTIVITY_UPDATE_USER, user.getOrgUserId(),
+                            newAppRolesForUser.getOrgUserId(), sbUserApps.toString()));
+                    MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP);
+                    MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP);
+                    MDC.remove(SystemProperties.MDC_TIMER);
+                    portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.OK, "success", null);
+
+                }
+                if (!changesApplied.isResult()) {
+                    throw new Exception(changesApplied.getDetailMessage());
+                }
+
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "putAppWithUserRoleStateForUser: failed for app {}, user {}",
+                    newAppRolesForUser.getAppId(),
+                    newAppRolesForUser.getOrgUserId(), e);
+                portalResponse = new PortalRestResponse<>(PortalRestStatusEnum.ERROR, e.getMessage(), null);
+            }
+        }
+
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/userAppRoles", "put result =", changesApplied);
+        return portalResponse;
     }
-    return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
-
-  }
-
-  @RequestMapping(value = {"/portalApi/app/{appId}/users"}, method = {
-      RequestMethod.GET}, produces = "application/json")
-  public List<UserApplicationRoles> getUsersFromAppEndpoint(@PathVariable("appId") Long appId) {
-    try {
-      logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
-      return fnUserRoleService.getUsersFromAppEndpoint(appId);
-    } catch (Exception e) {
-      logger.error(EELFLoggerDelegate.errorLogger, "getUsersFromAppEndpoint failed", e);
-      return new ArrayList<>();
+
+    @RequestMapping(value = {"/portalApi/updateRemoteUserProfile"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public PortalRestResponse<String> updateRemoteUserProfile(HttpServletRequest request) {
+
+        String updateRemoteUserFlag = FAILURE;
+        try {
+            // saveNewUser = userService.saveNewUser(newUser);
+            String orgUserId = request.getParameter("loginId");
+            long appId = Long.parseLong(request.getParameter("appId"));
+            fnUserRoleService.updateRemoteUserProfile(orgUserId, appId);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "updateRemoteUserProfile failed", e);
+            return new PortalRestResponse<>(PortalRestStatusEnum.OK, updateRemoteUserFlag, e.getMessage());
+        }
+        return new PortalRestResponse<>(PortalRestStatusEnum.ERROR, updateRemoteUserFlag, "");
+
     }
-  }
-
-  @RequestMapping(value = {"/portalApi/app/{appId}/roles"}, method = {
-      RequestMethod.GET}, produces = "application/json")
-  public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId)
-      throws HTTPException {
-    EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
-    List<EcompRole> rolesList = Arrays.asList(appRoles);
-    EcompPortalUtils
-        .logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId,
-            rolesList);
-
-    return rolesList;
-  }
-
-
-  @RequestMapping(value = {"/portalApi/admin/import/app/{appId}/roles"}, method = {
-      RequestMethod.GET}, produces = "application/json")
-  public List<FnRole> importRolesFromRemoteApplication(@PathVariable("appId") Long appId) throws HTTPException {
-    List<FnRole> rolesList = fnUserRoleService.importRolesFromRemoteApplication(appId);
-    EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles",
-        "response for appId=" + appId, rolesList);
-
-    return rolesList;
-  }
-
-
-  @RequestMapping(value = {"/portalApi/app/{appId}/user/{orgUserId}/roles"}, method = {
-      RequestMethod.GET}, produces = "application/json")
-  public EcompRole testGetRoles(@PathVariable("appId") Long appId,
-      @PathVariable("orgUserId") String orgUserId) throws Exception {
-    if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
-      String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
-      logger.error(EELFLoggerDelegate.errorLogger, msg);
-      throw new Exception(msg);
+
+    @RequestMapping(value = {"/portalApi/app/{appId}/users"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public List<UserApplicationRoles> getUsersFromAppEndpoint(@PathVariable("appId") Long appId) {
+        try {
+            logger.debug(EELFLoggerDelegate.debugLogger, "/portalApi/app/{}/users was invoked", appId);
+            return fnUserRoleService.getUsersFromAppEndpoint(appId);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getUsersFromAppEndpoint failed", e);
+            return new ArrayList<>();
+        }
     }
-    EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId,
-        String.format("/user/%s/roles", orgUserId));
-    if (roles.length != 1) {
-      String msg =
-          "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
-      logger.error(EELFLoggerDelegate.errorLogger, msg);
-      throw new Exception(msg);
+
+    @RequestMapping(value = {"/portalApi/app/{appId}/roles"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public List<EcompRole> testGetRoles(HttpServletRequest request, @PathVariable("appId") Long appId)
+        throws HTTPException {
+        EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, appId, "/roles");
+        List<EcompRole> rolesList = Arrays.asList(appRoles);
+        EcompPortalUtils
+            .logAndSerializeObject(logger, "/portalApi/app/{appId}/roles", "response for appId=" + appId,
+                rolesList);
+
+        return rolesList;
     }
 
-    EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles",
-        "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
-    return roles[0];
-  }
 
+    @RequestMapping(value = {"/portalApi/admin/import/app/{appId}/roles"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public List<FnRole> importRolesFromRemoteApplication(@PathVariable("appId") Long appId) throws HTTPException {
+        List<FnRole> rolesList = fnUserRoleService.importRolesFromRemoteApplication(appId);
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/admin/import/app/{appId}/roles",
+            "response for appId=" + appId, rolesList);
 
-  @RequestMapping(value = {"/portalApi/saveUserAppRoles"}, method = {
-      RequestMethod.PUT}, produces = "application/json")
-  public FieldsValidator putAppWithUserRoleRequest(Principal principal,
-      @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
-    FieldsValidator fieldsValidator = null;
-    FnUser user = fnUserService.loadUserByUsername(principal.getName());
-    try {
-      fieldsValidator = fnUserRoleService.putUserAppRolesRequest(newAppRolesForUser, user);
-      response.setStatus(0);
+        return rolesList;
+    }
 
-    } catch (Exception e) {
-      logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e);
 
+    @RequestMapping(value = {"/portalApi/app/{appId}/user/{orgUserId}/roles"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public EcompRole testGetRoles(@PathVariable("appId") Long appId,
+        @PathVariable("orgUserId") String orgUserId) throws Exception {
+        if (!EcompPortalUtils.legitimateUserId(orgUserId)) {
+            String msg = "Error /user/<user>/roles not legitimate orgUserId = " + orgUserId;
+            logger.error(EELFLoggerDelegate.errorLogger, msg);
+            throw new Exception(msg);
+        }
+        EcompRole[] roles = applicationsRestClientService.get(EcompRole[].class, appId,
+            String.format("/user/%s/roles", orgUserId));
+        if (roles.length != 1) {
+            String msg =
+                "Error /user/<user>/roles returned array. expected size 1 recieved size = " + roles.length;
+            logger.error(EELFLoggerDelegate.errorLogger, msg);
+            throw new Exception(msg);
+        }
+
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/app/{appId}/user/{orgUserId}/roles",
+            "response for appId='" + appId + "' and orgUserId='" + orgUserId + "'", roles[0]);
+        return roles[0];
     }
-    // return fieldsValidator;
-    EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =",
-        response.getStatus());
-    return fieldsValidator;
-  }
-
-
-  @SuppressWarnings("ConstantConditions")
-  @RequestMapping(value = {"/portalApi/appCatalogRoles"}, method = {
-      RequestMethod.GET}, produces = "application/json")
-  public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(Principal principal,
-      @RequestParam("appName") String appName) {
-    FnUser user = fnUserService.loadUserByUsername(principal.getName());
-    List<EPUserAppCatalogRoles> userAppRoleList = null;
-    try {
-      userAppRoleList = fnUserRoleService.getUserAppCatalogRoles(user, appName);
-    } catch (Exception e) {
-      logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
 
+
+    @RequestMapping(value = {"/portalApi/saveUserAppRoles"}, method = {
+        RequestMethod.PUT}, produces = "application/json")
+    public FieldsValidator putAppWithUserRoleRequest(Principal principal,
+        @RequestBody AppWithRolesForUser newAppRolesForUser, HttpServletResponse response) {
+        FieldsValidator fieldsValidator = null;
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        try {
+            fieldsValidator = fnUserRoleService.putUserAppRolesRequest(newAppRolesForUser, user);
+            response.setStatus(0);
+
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "putAppWithUserRoleRequest failed", e);
+
+        }
+        // return fieldsValidator;
+        EcompPortalUtils.logAndSerializeObject(logger, "/portalApi/saveUserAppRoles", "PUT result =",
+            response.getStatus());
+        return fieldsValidator;
     }
-    userAppRoleList.sort(getUserAppCatalogRolesComparator);
-    EcompPortalUtils
-        .logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
-
-    return userAppRoleList;
-
-  }
-
-
-  private final Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator =
-      Comparator.comparing(EPUserAppCatalogRoles::getRoleName);
-
-  @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET,
-      produces = "application/json")
-  public ExternalSystemAccess readExternalRequestAccess() {
-    ExternalSystemAccess result = null;
-    try {
-      result = fnUserRoleService.getExternalRequestAccess();
-      EcompPortalUtils
-          .logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =",
-              result);
-    } catch (Exception e) {
-      logger.error(EELFLoggerDelegate.errorLogger,
-          "readExternalRequestAccess failed: " + e.getMessage());
+
+
+    @SuppressWarnings("ConstantConditions")
+    @RequestMapping(value = {"/portalApi/appCatalogRoles"}, method = {
+        RequestMethod.GET}, produces = "application/json")
+    public List<EPUserAppCatalogRoles> getUserAppCatalogRoles(Principal principal,
+        @RequestParam("appName") String appName) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
+        List<EPUserAppCatalogRoles> userAppRoleList = null;
+        try {
+            userAppRoleList = fnUserRoleService.getUserAppCatalogRoles(user, appName);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "putUserWidgetsSortPref failed", e);
+
+        }
+        userAppRoleList.sort(getUserAppCatalogRolesComparator);
+        EcompPortalUtils
+            .logAndSerializeObject(logger, "/portalApi/userApplicationRoles", "result =", userAppRoleList);
+
+        return userAppRoleList;
+
     }
-    return result;
 
-  }
 
-  @RequestMapping(value = {"/portalApi/checkIfUserIsSuperAdmin"}, method = RequestMethod.GET,
-      produces = "application/json")
-  public boolean checkIfUserIsSuperAdmin(Principal principal) {
-    FnUser user = fnUserService.loadUserByUsername(principal.getName());
+    private final Comparator<EPUserAppCatalogRoles> getUserAppCatalogRolesComparator =
+        Comparator.comparing(EPUserAppCatalogRoles::getRoleName);
+
+    @RequestMapping(value = "/portalApi/externalRequestAccessSystem", method = RequestMethod.GET,
+        produces = "application/json")
+    public ExternalSystemAccess readExternalRequestAccess() {
+        ExternalSystemAccess result = null;
+        try {
+            result = fnUserRoleService.getExternalRequestAccess();
+            EcompPortalUtils
+                .logAndSerializeObject(logger, "/portalApi/externalRequestAccessSystem", "GET result =",
+                    result);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "readExternalRequestAccess failed: " + e.getMessage());
+        }
+        return result;
+
+    }
+
+    @RequestMapping(value = {"/portalApi/checkIfUserIsSuperAdmin"}, method = RequestMethod.GET,
+        produces = "application/json")
+    public boolean checkIfUserIsSuperAdmin(Principal principal) {
+        FnUser user = fnUserService.loadUserByUsername(principal.getName());
 
-    boolean isSuperAdmin = false;
-    try {
-      isSuperAdmin = adminRolesService.isSuperAdmin(user.getLoginId());
-    } catch (Exception e) {
-      logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage());
+        boolean isSuperAdmin = false;
+        try {
+            isSuperAdmin = adminRolesService.isSuperAdmin(user.getLoginId());
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "checkIfUserIsSuperAdmin failed: " + e.getMessage());
+        }
+        return isSuperAdmin;
     }
-    return isSuperAdmin;
-  }
 }
index 92b4b51..da1343d 100644 (file)
@@ -42,8 +42,8 @@ package org.onap.portal.controller;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import org.onap.portal.domain.dto.ecomp.PortalRestResponse;
-import org.onap.portal.domain.dto.ecomp.PortalRestStatusEnum;
+import org.onap.portal.domain.dto.PortalRestResponse;
+import org.onap.portal.domain.dto.PortalRestStatusEnum;
 import org.onap.portal.service.WidgetMService;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
 import org.springframework.beans.factory.annotation.Autowired;
index 2c23c3d..01641e1 100644 (file)
@@ -50,6 +50,7 @@ import javax.persistence.FetchType;
 import javax.persistence.Index;
 import javax.persistence.JoinColumn;
 import javax.persistence.ManyToOne;
+import javax.persistence.NamedNativeQuery;
 import javax.persistence.NamedQueries;
 import javax.persistence.NamedQuery;
 import javax.persistence.OneToMany;
@@ -81,7 +82,7 @@ CREATE TABLE `ep_app_function` (
 @NamedQueries({
     @NamedQuery(
         name = "EpAppFunction.getAppRoleFunctionList",
-        query = "from\n"
+        query = "SELECT DISTINCT f from\n"
             + "  EpAppRoleFunction rf,\n"
             + "  EpAppFunction f\n"
             + " where\n"
@@ -89,6 +90,18 @@ CREATE TABLE `ep_app_function` (
             + "  and rf.appId.id = :appId\n"
             + "  and rf.appId.id = f.appId.id\n"
             + "  and rf.epAppFunction.functionCd = f.functionCd"
+    ),
+    @NamedQuery(
+        name = "EpAppFunction.getAllRoleFunctions",
+        query = "from EpAppFunction where appId.id =:appId"
+    ),
+    @NamedQuery(
+        name = "EpAppFunction.getAppFunctionOnCodeAndAppId",
+        query = "from EpAppFunction where appId.id =:appId and functionCd =:functionCd "
+    ),
+    @NamedQuery(
+        name = "EpAppFunction.getRoleFunction",
+        query = "from EpAppFunction where functionCd like CONCAT('%', :functionCode,'%') and appId.id =:appId"
     )
 })
 
@@ -145,13 +158,12 @@ public class EpAppFunction extends DomainVo implements Serializable {
   }
 
   @Builder
-  public EpAppFunction(@Digits(integer = 11, fraction = 0) Long id,
-      LocalDateTime created, LocalDateTime modified, Long rowNum, Serializable auditUserId,
-      DomainVo createdId, DomainVo modifiedId, Set<DomainVo> fnUsersCreatedId,
+  public EpAppFunction(@Digits(integer = 11, fraction = 0) Long id, LocalDateTime created,
+      LocalDateTime modified, Long rowNum, Serializable auditUserId, DomainVo createdId,
+      DomainVo modifiedId, Set<DomainVo> fnUsersCreatedId,
       Set<DomainVo> fnUsersModifiedId, @Valid FnApp appId,
-      @Size(max = 250) @NotNull @SafeHtml String functionCd,
-      @Size(max = 250) @NotNull @SafeHtml String functionName, Long roleId, String type,
-      @SafeHtml String action, @SafeHtml String editUrl,
+      @Size(max = 250) @NotNull String functionCd,
+      @Size(max = 250) @NotNull String functionName, Long roleId, String type, String action, String editUrl,
       Set<EpAppRoleFunction> epAppRoleFunctions) {
     super(id, created, modified, rowNum, auditUserId, createdId, modifiedId, fnUsersCreatedId, fnUsersModifiedId);
     this.appId = appId;
index 3cb219a..117167a 100644 (file)
@@ -53,6 +53,8 @@ import javax.persistence.Index;
 import javax.persistence.JoinColumn;
 import javax.persistence.JoinColumns;
 import javax.persistence.ManyToOne;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
 import javax.persistence.Table;
 import javax.validation.Valid;
 import javax.validation.constraints.Digits;
@@ -83,6 +85,13 @@ CREATE TABLE `ep_app_role_function` (
         )
 */
 
+@NamedQueries({
+    @NamedQuery(
+        name = "EpAppRoleFunction.getAppRoleFunctionOnRoleIdAndAppId",
+        query = "from EpAppRoleFunction where appId.id = :appId and fnRole.id = :roleId"
+    )
+})
+
 @Table(name = "ep_app_role_function", indexes = {
     @Index(name = "fk_ep_app_role_function_ep_app_func_role_id", columnList = "app_id, role_id, function_cd", unique = true),
     @Index(name = "fk_ep_app_role_function_ep_app_func", columnList = "app_id, function_cd"),
index 74b051f..a4180a2 100644 (file)
@@ -80,10 +80,10 @@ CREATE TABLE `ep_microservice_parameter` (
 @NamedQueries({
         @NamedQuery(
                 name = "EpMicroserviceParameter.deleteByServiceId",
-                query = "DELETE FROM EpMicroserviceParameter WHERE service_id =:SERVICEID"),
+                query = "DELETE FROM EpMicroserviceParameter WHERE serviceId.id =:SERVICEID"),
         @NamedQuery(
                 name = "EpMicroserviceParameter.getParametersById",
-                query = "FROM EpMicroserviceParameter WHERE service_id =:SERVICEID")
+                query = "FROM EpMicroserviceParameter WHERE serviceId.id =:SERVICEID")
 })
 
 @Table(name = "ep_microservice_parameter", indexes = {
index 113863c..7828c13 100644 (file)
@@ -100,42 +100,42 @@ CREATE TABLE `ep_user_roles_request` (
 @Setter
 @Entity
 public class EpUserRolesRequest implements Serializable {
-       @Id
 
-  @GeneratedValue(strategy = GenerationType.AUTO)
-       @Column(name = "req_id", length = 11, nullable = false, columnDefinition = "int(11) AUTO_INCREMENT")
-       @Digits(integer = 11, fraction = 0)
-       private Long reqId;
-       @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
-       @JoinColumn(name = "user_id", nullable = false, columnDefinition = "bigint")
-       @NotNull
-       @Valid
-       private FnUser userId;
-       @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
-       @JoinColumn(name = "app_id", nullable = false, columnDefinition = "bigint")
-       @NotNull
-       @Valid
-       private FnApp appId;
-       @Column(name = "created_date", nullable = false, columnDefinition = "datetime default now()")
-       @PastOrPresent
-       private LocalDateTime createdDate;
-       @Column(name = "updated_date", nullable = false, columnDefinition = "datetime default now()")
-       @PastOrPresent
-       private LocalDateTime updatedDate;
-       @Column(name = "request_status", nullable = false, length = 50)
-       @Size(max = 50)
-       @NotNull
-       @SafeHtml
-       private String requestStatus;
-       @OneToMany(
-               targetEntity = EpUserRolesRequestDet.class,
-               mappedBy = "reqId",
-               cascade = CascadeType.MERGE,
-               fetch = FetchType.LAZY
-       )
-       private Set<EpUserRolesRequestDet> epUserRolesRequestDets;
+    @Id
+    @GeneratedValue(strategy = GenerationType.AUTO)
+    @Column(name = "req_id", length = 11, nullable = false, columnDefinition = "int(11) AUTO_INCREMENT")
+    @Digits(integer = 11, fraction = 0)
+    private Long reqId;
+    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
+    @JoinColumn(name = "user_id", nullable = false, columnDefinition = "bigint")
+    @NotNull
+    @Valid
+    private FnUser userId;
+    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
+    @JoinColumn(name = "app_id", nullable = false, columnDefinition = "bigint")
+    @NotNull
+    @Valid
+    private FnApp appId;
+    @Column(name = "created_date", nullable = false, columnDefinition = "datetime default now()")
+    @PastOrPresent
+    private LocalDateTime createdDate;
+    @Column(name = "updated_date", nullable = false, columnDefinition = "datetime default now()")
+    @PastOrPresent
+    private LocalDateTime updatedDate;
+    @Column(name = "request_status", nullable = false, length = 50)
+    @Size(max = 50)
+    @NotNull
+    @SafeHtml
+    private String requestStatus;
+    @OneToMany(
+        targetEntity = EpUserRolesRequestDet.class,
+        mappedBy = "reqId",
+        cascade = CascadeType.MERGE,
+        fetch = FetchType.LAZY
+    )
+    private Set<EpUserRolesRequestDet> epUserRolesRequestDets;
 
-       public void setEpRequestIdDetail(Set<EpUserRolesRequestDet> epMyLoginsDetail) {
-              this.epUserRolesRequestDets = epMyLoginsDetail;
-       }
+    public void setEpRequestIdDetail(Set<EpUserRolesRequestDet> epMyLoginsDetail) {
+        this.epUserRolesRequestDets = epMyLoginsDetail;
+    }
 }
index 4d2fcae..1af088e 100644 (file)
@@ -89,8 +89,8 @@ CREATE TABLE `ep_user_roles_request_det` (
 })
 
 @Table(name = "ep_user_roles_request_det", indexes = {
-        @Index(name = "fk_user_roles_req_fn_req_id", columnList = "req_id"),
-        @Index(name = "fk_user_roles_req_fn_role_id", columnList = "requested_role_id")
+    @Index(name = "fk_user_roles_req_fn_req_id", columnList = "req_id"),
+    @Index(name = "fk_user_roles_req_fn_role_id", columnList = "requested_role_id")
 })
 @NoArgsConstructor
 @AllArgsConstructor
@@ -99,25 +99,25 @@ CREATE TABLE `ep_user_roles_request_det` (
 @Entity
 public class EpUserRolesRequestDet implements Serializable {
 
-       @Id
-
-  @GeneratedValue(strategy = GenerationType.AUTO)
-       @Column(name = "id", length = 11, nullable = false, columnDefinition = "int(11) AUTO_INCREMENT")
-       @Digits(integer = 11, fraction = 0)
-       private Long id;
-       @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
-       @JoinColumn(name = "req_id", columnDefinition = "int(11) default null")
-       @Valid
-       private EpUserRolesRequest reqId;
-       @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
-       @JoinColumn(name = "requested_role_id", nullable = false, columnDefinition = "bigint")
-       @NotNull
-       @Valid
-       private FnRole requestedRoleId;
-       @Column(name = "request_type", length = 10, nullable = false)
-       @Size(max = 10)
-       @NotNull
-       @SafeHtml
-       private String requestType;
+    @Id
+    @GeneratedValue(strategy = GenerationType.AUTO)
+    @Column(name = "id", length = 11, nullable = false, columnDefinition = "int(11) AUTO_INCREMENT")
+    @Digits(integer = 11, fraction = 0)
+    private Long id;
+    //TODO One to many
+    @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
+    @JoinColumn(name = "req_id", columnDefinition = "int(11) default null")
+    @Valid
+    private EpUserRolesRequest reqId;
+    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
+    @JoinColumn(name = "requested_role_id", nullable = false, columnDefinition = "bigint")
+    @NotNull
+    @Valid
+    private FnRole requestedRoleId;
+    @Column(name = "request_type", length = 10, nullable = false)
+    @Size(max = 10)
+    @NotNull
+    @SafeHtml
+    private String requestType;
 
 }
index 307abeb..beb5bd5 100644 (file)
@@ -108,10 +108,15 @@ CREATE TABLE `fn_app` (
         query = "from FnApp where uebKey = :uebKey"),
     @NamedQuery(
         name = "FnApp.getCentralizedApps",
-        query = "from FnApp where authCentral = 'Y' and open = 'N' and authNamespace is not null"
+        query = "from FnApp where authCentral = 'Y' and open = 'N' and authNamespace is not null"),
+    @NamedQuery(
+        name = "FnApp.retrieveWhereAppName",
+        query = "FROM FnApp WHERE appName = :appName"
     )
 })
 
+//TODO appName as unique index?
+
 @Table(name = "fn_app")
 @NoArgsConstructor
 @AllArgsConstructor
index 6bb13d7..ff03199 100644 (file)
@@ -55,6 +55,8 @@ import javax.persistence.Index;
 import javax.persistence.JoinColumn;
 import javax.persistence.JoinTable;
 import javax.persistence.ManyToMany;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedNativeQuery;
 import javax.persistence.NamedQueries;
 import javax.persistence.NamedQuery;
 import javax.persistence.OneToMany;
@@ -113,6 +115,9 @@ CREATE TABLE `fn_role` (
     @NamedQuery(
         name = "FnRole.retrieveActiveRolesOfApplication",
         query = "from FnRole where activeYn = 'Y' and appId=:appId"),
+    @NamedQuery(
+        name = "FnRole.retrieveActiveRolesWhereAppIdIsNull",
+        query = "from FnRole where activeYn = 'Y' and appId is null"),
     @NamedQuery(
         name = "FnRole.getUserRoleOnUserIdAndAppId",
         query = " FROM"
@@ -137,6 +142,13 @@ CREATE TABLE `fn_role` (
     )
 })
 
+@NamedNativeQuery(
+    name = "FnRole.userAppGlobalRoles",
+    query = "select fr.role_id , fr.role_name ,fr.active_yn, fr.priority, fr.app_id, fr.app_role_id \n"
+        + " from fn_user_role a, fn_role fr, fn_user fu \n"
+        + " where a.role_id in (select b.role_id from ep_app_role_function b where b.role_app_id = 1 and b.app_id =:appId) and a.user_id =fu.user_id and a.role_id = fr.role_id and fr.active_yn='Y' and fu.active_yn='Y' and fu.user_id =:userId\n"
+)
+
 @Table(name = "fn_role")
 @NoArgsConstructor
 @Getter
index d98687a..038fc35 100644 (file)
@@ -75,8 +75,8 @@ CREATE TABLE `fn_role_function` (
 
 @Table(name = "fn_role_function", indexes = {
     @Index(name = "fn_role_function_function_cd", columnList = "function_cd"),
-    @Index(name = "fn_role_function_role_id", columnList = "role"),
-    @Index(name = "fn_role_function_roleId_functionCd", columnList = "role, function_cd", unique = true)})
+    @Index(name = "fn_role_function_role_id", columnList = "role_id"),
+    @Index(name = "fn_role_function_roleId_functionCd", columnList = "role_id, function_cd", unique = true)})
 
 @NoArgsConstructor
 @AllArgsConstructor
@@ -86,7 +86,7 @@ CREATE TABLE `fn_role_function` (
 public class FnRoleFunction extends DomainVo implements Serializable {
 
   @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
-  @JoinColumn(name = "role", nullable = false, columnDefinition = "bigint")
+  @JoinColumn(name = "role_id", nullable = false, columnDefinition = "bigint")
   @Valid
   @NotNull
   private FnRole role;
index 6800b0c..375838e 100644 (file)
@@ -162,7 +162,10 @@ CREATE TABLE `fn_user` (
         query = "FROM FnUser WHERE activeYn = 'Y'"),
     @NamedQuery(
         name = "FnUser.getUsersByOrgIds",
-        query = "FROM FnUser WHERE orgUserId IN :orgIds"
+        query = "FROM FnUser WHERE orgUserId IN :orgIds"),
+    @NamedQuery(
+        name = "FnUSer.findByFirstNameAndLastName",
+        query = "FROM FnUser WHERE firstName = :firstName AND  lastName = :lastName"
     )
 })
 
@@ -243,7 +246,7 @@ public class FnUser extends DomainVo implements UserDetails, Serializable {
   @Column(name = "org_code", length = 30)
   @Size(max = 30)
   @SafeHtml
-  private String org_code;
+  private String orgCode;
   @Column(name = "login_id", length = 25)
   @Size(max = 25)
   @SafeHtml
@@ -296,9 +299,7 @@ public class FnUser extends DomainVo implements UserDetails, Serializable {
   @SafeHtml
   private String locationClli;
   @Column(name = "org_manager_userid", length = 20)
-  @Size(max = 20)
-  @SafeHtml
-  private String orgManagerUserId;
+  private Long orgManagerUserId;
   @Column(name = "company", length = 100)
   @Size(max = 100)
   @SafeHtml
@@ -329,7 +330,7 @@ public class FnUser extends DomainVo implements UserDetails, Serializable {
   @Column(name = "cost_center", length = 25)
   @Size(max = 25)
   @SafeHtml
-  private String cost_center;
+  private String costCenter;
   @Column(name = "fin_loc_code", length = 10)
   @Size(max = 10)
   @SafeHtml
@@ -549,7 +550,7 @@ public class FnUser extends DomainVo implements UserDetails, Serializable {
       @Size(max = 11) @SafeHtml String zipCode,
       @Size(max = 3) @SafeHtml String countryCd,
       @Size(max = 8) @SafeHtml String locationClli,
-      @Size(max = 20) @SafeHtml String orgManagerUserId,
+      Long orgManagerUserId,
       @Size(max = 100) @SafeHtml String company,
       @Size(max = 200) @SafeHtml String departmentName,
       @Size(max = 100) @SafeHtml String jobTitle, FnLuTimezone timezone,
@@ -582,7 +583,7 @@ public class FnUser extends DomainVo implements UserDetails, Serializable {
     this.alertMethodCd = alertMethodCd;
     this.hrid = hrid;
     this.orgUserId = orgUserId;
-    this.org_code = org_code;
+    this.orgCode = org_code;
     this.loginId = loginId;
     this.loginPwd = loginPwd;
     this.lastLoginDate = lastLoginDate;
@@ -606,7 +607,7 @@ public class FnUser extends DomainVo implements UserDetails, Serializable {
     this.department = department;
     this.businessUnit = businessUnit;
     this.businessUnitName = businessUnitName;
-    this.cost_center = cost_center;
+    this.costCenter = cost_center;
     this.finLocCode = finLocCode;
     this.siloStatus = siloStatus;
     this.languageId = languageId;
index e2913e0..581b7ab 100644 (file)
@@ -186,7 +186,7 @@ public class FnUserRole implements Serializable {
   @Digits(integer = 4, fraction = 0)
   private Long priority;
   @ManyToOne(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
-  @JoinColumn(name = "fn_App_Id", columnDefinition = "bigint")
+  @JoinColumn(name = "fn_app_id", columnDefinition = "bigint")
   @Valid
   private FnApp fnAppId;
-}
\ No newline at end of file
+}
index d0c8cee..1b4afaa 100644 (file)
@@ -48,6 +48,7 @@ import lombok.NoArgsConstructor;
 import lombok.Setter;
 import org.hibernate.validator.constraints.SafeHtml;
 import org.onap.portal.domain.db.DomainVo;
+import org.onap.portal.domain.db.fn.FnApp;
 
 @Getter
 @Setter
@@ -59,7 +60,7 @@ public class AppContactUs extends DomainVo {
 
        @JsonBackReference
        @Valid
-       private EPApp app;
+       private FnApp app;
        @SafeHtml
        private String description;
        @SafeHtml
diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPApp.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPApp.java
deleted file mode 100644 (file)
index 5f24436..0000000
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * ONAP Portal
- * ===================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- *
- * Unless otherwise specified, all software contained herein is licensed
- * under the Apache License, Version 2.0 (the "License");
- * you may not use this software except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *             http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * Unless otherwise specified, all documentation contained herein is licensed
- * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
- * you may not use this documentation except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *             https://creativecommons.org/licenses/by/4.0/
- *
- * Unless required by applicable law or agreed to in writing, documentation
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ============LICENSE_END============================================
- *
- *
- */
-
-package org.onap.portal.domain.dto.ecomp;
-
-import javax.persistence.Lob;
-import javax.validation.Valid;
-import lombok.AllArgsConstructor;
-import lombok.EqualsAndHashCode;
-import lombok.Getter;
-import lombok.Setter;
-import org.apache.commons.lang.StringUtils;
-import org.hibernate.validator.constraints.SafeHtml;
-import org.onap.portal.domain.db.DomainVo;
-
-@Getter
-@Setter
-@EqualsAndHashCode(callSuper = false)
-@AllArgsConstructor
-public class EPApp extends DomainVo {
-
-       private static final long serialVersionUID = 1L;
-
-       @SafeHtml
-       private String name;
-       @SafeHtml
-       private String imageUrl;
-       @SafeHtml
-       private String description;
-       @SafeHtml
-       private String notes;
-       @SafeHtml
-       private String url;
-       @SafeHtml
-       private String alternateUrl;
-       @SafeHtml
-       private String appRestEndpoint;
-       @SafeHtml
-       private String mlAppName;
-       @SafeHtml
-       private String mlAppAdminId;
-       private Long motsId;
-       @SafeHtml
-       private String username;
-       @SafeHtml
-       private String appPassword;
-       @Lob
-       private byte[] thumbnail;
-       private Boolean open;
-       private Boolean enabled;
-       @SafeHtml
-       private String uebTopicName;
-       @SafeHtml
-       private String uebKey;
-       @SafeHtml
-       private String uebSecret;
-       private Integer appType;
-       @Valid
-       private AppContactUs contactUs;
-       private Boolean centralAuth;
-       @SafeHtml
-       private String nameSpace;
-
-       public EPApp() {
-              this.name = "";
-              this.mlAppName = "";
-              this.mlAppAdminId = "";
-              this.username = "";
-              this.appPassword = "";
-              this.open = Boolean.FALSE;
-              this.enabled = Boolean.TRUE;
-              this.uebTopicName = "";
-              this.uebKey = "";
-              this.uebSecret = "";
-              this.appType = 1;
-       }
-
-
-       public void setName(String name) {
-              if (StringUtils.isEmpty(name)) {
-                     name = "";
-              }
-              this.name = name;
-       }
-
-       public void setMlAppName(String mlAppName) {
-              if (StringUtils.isEmpty(mlAppName)) {
-                     mlAppName = "";
-              }
-              this.mlAppName = mlAppName;
-       }
-
-       public void setMlAppAdminId(String mlAppAdminId) {
-              if (StringUtils.isEmpty(mlAppAdminId)) {
-                     mlAppAdminId = "";
-              }
-              this.mlAppAdminId = mlAppAdminId;
-       }
-
-
-       public void setAppPassword(String appPassword) {
-              if (StringUtils.isEmpty(appPassword)) {
-                     appPassword = "";
-              }
-              this.appPassword = appPassword;
-       }
-
-       public void setOpen(Boolean open) {
-              if (open == null) {
-                     open = Boolean.FALSE;
-              }
-              this.open = open;
-       }
-
-       public void setEnabled(Boolean enabled) {
-              if (enabled == null) {
-                     enabled = Boolean.TRUE;
-              }
-              this.enabled = enabled;
-       }
-
-       public void setAppType(Integer appType) {
-              if (appType == null) {
-                     appType = 1;
-              }
-              this.appType = appType;
-       }
-
-       public void setRestrictedApp(Boolean restrictedApp) {
-              Integer result = 1;
-              if (restrictedApp) {
-                     result = 2;
-              }
-              this.appType = result;
-       }
-
-       public Boolean isRestrictedApp() {
-              return (this.appType == 2);
-       }
-
-       public int compareTo(Object obj) {
-              Long c1 = getId();
-              Long c2 = ((EPApp) obj).getId();
-
-              return c1.compareTo(c2);
-       }
-
-       public void setUebTopicName(String topicName) {
-              if (StringUtils.isEmpty(topicName)) {
-                     this.uebTopicName = "";
-              }
-              this.uebTopicName = topicName;
-       }
-
-       public void setUebKey(String uebKey) {
-              if (StringUtils.isEmpty(uebKey)) {
-                     this.uebKey = "";
-              }
-              this.uebKey = uebKey;
-       }
-
-
-       public void setUebSecret(String uebSecret) {
-              if (StringUtils.isEmpty(uebSecret)) {
-                     this.uebSecret = "";
-              }
-              this.uebSecret = uebSecret;
-       }
-
-       public void setCentralAuth(Boolean centralAuth) {
-              if (centralAuth == null) {
-                     centralAuth = Boolean.FALSE;
-              }
-              this.centralAuth = centralAuth;
-       }
-
-       public void setNameSpace(String nameSpace) {
-              if (StringUtils.isEmpty(nameSpace)) {
-                     nameSpace = null;
-              }
-              this.nameSpace = nameSpace;
-       }
-
-       @Override
-       public String toString() {
-              return "[" + getId() + ":" + getName() + "]";
-       }
-
-}
diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPRole.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPRole.java
deleted file mode 100644 (file)
index 9ef4ce2..0000000
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * ONAP Portal
- * ===================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- *
- * Unless otherwise specified, all software contained herein is licensed
- * under the Apache License, Version 2.0 (the "License");
- * you may not use this software except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *             http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * Unless otherwise specified, all documentation contained herein is licensed
- * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
- * you may not use this documentation except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *             https://creativecommons.org/licenses/by/4.0/
- *
- * Unless required by applicable law or agreed to in writing, documentation
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ============LICENSE_END============================================
- *
- *
- */
-
-package org.onap.portal.domain.dto.ecomp;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import javax.validation.Valid;
-import lombok.AllArgsConstructor;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import org.hibernate.validator.constraints.SafeHtml;
-import org.onap.portalsdk.core.domain.RoleFunction;
-import org.onap.portal.domain.db.DomainVo;
-
-@Getter
-@Setter
-@NoArgsConstructor
-@AllArgsConstructor
-public class EPRole extends DomainVo {
-
-       private static final long serialVersionUID = 1L;
-       @SafeHtml
-       private String name;
-       private boolean active;
-       private Integer priority;
-       private Long appId;     // used by ONAP only
-       private Long appRoleId; // used by ONAP only
-       private SortedSet<RoleFunction> roleFunctions = new TreeSet<>();
-       @Valid
-       private SortedSet<EPRole> childRoles = new TreeSet<>();
-       @JsonIgnore
-       private SortedSet<EPRole> parentRoles = new TreeSet<>();
-
-
-       public void addRoleFunction(RoleFunction roleFunction) {
-              this.roleFunctions.add(roleFunction);
-       }
-
-       public void addChildRole(EPRole role) {
-              this.childRoles.add(role);
-       }
-
-       public void addParentRole(EPRole role) {
-              this.parentRoles.add(role);
-       }
-
-       public String getEditUrl() {
-              return "/role.htm?role_id=" + getId();
-       }
-
-       public String getToggleActiveImage() {
-              return "/static/fusion/images/" + (isActive() ? "active.png" : "inactive.png");
-       }
-
-       public String getToggleActiveAltText() {
-              return isActive() ? "Click to Deactivate Role" : "Click to Activate Role";
-       }
-
-       public void removeChildRole(Long roleId) {
-
-              for (EPRole childRole : this.childRoles) {
-                     if (childRole.getId().equals(roleId)) {
-                            this.childRoles.remove(childRole);
-                            break;
-                     }
-              }
-       }
-
-       public void removeParentRole(Long roleId) {
-
-              for (EPRole parentRole : this.parentRoles) {
-                     if (parentRole.getId().equals(roleId)) {
-                            this.parentRoles.remove(parentRole);
-                            break;
-                     }
-              }
-       }
-
-       public void removeRoleFunction(String roleFunctionCd) {
-
-              for (RoleFunction roleFunction : this.roleFunctions) {
-                     if (roleFunction.getCode().equals(roleFunctionCd)) {
-                            this.roleFunctions.remove(roleFunction);
-                            break;
-                     }
-              }
-       }
-
-       public int compareTo(Object obj) {
-              EPRole other = (EPRole) obj;
-
-              if (this.appId == null) {
-                     if (other.getAppId() == null) {
-                            return compareByName(other); //equal
-                     } else {
-                            return -1;
-                     }
-              } else if (other.getAppId() == null) {
-                     return 1;
-              } else {
-                     int appIdCompareResult = appId.compareTo(other.getAppId());
-                     return appIdCompareResult == 0 ? compareByName(other) : appIdCompareResult;
-              }
-       }
-
-       private int compareByName(EPRole other) {
-              String c1 = getName();
-              String c2 = other.getName();
-
-              return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
-       }
-
-       @Override
-       public String toString() {
-              return "[Id = " + super.getId() + ", name = " + name + "]";
-       }
-
-}
diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUser.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/ecomp/EPUser.java
deleted file mode 100644 (file)
index d22fb08..0000000
+++ /dev/null
@@ -1,235 +0,0 @@
-/*
- * ============LICENSE_START==========================================
- * ONAP Portal
- * ===================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
- * ===================================================================
- *
- * Unless otherwise specified, all software contained herein is licensed
- * under the Apache License, Version 2.0 (the "License");
- * you may not use this software except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *             http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * Unless otherwise specified, all documentation contained herein is licensed
- * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
- * you may not use this documentation except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *             https://creativecommons.org/licenses/by/4.0/
- *
- * Unless required by applicable law or agreed to in writing, documentation
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * ============LICENSE_END============================================
- *
- *
- */
-
-package org.onap.portal.domain.dto.ecomp;
-
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import javax.validation.Valid;
-import lombok.AllArgsConstructor;
-import lombok.Builder;
-import lombok.Getter;
-import lombok.NoArgsConstructor;
-import lombok.Setter;
-import lombok.ToString;
-import org.hibernate.validator.constraints.SafeHtml;
-import org.onap.portalsdk.core.domain.User;
-import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
-
-@Getter
-@Setter
-@Builder
-@ToString
-@NoArgsConstructor
-@AllArgsConstructor
-public class EPUser extends User {
-
-       private Long orgId;
-       private Long managerId;
-       @SafeHtml
-       private String firstName;
-       @SafeHtml
-       private String middleInitial;
-       @SafeHtml
-       private String lastName;
-       @SafeHtml
-       private String phone;
-       @SafeHtml
-       private String fax;
-       @SafeHtml
-       private String cellular;
-       @SafeHtml
-       private String email;
-       private Long addressId;
-       @SafeHtml
-       private String alertMethodCd;
-       @SafeHtml
-       private String hrid;
-       @SafeHtml
-       private String orgUserId;
-       @SafeHtml
-       private String orgCode;
-       @SafeHtml
-       private String address1;
-       @SafeHtml
-       private String address2;
-       @SafeHtml
-       private String city;
-       @SafeHtml
-       private String state;
-       @SafeHtml
-       private String zipCode;
-       @SafeHtml
-       private String country;
-       @SafeHtml
-       private String orgManagerUserId;
-       @SafeHtml
-       private String locationClli;
-       @SafeHtml
-       private String businessCountryCode;
-       @SafeHtml
-       private String businessCountryName;
-       @SafeHtml
-       private String businessUnit;
-       @SafeHtml
-       private String businessUnitName;
-       @SafeHtml
-       private String department;
-       @SafeHtml
-       private String departmentName;
-       @SafeHtml
-       private String companyCode;
-       @SafeHtml
-       private String company;
-       @SafeHtml
-       private String zipCodeSuffix;
-       @SafeHtml
-       private String jobTitle;
-       @SafeHtml
-       private String commandChain;
-       @SafeHtml
-       private String siloStatus;
-       @SafeHtml
-       private String costCenter;
-       @SafeHtml
-       private String financialLocCode;
-       @SafeHtml
-       private String loginId;
-       @SafeHtml
-       private String loginPwd;
-       private Date lastLoginDate;
-       private boolean active;
-       private boolean internal;
-       private Long selectedProfileId;
-       private Long timeZoneId;
-       private boolean online;
-       @SafeHtml
-       private String chatId;
-       private boolean systemUser;
-       private Integer languageId;
-       private static final long serialVersionUID = 1L;
-       private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EPUser.class);
-       private static final String ECOMP_PORTAL_NAME = "ECOMP";
-       private boolean isGuest = false;
-       @Valid
-       private SortedSet<EPUserApp> userApps = new TreeSet<>();
-       @Valid
-       private SortedSet<EPRole> pseudoRoles = new TreeSet<>();
-
-       @JsonIgnore
-       public String getFullName() {
-              return getFirstName() + " " + getLastName();
-       }
-
-       public int compareTo(Object obj) {
-              EPUser user = (EPUser) obj;
-
-              String c1 = getLastName() + getFirstName() + getMiddleInitial();
-              String c2 = user.getLastName() + user.getFirstName() + user.getMiddleInitial();
-
-              return c1.compareTo(c2);
-       }
-
-
-       public void addAppRoles(EPApp app, SortedSet<EPRole> roles) {
-              if (roles != null) {
-                     // add all
-                     SortedSet<EPUserApp> userApps = new TreeSet<>();
-                     // this.userApps.removeAll(this.userApps);
-                     for (EPRole role : roles) {
-                            EPUserApp userApp = new EPUserApp();
-                            userApp.setUserId(this.id);
-                            userApp.setApp(app);
-                            userApp.setRole(role);
-                            userApps.add(userApp);
-                     }
-                     setUserApps(userApps);
-              } else {
-                     setUserApps(null);
-              }
-
-       }
-
-       public SortedSet<EPRole> getAppEPRoles(EPApp app) {
-
-              logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - app = {}", app.getName());
-
-              SortedSet<EPRole> roles = new TreeSet<>();
-              SortedSet<EPUserApp> userAppRoles = getUserApps();
-
-              logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - userApps = {} ",
-                      userAppRoles.size());
-
-              Iterator<EPUserApp> userAppRolesIterator = userAppRoles.iterator();
-
-              EPUserApp userAppRole;
-              // getting default app
-              while (userAppRolesIterator.hasNext()) {
-                     EPUserApp tempUserApp = userAppRolesIterator.next();
-                     if (tempUserApp.getApp().getId().equals(app.getId())) {
-
-                            logger.debug(EELFLoggerDelegate.debugLogger,
-                                    "In EPUser.getAppEPRoles() - for user {}, found application {}", this.getFullName(),
-                                    app.getName());
-
-                            userAppRole = tempUserApp;
-
-                            EPRole role = userAppRole.getRole();
-                            if (role.isActive()) {
-                                   logger.debug(EELFLoggerDelegate.debugLogger,
-                                           "In EPUser.getAppEPRoles() - Role {} is active - adding for user {} and app {}",
-                                           role.getName(), this.getFullName(), app.getName());
-                                   roles.add(role);
-                            } else {
-                                   logger.debug(EELFLoggerDelegate.debugLogger,
-                                           "In EPUser.getAppEPRoles() - Role {} is NOT active - NOT adding for user {} and app {}",
-                                           role.getName(), this.getFullName(), app.getName());
-                            }
-                     }
-              }
-              logger.debug(EELFLoggerDelegate.debugLogger, "In EPUser.getAppEPRoles() - roles = {}", roles.size());
-
-              return roles;
-       }
-
-}
index 8bf9b72..2448971 100644 (file)
@@ -46,6 +46,8 @@ import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
 import org.onap.portal.domain.db.DomainVo;
+import org.onap.portal.domain.db.fn.FnApp;
+import org.onap.portal.domain.db.fn.FnRole;
 
 @Getter
 @Setter
@@ -57,13 +59,13 @@ public class EPUserApp extends DomainVo implements java.io.Serializable, Compara
        
        private Long userId;
        @Valid
-       private EPApp app;
+       private FnApp app;
        @Valid
-       private EPRole role;
+       private FnRole role;
 
        private Integer priority;
 
-       public EPUserApp(final Long userId, final EPApp app, final EPRole role) {
+       public EPUserApp(final Long userId, final FnApp app, final FnRole role) {
                this.userId = userId;
                this.app = app;
                this.role = role;
index be28e2c..300b870 100644 (file)
@@ -46,6 +46,7 @@ import lombok.EqualsAndHashCode;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
+import org.onap.portal.domain.db.fn.FnRole;
 
 @Getter
 @Setter
@@ -63,7 +64,7 @@ public class ExternalRoleDetails implements Comparable {
 
     @Override
     public int compareTo(Object obj) {
-        EPRole other = (EPRole) obj;
-        return (this.getName() == null || other.getName() == null) ? 1 : getName().equals(other.getName()) ? 0 : 1;
+        FnRole other = (FnRole) obj;
+        return (this.getName() == null || other.getRoleName() == null) ? 1 : getName().equals(other.getRoleName()) ? 0 : 1;
     }
 }
index c107d19..3f88c63 100644 (file)
@@ -84,7 +84,7 @@ public class FnUserDto {
        private String zipCode;
        private String countryCd;
        private String locationClli;
-       private String orgManagerUserId;
+       private Long orgManagerUserId;
        private String company;
        private String departmentName;
        private String jobTitle;
@@ -1,10 +1,8 @@
-/*
+/*-
  * ============LICENSE_START==========================================
  * ONAP Portal
  * ===================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
  * ===================================================================
  *
  * Unless otherwise specified, all software contained herein is licensed
  *
  *
  */
+package org.onap.portal.domain.dto.model;
 
-package org.onap.portal.domain.dto.ecomp;
-
+import java.io.Serializable;
 import lombok.AllArgsConstructor;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
+import org.hibernate.validator.constraints.SafeHtml;
 
 @Getter
 @Setter
 @NoArgsConstructor
 @AllArgsConstructor
-public class PortalRestResponse<T> {
-       
-       private PortalRestStatusEnum status;
-       private String message;
-       private T response;
+public class ExternalSystemRoleApproval implements Serializable {
+
+    @SafeHtml
+    private String roleName;
 
 }
diff --git a/portal-BE/src/main/java/org/onap/portal/domain/dto/model/ExternalSystemUser.java b/portal-BE/src/main/java/org/onap/portal/domain/dto/model/ExternalSystemUser.java
new file mode 100644 (file)
index 0000000..95b440a
--- /dev/null
@@ -0,0 +1,64 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+package org.onap.portal.domain.dto.model;
+
+
+import java.util.List;
+import javax.validation.Valid;
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+import lombok.NoArgsConstructor;
+import lombok.Setter;
+import org.hibernate.validator.constraints.SafeHtml;
+
+@Getter
+@Setter
+@NoArgsConstructor
+@AllArgsConstructor
+public class ExternalSystemUser {
+
+    @SafeHtml
+    private String loginId;
+    @SafeHtml
+    private String applicationName;
+    @SafeHtml
+    private String myloginrequestId;
+    @Valid
+    private List<ExternalSystemRoleApproval> roles;
+
+}
index 20060e4..b27d259 100644 (file)
 package org.onap.portal.domain.dto.transport;
 
 import java.io.Serializable;
+import java.time.LocalDateTime;
 import java.util.Date;
 import lombok.AllArgsConstructor;
+import lombok.Builder;
 import lombok.EqualsAndHashCode;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
@@ -50,6 +52,7 @@ import lombok.Setter;
 
 @Getter
 @Setter
+@Builder
 @EqualsAndHashCode
 @NoArgsConstructor
 @AllArgsConstructor
@@ -57,8 +60,8 @@ public class CentralApp implements Serializable{
 
        private static final long serialVersionUID = -3325965646585871632L;
        private Long id;
-       private Date created;
-       private Date modified;
+       private LocalDateTime created;
+       private LocalDateTime modified;
        private Long createdId;
        private Long modifiedId;
        private Long rowNum;
index a38aa05..37009b8 100644 (file)
@@ -49,6 +49,7 @@ import lombok.Builder;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
+import org.onap.portal.domain.db.ep.EpAppFunction;
 
 @Getter
 @Setter
@@ -68,8 +69,34 @@ public class CentralRole implements Serializable {
        private String name;
        private boolean active;
        private Integer priority;
-       private SortedSet<CentralRoleFunction> roleFunctions = new TreeSet<>();
+       private SortedSet<EpAppFunction> roleFunctions = new TreeSet<>();
        private SortedSet<CentralRole> childRoles;
        private SortedSet<CentralRole> parentRoles;
 
+       public CentralRole(Long id, String name, boolean active, Integer priority,
+               SortedSet<EpAppFunction> roleFunctions) {
+               super();
+               this.id = id;
+               this.name = name;
+               this.active = active;
+               this.priority = priority;
+               this.roleFunctions = roleFunctions;
+       }
+
+       public CentralRole(CentralRoleBuilder centralRoleBuilder) {
+               super();
+               this.id = centralRoleBuilder.id;
+               this.created = centralRoleBuilder.created;
+               this.modified = centralRoleBuilder.modified;
+               this.createdId = centralRoleBuilder.createdId;
+               this.modifiedId = centralRoleBuilder.modifiedId;
+               this.rowNum = centralRoleBuilder.rowNum;
+               this.name = centralRoleBuilder.name;
+               this.active = centralRoleBuilder.active;
+               this.priority = centralRoleBuilder.priority;
+               this.roleFunctions = centralRoleBuilder.roleFunctions;
+               this.childRoles = centralRoleBuilder.childRoles;
+               this.parentRoles = centralRoleBuilder.parentRoles;
+       }
+
 }
index 744dc36..6e1f8df 100644 (file)
@@ -41,6 +41,7 @@
 package org.onap.portal.domain.dto.transport;
 
 import java.io.Serializable;
+import java.time.LocalDateTime;
 import java.util.Date;
 import java.util.Set;
 import lombok.AllArgsConstructor;
@@ -59,8 +60,8 @@ public class CentralUser implements Serializable {
        private static final long serialVersionUID = 7060454665330579923L;
 
        private Long id;
-       private Date created;
-       private Date modified;
+       private LocalDateTime created;
+       private LocalDateTime modified;
        private Long createdId;
        private Long modifiedId;
        private Long rowNum;
@@ -84,7 +85,7 @@ public class CentralUser implements Serializable {
        private String state;
        private String zipCode;
        private String country;
-       private String orgManagerUserId;
+       private Long orgManagerUserId;
        private String locationClli;
        private String businessCountryCode;
        private String businessCountryName;
@@ -102,7 +103,7 @@ public class CentralUser implements Serializable {
        private String financialLocCode;
        private String loginId;
        private String loginPwd;
-       private Date lastLoginDate;
+       private LocalDateTime lastLoginDate;
        private boolean active;
        private boolean internal;
        private Long selectedProfileId;
index 742fe93..02a0423 100644 (file)
@@ -50,6 +50,7 @@ import lombok.EqualsAndHashCode;
 import lombok.Getter;
 import lombok.NoArgsConstructor;
 import lombok.Setter;
+import org.onap.portal.domain.db.DomainVo;
 import org.onap.portal.domain.db.fn.FnRoleFunction;
 
 @Getter
@@ -60,49 +61,49 @@ import org.onap.portal.domain.db.fn.FnRoleFunction;
 @AllArgsConstructor
 public class CentralV2Role implements Serializable, Comparable {
 
-  private static final long serialVersionUID = -4332644961113063714L;
+    private static final long serialVersionUID = -4332644961113063714L;
 
-  private Long id;
-  private LocalDateTime created;
-  private LocalDateTime modified;
-  private Long createdId;
-  private Long modifiedId;
-  private Long rowNum;
-  private String name;
-  private boolean active;
-  private Integer priority;
-  @Builder.Default
-  private SortedSet<FnRoleFunction> roleFunctions = new TreeSet<>();
-  @Builder.Default
-  private SortedSet<CentralV2Role> childRoles = new TreeSet<>();
-  @Builder.Default
-  private SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
+    private Long id;
+    private LocalDateTime created;
+    private LocalDateTime modified;
+    private Long createdId;
+    private Long modifiedId;
+    private Long rowNum;
+    private String name;
+    private boolean active;
+    private Integer priority;
+    @Builder.Default
+    private SortedSet<DomainVo> roleFunctions = new TreeSet<>();
+    @Builder.Default
+    private SortedSet<CentralV2Role> childRoles = new TreeSet<>();
+    @Builder.Default
+    private SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
 
-  public CentralV2Role(Long id, String name) {
-    this.id = id;
-    this.name = name;
-  }
+    public CentralV2Role(Long id, String name) {
+        this.id = id;
+        this.name = name;
+    }
 
-  public void addRoleFunction(FnRoleFunction roleFunction) {
-    this.roleFunctions.add(roleFunction);
-  }
+    public void addRoleFunction(DomainVo roleFunction) {
+        this.roleFunctions.add(roleFunction);
+    }
 
-  public void addChildRole(CentralV2Role role) {
-    this.childRoles.add(role);
-  }
+    public void addChildRole(CentralV2Role role) {
+        this.childRoles.add(role);
+    }
 
-  public void addParentRole(CentralV2Role role) {
-    this.parentRoles.add(role);
-  }
+    public void addParentRole(CentralV2Role role) {
+        this.parentRoles.add(role);
+    }
 
-  @Override
-  public int compareTo(Object obj) {
-    CentralV2Role other = (CentralV2Role) obj;
+    @Override
+    public int compareTo(Object obj) {
+        CentralV2Role other = (CentralV2Role) obj;
 
-    String c1 = getName();
-    String c2 = other.getName();
+        String c1 = getName();
+        String c2 = other.getName();
 
-    return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
-  }
+        return (c1 == null || c2 == null) ? 1 : c1.compareTo(c2);
+    }
 
 }
index 79bcee1..94a9fdf 100644 (file)
@@ -41,6 +41,7 @@
 package org.onap.portal.domain.dto.transport;
 
 import java.io.Serializable;
+import java.time.LocalDateTime;
 import java.util.Date;
 import java.util.Set;
 import lombok.AllArgsConstructor;
@@ -61,8 +62,8 @@ public class CentralV2User implements Serializable {
        private static final long serialVersionUID = -2673289523184880563L;
 
        private Long id;
-       private Date created;
-       private Date modified;
+       private LocalDateTime created;
+       private LocalDateTime modified;
        private Long createdId;
        private Long modifiedId;
        private Long rowNum;
@@ -86,7 +87,7 @@ public class CentralV2User implements Serializable {
     private String state;
     private String zipCode;
     private String country;
-    private String orgManagerUserId;
+    private Long orgManagerUserId;
     private String locationClli;
     private String businessCountryCode;
     private String businessCountryName;
@@ -104,7 +105,7 @@ public class CentralV2User implements Serializable {
     private String financialLocCode;
     private String loginId;
     private String loginPwd;
-    private Date   lastLoginDate;
+    private LocalDateTime   lastLoginDate;
     private boolean active;
     private boolean internal;
     private Long    selectedProfileId;
index 07a1f51..3c9a792 100644 (file)
 package org.onap.portal.domain.dto.transport;
 
 import java.io.Serializable;
+import javax.persistence.ColumnResult;
+import javax.persistence.ConstructorResult;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.SqlResultSetMapping;
 import lombok.AllArgsConstructor;
 import lombok.Builder;
 import lombok.Getter;
@@ -48,6 +52,48 @@ import lombok.NoArgsConstructor;
 import lombok.Setter;
 import lombok.ToString;
 
+@NamedNativeQuery(
+    name = "GlobalRoleWithApplicationRoleFunction.getGlobalRoleForRequestedApp",
+    query = "select distinct "
+          + "    d.role_id as roleId, "
+          + "    d.role_name as roleName, "
+          + "    d.active_yn as active, "
+          + "    d.priority as priority, "
+          + "    c.function_cd as functionCd, "
+          + "    e.function_name as functionName, "
+          + "    c.app_id as appId, "
+          + "    c.role_app_id as roleAppId"
+          + "from fn_user_role a, fn_app b, ep_app_role_function c, fn_role d, ep_app_function e"
+          + "    where b.app_id = c.app_id"
+          + "    and a.app_id = c.role_app_id"
+          + "    and b.enabled = 'Y' "
+          + "    and c.role_id = d.role_id"
+          + "    and d.active_yn='Y'"
+          + "    and e.function_cd = c.function_cd"
+          + "    and c.app_id=:requestedAppId "
+          + "    and c.role_id =:roleId "
+          + "    and e.app_id = c.app_id",
+    resultSetMapping = "GlobalRoleWithApplicationRoleFunction"
+)
+
+@SqlResultSetMapping(
+    name = "GlobalRoleWithApplicationRoleFunction",
+    classes = @ConstructorResult(
+        targetClass = GlobalRoleWithApplicationRoleFunction.class,
+        columns = {
+            @ColumnResult(name = "roleId"),
+            @ColumnResult(name = "roleName"),
+            @ColumnResult(name = "active"),
+            @ColumnResult(name = "priority"),
+            @ColumnResult(name = "functionCd"),
+            @ColumnResult(name = "functionName"),
+            @ColumnResult(name = "appId"),
+            @ColumnResult(name = "roleAppId")
+        }
+    )
+)
+
+
 @Getter
 @Setter
 @ToString
index c68f5a2..b967b2d 100644 (file)
 package org.onap.portal.domain.dto.transport;
 
 import java.io.Serializable;
+import javax.persistence.ColumnResult;
+import javax.persistence.ConstructorResult;
+import javax.persistence.NamedNativeQueries;
+import javax.persistence.NamedNativeQuery;
+import javax.persistence.SqlResultSetMapping;
 import javax.validation.constraints.Digits;
 import javax.validation.constraints.Size;
 import lombok.AllArgsConstructor;
@@ -49,24 +54,63 @@ import lombok.NoArgsConstructor;
 import lombok.Setter;
 import org.hibernate.validator.constraints.SafeHtml;
 
+
+@NamedNativeQuery(
+    name = "PortalAdmin.PortalAdminDTO",
+    query = "SELECT " +
+        "u.id AS userId, " +
+        "u.loginId AS loginId " +
+        "u.firstName AS firstName " +
+        "u.lastName AS lastName " +
+        "FROM " +
+        "FnUser u, " +
+        "FnUserRole ur " +
+        "WHERE u.activeYn = 'true' AND u.user_id = ur.user_id AND ur.role_id= :adminRoleId",
+    resultSetMapping = "PortalAdminDTO")
+@NamedNativeQuery(
+    name = "PortalAdmin.ActivePortalAdminDTO",
+    query = "SELECT " +
+        "u.id AS userId, " +
+        "u.loginId AS loginId " +
+        "u.firstName AS firstName " +
+        "u.lastName AS lastName " +
+        "FROM fn_user u, fn_user_role ur " +
+        "WHERE u.user_id = ur.user_id " +
+        "AND ur.user_id= :userId " +
+        "AND ur.role_id=:SYS_ADMIN_ROLE_ID",
+    resultSetMapping = "PortalAdminDTO")
+
+@SqlResultSetMapping(
+    name = "PortalAdminDTO",
+    classes = @ConstructorResult(
+        targetClass = PortalAdmin.class,
+        columns = {
+            @ColumnResult(name = "userId"),
+            @ColumnResult(name = "loginId"),
+            @ColumnResult(name = "firstName"),
+            @ColumnResult(name = "lastName")
+        }
+    )
+)
+
 @Getter
 @Setter
 @NoArgsConstructor
 @AllArgsConstructor
 public class PortalAdmin implements Serializable {
 
-       private static final long serialVersionUID = 1L;
+    private static final long serialVersionUID = 1L;
 
-       @Digits(integer = 11, fraction = 0)
-       private Long userId;
-       @Size(max = 25)
-       @SafeHtml
-       private String loginId;
-       @Size(max = 50)
-       @SafeHtml
-       private String firstName;
-       @Size(max = 50)
-       @SafeHtml
-       private String lastName;
+    @Digits(integer = 11, fraction = 0)
+    private Long userId;
+    @Size(max = 25)
+    @SafeHtml
+    private String loginId;
+    @Size(max = 50)
+    @SafeHtml
+    private String firstName;
+    @Size(max = 50)
+    @SafeHtml
+    private String lastName;
 
 }
index 0a71850..5e0489a 100644 (file)
@@ -63,7 +63,7 @@ public class FnUserMapper {
                       .alertMethodCd(fnUser.getAlertMethodCd().getAlertMethodCd())
                       .hrid(fnUser.getHrid())
                       .orgUserId(fnUser.getOrgUserId())
-                      .org_code(fnUser.getOrg_code())
+                      .org_code(fnUser.getOrgCode())
                       .loginId(fnUser.getLoginId())
                       .loginPwd(fnUser.getLoginPwd())
                       .lastLoginDate(fnUser.getLastLoginDate())
@@ -86,7 +86,7 @@ public class FnUserMapper {
                       .department(fnUser.getDepartment())
                       .businessUnit(fnUser.getBusinessUnit())
                       .businessUnitName(fnUser.getBusinessUnitName())
-                      .cost_center(fnUser.getCost_center())
+                      .cost_center(fnUser.getCostCenter())
                       .finLocCode(fnUser.getFinLocCode())
                       .siloStatus(fnUser.getSiloStatus())
                       .languageId(fnUser.getLanguageId().getLanguageId())
@@ -110,7 +110,7 @@ public class FnUserMapper {
                       .alertMethodCd(fnUser.getAlertMethodCd())
                       .hrid(fnUser.getHrid())
                       .orgUserId(fnUser.getOrgUserId())
-                      .org_code(fnUser.getOrg_code())
+                      .org_code(fnUser.getOrgCode())
                       .loginId(fnUser.getLoginId())
                       .loginPwd(fnUser.getLoginPwd())
                       .lastLoginDate(fnUser.getLastLoginDate())
@@ -133,7 +133,7 @@ public class FnUserMapper {
                       .department(fnUser.getDepartment())
                       .businessUnit(fnUser.getBusinessUnit())
                       .businessUnitName(fnUser.getBusinessUnitName())
-                      .cost_center(fnUser.getCost_center())
+                      .cost_center(fnUser.getCostCenter())
                       .finLocCode(fnUser.getFinLocCode())
                       .siloStatus(fnUser.getSiloStatus())
                       .languageId(fnUser.getLanguageId())
diff --git a/portal-BE/src/main/java/org/onap/portal/exception/DuplicateRecordException.java b/portal-BE/src/main/java/org/onap/portal/exception/DuplicateRecordException.java
new file mode 100644 (file)
index 0000000..c85278d
--- /dev/null
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+package org.onap.portal.exception;
+
+public class DuplicateRecordException extends Exception {
+
+    private static final long serialVersionUID = 2759542750310357001L;
+
+    public DuplicateRecordException(String msg) {
+        super(msg);
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/exception/ExternalAuthSystemException.java b/portal-BE/src/main/java/org/onap/portal/exception/ExternalAuthSystemException.java
new file mode 100644 (file)
index 0000000..cb354fd
--- /dev/null
@@ -0,0 +1,47 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ * 
+ */
+package org.onap.portal.exception;
+
+public class ExternalAuthSystemException extends Exception {
+
+       private static final long serialVersionUID = -4576754924998287267L;
+
+       public ExternalAuthSystemException(String msg) {
+                  super(msg);
+          } 
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/exception/InactiveApplicationException.java b/portal-BE/src/main/java/org/onap/portal/exception/InactiveApplicationException.java
new file mode 100644 (file)
index 0000000..45179d4
--- /dev/null
@@ -0,0 +1,13 @@
+package org.onap.portal.exception;
+
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Size;
+
+public class InactiveApplicationException extends Exception{
+
+    private static final long serialVersionUID = -4641226040102977745L;
+
+    public InactiveApplicationException(String msg) {
+        super(msg);
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/exception/InvalidRoleException.java b/portal-BE/src/main/java/org/onap/portal/exception/InvalidRoleException.java
new file mode 100644 (file)
index 0000000..15dbfe5
--- /dev/null
@@ -0,0 +1,10 @@
+package org.onap.portal.exception;
+
+public class InvalidRoleException extends Exception{
+
+    private static final long serialVersionUID = -7453145846850741282L;
+
+    public InvalidRoleException(String message){
+        super(message);
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/exception/InvalidUserException.java b/portal-BE/src/main/java/org/onap/portal/exception/InvalidUserException.java
new file mode 100644 (file)
index 0000000..00f09f4
--- /dev/null
@@ -0,0 +1,10 @@
+package org.onap.portal.exception;
+
+public class InvalidUserException extends Exception{
+
+    private static final long serialVersionUID = 273572212076653743L;
+
+    public InvalidUserException(String msg) {
+        super(msg);
+    }
+}
@@ -1,10 +1,8 @@
-/*
+/*-
  * ============LICENSE_START==========================================
  * ONAP Portal
  * ===================================================================
- * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
- * ===================================================================
- * Modifications Copyright (c) 2019 Samsung
+ * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
  * ===================================================================
  *
  * Unless otherwise specified, all software contained herein is licensed
  *
  */
 
-package org.onap.portal.domain.dto.ecomp;
+package org.onap.portal.exception;
+
+public class NonCentralizedAppException extends Exception {
+
+    String appName;
+
+    private static final long serialVersionUID = 1L;
 
-public enum PortalRestStatusEnum{
-       OK("ok"),
-       WARN("WARNING"),
-       ERROR("error");
-       
-       private final String value;
-       PortalRestStatusEnum(String value){
-               this.value = value;
-       }
-       
-       @Override
+    public NonCentralizedAppException(String name) {
+        this.appName = name;
+    }
+
+    @Override
     public String toString() {
-        return value;
+        return appName + " is not Centralized Application";
     }
+
 }
diff --git a/portal-BE/src/main/java/org/onap/portal/restTemplates/AAFTemplate.java b/portal-BE/src/main/java/org/onap/portal/restTemplates/AAFTemplate.java
new file mode 100644 (file)
index 0000000..420307d
--- /dev/null
@@ -0,0 +1,31 @@
+package org.onap.portal.restTemplates;
+
+import org.onap.portal.utils.EPCommonSystemProperties;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
+
+@Component
+public class AAFTemplate {
+
+    private final RestTemplate template = new RestTemplate();
+
+    public ResponseEntity<String> addPortalAdminInAAF(HttpEntity<String> addUserRole){
+        return template.exchange(
+            SystemProperties.getProperty(
+                EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                + "userRole",
+            HttpMethod.POST, addUserRole, String.class);
+    }
+
+    public void deletePortalAdminFromAAF(final String name, final String extRole, final HttpEntity<String> addUserRole){
+        template.exchange(
+            SystemProperties.getProperty(
+                EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                + "userRole/" + name + "/" + extRole,
+            HttpMethod.DELETE, addUserRole, String.class);
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/restTemplates/PortalWMSTemplate.java b/portal-BE/src/main/java/org/onap/portal/restTemplates/PortalWMSTemplate.java
new file mode 100644 (file)
index 0000000..5b99e48
--- /dev/null
@@ -0,0 +1,48 @@
+package org.onap.portal.restTemplates;
+
+import java.util.List;
+import org.onap.portal.domain.dto.ecomp.WidgetCatalog;
+import org.onap.portal.domain.dto.ecomp.WidgetServiceHeaders;
+import org.onap.portal.service.WidgetMService;
+import org.onap.portal.utils.EcompPortalUtils;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.core.ParameterizedTypeReference;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Component;
+import org.springframework.web.client.RestTemplate;
+
+@Component
+public class PortalWMSTemplate {
+
+    private final RestTemplate template = new RestTemplate();
+    private final WidgetMService widgetMService;
+
+    @Autowired
+    public PortalWMSTemplate(WidgetMService widgetMService) {
+        this.widgetMService = widgetMService;
+    }
+
+
+    @SuppressWarnings("rawtypes")
+    public ResponseEntity<Long> proxyToDestinationByWidgetId(long widgetId) throws Exception {
+        return template.exchange(
+            EcompPortalUtils.widgetMsProtocol() + "://"
+                + widgetMService.getServiceLocation("widgets-service",
+                SystemProperties.getProperty("microservices.widget.local.port"))
+                + "/widget/microservices/widgetCatalog/parameters/" + widgetId,
+            HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), Long.class);
+    }
+
+    public ResponseEntity<List<WidgetCatalog>> getWidgets(long serviceId,
+        ParameterizedTypeReference<List<WidgetCatalog>> typeRef)
+        throws Exception {
+        return template.exchange(
+            EcompPortalUtils.widgetMsProtocol() + "://" + widgetMService
+                .getServiceLocation("widgets-service", SystemProperties.getProperty("microservices.widget.local.port"))
+                + "/widget/microservices/widgetCatalog/service/" + serviceId,
+            HttpMethod.GET, new HttpEntity(WidgetServiceHeaders.getInstance()), typeRef);
+    }
+}
index 5b72183..a9d5f6c 100644 (file)
@@ -66,6 +66,7 @@ import org.hibernate.Session;
 import org.hibernate.Transaction;
 import org.json.JSONArray;
 import org.json.JSONObject;
+import org.onap.portal.domain.db.DomainVo;
 import org.onap.portal.domain.db.ep.EpAppFunction;
 import org.onap.portal.domain.db.ep.EpUserRolesRequest;
 import org.onap.portal.domain.db.ep.EpUserRolesRequestDet;
@@ -77,6 +78,8 @@ import org.onap.portal.domain.db.fn.FnRole;
 import org.onap.portal.domain.db.fn.FnRoleFunction;
 import org.onap.portal.domain.db.fn.FnUser;
 import org.onap.portal.domain.db.fn.FnUserRole;
+import org.onap.portal.domain.dto.model.ExternalSystemRoleApproval;
+import org.onap.portal.domain.dto.model.ExternalSystemUser;
 import org.onap.portal.domain.dto.transport.AppNameIdIsAdmin;
 import org.onap.portal.domain.dto.transport.AppWithRolesForUser;
 import org.onap.portal.domain.dto.transport.AppsListWithAdminRole;
@@ -96,15 +99,16 @@ import org.onap.portal.exception.RoleFunctionException;
 import org.onap.portal.exception.SyncUserRolesException;
 import org.onap.portal.logging.format.EPAppMessagesEnum;
 import org.onap.portal.logging.logic.EPLogUtil;
-import org.onap.portal.service.appFunction.EpAppFunctionService;
-import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
-import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
 import org.onap.portal.service.app.FnAppService;
-import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
+import org.onap.portal.service.appFunction.EpAppFunctionService;
 import org.onap.portal.service.menuFunctional.FnMenuFunctionalService;
+import org.onap.portal.service.menuFunctionalRoles.FnMenuFunctionalRolesService;
 import org.onap.portal.service.role.FnRoleService;
-import org.onap.portal.service.userRole.FnUserRoleService;
+import org.onap.portal.service.roleFunction.FnRoleFunctionService;
 import org.onap.portal.service.user.FnUserService;
+import org.onap.portal.service.userRole.FnUserRoleService;
+import org.onap.portal.service.userRolesRequest.EpUserRolesRequestService;
+import org.onap.portal.service.userRolesRequestDet.EpUserRolesRequestDetService;
 import org.onap.portal.utils.EPCommonSystemProperties;
 import org.onap.portal.utils.EPUserUtils;
 import org.onap.portal.utils.EcompPortalUtils;
@@ -142,6 +146,7 @@ public class AdminRolesService {
     private final FnUserService fnUserService;
     private final FnRoleService fnRoleService;
     private final FnAppService fnAppService;
+    private final FnRoleFunctionService fnRoleFunctionService;
     private final FnMenuFunctionalService fnMenuFunctionalService;
     private final FnUserRoleService fnUserRoleService;
     private final EpAppFunctionService epAppFunctionService;
@@ -157,7 +162,7 @@ public class AdminRolesService {
         final EntityManager entityManager,
         final FnUserService fnUserService, FnRoleService fnRoleService,
         FnAppService fnAppService,
-        FnMenuFunctionalService fnMenuFunctionalService,
+        FnRoleFunctionService fnRoleFunctionService, FnMenuFunctionalService fnMenuFunctionalService,
         final FnUserRoleService fnUserRoleService,
         EpAppFunctionService epAppFunctionService,
         EcompUserAppRolesService ecompUserAppRolesService,
@@ -171,6 +176,7 @@ public class AdminRolesService {
         this.fnUserService = fnUserService;
         this.fnRoleService = fnRoleService;
         this.fnAppService = fnAppService;
+        this.fnRoleFunctionService = fnRoleFunctionService;
         this.fnMenuFunctionalService = fnMenuFunctionalService;
         this.fnUserRoleService = fnUserRoleService;
         this.epAppFunctionService = epAppFunctionService;
@@ -279,7 +285,7 @@ public class AdminRolesService {
         return false;
     }
 
-    private boolean isAccountAdminOfApplication(Long userId, FnApp app) {
+    public boolean isAccountAdminOfApplication(Long userId, FnApp app) {
         boolean isApplicationAccountAdmin = false;
         try {
             logger.debug(EELFLoggerDelegate.debugLogger, ADMIN_ACCOUNT, userId);
@@ -540,10 +546,15 @@ public class AdminRolesService {
             Role role = new Role();
             FnRole appRole = getAppRoles.stream()
                 .filter(applicationRole -> epRole.getId().equals(applicationRole.getId())).findAny().orElse(null);
+            List<FnRoleFunction> fnRoleFunctions = new ArrayList<>();
+            for (DomainVo vo : epRole.getRoleFunctions()) {
+                Optional<FnRoleFunction> roleFunction = fnRoleFunctionService.findById(vo.getId());
+                roleFunction.ifPresent(fnRoleFunctions::add);
+            }
             if (appRole != null) {
                 role.setId(appRole.getAppRoleId());
                 role.setRoleName(epRole.getName());
-                role.setFnRoleFunctions(epRole.getRoleFunctions());
+                role.setFnRoleFunctions(new HashSet<>(fnRoleFunctions));
             }
             roles.add(role);
         }
@@ -678,23 +689,6 @@ public class AdminRolesService {
         }
     }
 
-    private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
-        return constructUsersEcompRoles(roleInAppForUserList);
-    }
-
-    private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
-        Set<EcompRole> existingUserRoles = new TreeSet<>();
-        for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
-            if (roleInAppForUser.getIsApplied()) {
-                EcompRole ecompRole = new EcompRole();
-                ecompRole.setId(roleInAppForUser.getRoleId());
-                ecompRole.setName(roleInAppForUser.getRoleName());
-                existingUserRoles.add(ecompRole);
-            }
-        }
-        return existingUserRoles;
-    }
-
     public RolesInAppForUser constructRolesInAppForUserUpdate(String userId, Long appId,
         Set<EcompRole> userRolesInRemoteApp) {
         RolesInAppForUser result;
@@ -1923,4 +1917,308 @@ public class AdminRolesService {
 
         return finalRoleFunctionSet;
     }
+
+    public AppsListWithAdminRole getAppsWithAdminRoleStateForUser(String orgUserId) {
+        AppsListWithAdminRole appsListWithAdminRole = null;
+
+        try {
+            List<FnUser> userList = fnUserService.getUserWithOrgUserId(orgUserId);
+            HashMap<Long, Long> appsUserAdmin = new HashMap<>();
+            if (userList != null && userList.size() > 0) {
+                FnUser user = userList.get(0);
+                List<FnUserRole> userAppList = new ArrayList<>();
+                try {
+                    userAppList = fnUserRoleService.retrieveByUserIdAndRoleId(user.getId(), ACCOUNT_ADMIN_ROLE_ID);
+                } catch (Exception e) {
+                    logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 1 failed", e);
+                    EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+                }
+                for (FnUserRole userApp : userAppList) {
+                    appsUserAdmin.put(userApp.getFnAppId().getId(), userApp.getUserId().getId());
+                }
+            }
+
+            appsListWithAdminRole = new AppsListWithAdminRole();
+            appsListWithAdminRole.setOrgUserId(orgUserId);
+            List<FnApp> appsList = new ArrayList<>();
+            try {
+                appsList = fnAppService.findAll();
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 2 failed", e);
+                EPLogUtil.logEcompError(EPAppMessagesEnum.BeDaoSystemError);
+            }
+            for (FnApp app : appsList) {
+                AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin();
+                appNameIdIsAdmin.setId(app.getId());
+                appNameIdIsAdmin.setAppName(app.getAppName());
+                appNameIdIsAdmin.setIsAdmin(appsUserAdmin.containsKey(app.getId()));
+                appNameIdIsAdmin.setRestrictedApp(app.isRestrictedApp());
+                appsListWithAdminRole.getAppsRoles().add(appNameIdIsAdmin);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getAppsWithAdminRoleStateForUser 3 failed", e);
+        }
+        return appsListWithAdminRole;
+    }
+
+    public ExternalRequestFieldsValidator setExternalRequestUserAppRole(ExternalSystemUser newAppRolesForUser,
+        String reqType) {
+        boolean result = false;
+        boolean externalSystemRequest = true;
+        List<FnUser> userInfo = null;
+        FnUser user = null;
+        List<EpUserRolesRequest> epRequestId = null;
+        String orgUserId = "";
+        String updateStatus = "";
+        String reqMessage = "";
+        FnApp app = null;
+        if (newAppRolesForUser != null && newAppRolesForUser.getLoginId() != null) {
+            orgUserId = newAppRolesForUser.getLoginId().trim();
+        }
+        String appName = newAppRolesForUser.getApplicationName();
+        String logMessage = ("DELETE").equals(reqType) ? "Deleting" : "Assigning/Updating";
+        if (orgUserId.length() > 0) {
+            ObjectMapper mapper = new ObjectMapper();
+            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+            int epRequestIdSize = 0;
+            try {
+                app = fnAppService.getAppDetail(appName);
+                userInfo = checkIfUserExists(orgUserId);
+                reqMessage = "Updated Successfully";
+                if (!reqType.equals("DELETE") && (userInfo.isEmpty())) {
+                    reqMessage = validateNewUser(orgUserId, app);
+                }
+                if (!userInfo.isEmpty()) {
+                    validateExternalRequestFields(app);
+                    user = userInfo.get(0);
+                    epRequestId = epUserRolesRequestService.userAppRolesRequestList(user.getId(), app.getId());
+                    epRequestIdSize = epRequestId.size();
+                }
+                if (!app.getId().equals(PortalConstants.PORTAL_APP_ID) && !app.getAuthCentral()) {
+                    logger.debug(EELFLoggerDelegate.debugLogger,
+                        "setExternalRequestUserAppRole: Starting GET roles for app {}", app.getId());
+                    EcompRole[] appRoles = applicationsRestClientService.get(EcompRole[].class, app.getId(), "/roles");
+                    logger.debug(EELFLoggerDelegate.debugLogger,
+                        "setExternalRequestUserAppRole: Finshed GET roles for app {} and payload {}", app.getId(),
+                        appRoles);
+                    if (appRoles.length > 0) {
+                        syncAppRoles(app.getId(), appRoles);
+                    }
+                }
+                List<RoleInAppForUser> roleInAppForUserList = roleInAppForUserList(newAppRolesForUser.getRoles(),
+                    app.getId(), app.getMlAppName());
+                List<EcompUserAppRoles> userRoleList = null;
+                if (!userInfo.isEmpty()) {
+                    userRoleList = ecompUserAppRolesService.getUserAppExistingRoles(app.getId(), user.getId());
+                }
+                // Check if list contains just account admin role
+                boolean checkIfAdminRoleExists = false;
+                if (reqType.equals("DELETE") && userRoleList != null) {
+                    checkIfAdminRoleExists = userRoleList.stream()
+                        .anyMatch(userRole -> userRole.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
+                } else {
+                    checkIfAdminRoleExists = roleInAppForUserList.stream()
+                        .anyMatch(roleList -> roleList.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
+                }
+                if (app.getAuthCentral()) {
+                    try {
+                        if (!(app.getId().equals(PortalConstants.PORTAL_APP_ID) && reqType.equals("DELETE"))
+                            && ((checkIfAdminRoleExists && roleInAppForUserList.size() > 1)
+                            || (!checkIfAdminRoleExists && roleInAppForUserList.size() >= 1))) {
+                            List<RoleInAppForUser> remoteUserRoles = new ArrayList<>(roleInAppForUserList);
+                            remoteUserRoles.removeIf(role -> {
+                                return (role.getRoleId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID));
+                            });
+                            String orgUserIdNewOrExist = (!userInfo.isEmpty()) ? user.getOrgUserId() : orgUserId;
+                            pushRemoteUser(remoteUserRoles, orgUserIdNewOrExist, app, mapper,
+                                applicationsRestClientService, true);
+                        }
+                    } catch (Exception e) {
+                        reqMessage = e.getMessage();
+                        logger.error(EELFLoggerDelegate.errorLogger,
+                            "setExternalRequestUserAppRole: Failed to added remote user", e);
+                        throw new Exception(reqMessage);
+                    }
+                    Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
+                    RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
+                        userRolesInLocalApp);
+                    List<RoleInAppForUser> roleAppUserList = rolesInAppForUser.getRoles();
+                    Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
+                    if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                        updateUserRolesInExternalSystem(app, rolesInAppForUser.getOrgUserId(), roleAppUserList,
+                            externalSystemRequest, false, rolesGotDeletedByApprover, false);
+                    }
+                    logger.info(EELFLoggerDelegate.debugLogger,
+                        "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
+                        newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
+                    result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,
+                        false, rolesGotDeletedByApprover, false);
+                } else if (!app.getAuthCentral() && app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                    Set<EcompRole> userRolesInLocalApp = postUsersRolesToLocalApp(roleInAppForUserList);
+                    RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
+                        userRolesInLocalApp);
+                    Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
+
+                    result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest, reqType,
+                        false, rolesGotDeletedByApprover, false);
+                } else {
+                    if (!((roleInAppForUserList.size() == 1 || reqType.equals("DELETE")) && checkIfAdminRoleExists)) {
+                        FnUser remoteAppUser = null;
+                        remoteAppUser = checkIfRemoteUserExits(orgUserId, app, applicationsRestClientService);
+                        if (remoteAppUser == null) {
+                            addRemoteUser(roleInAppForUserList, orgUserId, app, mapper,
+                                applicationsRestClientService);
+                            reqMessage = "Saved Successfully";
+                        }
+                        Set<EcompRole> userRolesInRemoteApp = postUsersRolesToRemoteApp(roleInAppForUserList, mapper,
+                            applicationsRestClientService, app.getId(), orgUserId);
+                        RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
+                            userRolesInRemoteApp);
+                        logger.info(EELFLoggerDelegate.debugLogger,
+                            "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}", logMessage,
+                            newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
+                        Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
+                        result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
+                            reqType, false, rolesGotDeletedByApprover, false);
+                    } else {
+                        if (!(reqType.equals("DELETE")) && userInfo.isEmpty()) {
+                            reqMessage = "Saved Successfully";
+                        }
+                        Set<EcompRole> userRolesInRemoteApp = constructUsersEcompRoles(roleInAppForUserList);
+                        RolesInAppForUser rolesInAppForUser = constructRolesInAppForUserUpdate(orgUserId, app.getId(),
+                            userRolesInRemoteApp);
+                        logger.info(EELFLoggerDelegate.debugLogger,
+                            "setExternalRequestUserAppRole: {} user app roles: for app {}, user {}",
+                            logMessage, newAppRolesForUser.getApplicationName(), newAppRolesForUser.getLoginId());
+                        Set<EcompRole> rolesGotDeletedByApprover = new TreeSet<>();
+                        result = applyChangesInUserRolesForAppToEcompDB(rolesInAppForUser, externalSystemRequest,
+                            reqType, false, rolesGotDeletedByApprover, false);
+                    }
+                    if (!result) {
+                        reqMessage = "Failed to save the user app role(s)";
+                    }
+                    if (epRequestIdSize > 0 && !userInfo.isEmpty()) {
+                        updateStatus = "C";
+                        applyChangesToAppRolesRequest(user.getId(), updateStatus, epRequestId.get(0));
+                    }
+                }
+            } catch (Exception e) {
+                String message = String.format(
+                    "setExternalRequestUserAppRole: Failed to create user or update user roles for User %s, AppId %s",
+                    orgUserId, appName);
+                logger.error(EELFLoggerDelegate.errorLogger, message, e);
+                result = false;
+                reqMessage = e.getMessage();
+                if (epRequestIdSize > 0 && userInfo != null && !userInfo.isEmpty()) {
+                    updateStatus = "F";
+                    applyChangesToAppRolesRequest(user.getId(),
+                        updateStatus, epRequestId.get(0));
+                }
+            }
+        }
+        return new ExternalRequestFieldsValidator(result, reqMessage);
+    }
+
+    private Set<EcompRole> postUsersRolesToLocalApp(List<RoleInAppForUser> roleInAppForUserList) {
+        return constructUsersEcompRoles(roleInAppForUserList);
+    }
+
+    private Set<EcompRole> constructUsersEcompRoles(List<RoleInAppForUser> roleInAppForUserList) {
+        Set<EcompRole> existingUserRoles = new TreeSet<>();
+        for (RoleInAppForUser roleInAppForUser : roleInAppForUserList) {
+            if (roleInAppForUser.getIsApplied()) {
+                EcompRole ecompRole = new EcompRole();
+                ecompRole.setId(roleInAppForUser.getRoleId());
+                ecompRole.setName(roleInAppForUser.getRoleName());
+                existingUserRoles.add(ecompRole);
+            }
+        }
+        return existingUserRoles;
+    }
+
+    private List<RoleInAppForUser> roleInAppForUserList(List<ExternalSystemRoleApproval> roleInAppForUserList,
+        Long appId, String appName) throws Exception {
+        List<RoleInAppForUser> existingUserRoles = new ArrayList<>();
+        List<FnRole> existingAppRole;
+        for (ExternalSystemRoleApproval roleInAppForUser : roleInAppForUserList) {
+            RoleInAppForUser ecompRole = new RoleInAppForUser();
+            existingAppRole = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(roleInAppForUser.getRoleName(), appId);
+            if (existingAppRole.isEmpty()) {
+                logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
+                    roleInAppForUserList);
+                throw new Exception("'" + roleInAppForUser.getRoleName() + "'" + " role does not exist for " + appName
+                    + " application");
+            }
+            if (!existingAppRole.get(0).getActiveYn()) {
+                logger.error(EELFLoggerDelegate.errorLogger, "roleInAppForUserList failed for the roles {}",
+                    roleInAppForUserList);
+                throw new Exception(
+                    roleInAppForUser.getRoleName() + " role is unavailable for " + appName + " application");
+            } else {
+
+                List<FnRole> roleInfo = externalAccessRolesService
+                    .getPortalAppRoleInfo(PortalConstants.ACCOUNT_ADMIN_ROLE_ID);
+                FnRole adminRole = new FnRole();
+                if (roleInfo.size() > 0) {
+                    adminRole = roleInfo.get(0);
+                    logger.debug(EELFLoggerDelegate.debugLogger, "Admin RoleName form DB: " + adminRole.getRoleName());
+                }
+                ecompRole.setRoleId(
+                    (appId == 1 || roleInAppForUser.getRoleName().equals(adminRole.getRoleName())) ? existingAppRole
+                        .get(0)
+                        .getId() : existingAppRole.get(0).getAppRoleId());
+                ecompRole.setRoleName(roleInAppForUser.getRoleName());
+                ecompRole.setIsApplied(true);
+                existingUserRoles.add(ecompRole);
+            }
+        }
+        return existingUserRoles;
+    }
+
+    private void validateExternalRequestFields(FnApp app) throws Exception {
+        if (app == null) {
+            throw new Exception("Application does not exist");
+        } else if (!app.getEnabled() && !app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+            throw new Exception(app.getMlAppName() + " application is unavailable");
+        }
+    }
+
+    private String validateNewUser(String orgUserId, FnApp app) throws Exception {
+        FnUser epUser = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
+        if (epUser == null) {
+            throw new Exception("User does not exist");
+        } else if (!epUser.getOrgUserId().equals(orgUserId)) {
+            throw new Exception("User does not exist");
+        } else if (app == null) {
+            throw new Exception("Application does not exist");
+        }
+        return "Saved Successfully";
+    }
+
+    private void applyChangesToAppRolesRequest(final Long userId, final String updateStatus,
+        final EpUserRolesRequest epUserAppRolesRequest) {
+        try {
+            epUserAppRolesRequest.setUpdatedDate(LocalDateTime.now());
+            epUserAppRolesRequest.setRequestStatus(updateStatus);
+            epUserAppRolesRequest.setUserId(fnUserService.getUser(userId).get());
+            epUserRolesRequestService.saveOne(epUserAppRolesRequest);
+            List<EpUserRolesRequestDet> epUserAppRolessDetailList = epUserRolesRequestDetService
+                .appRolesRequestDetailList(epUserAppRolesRequest.getReqId());
+            if (epUserAppRolessDetailList.size() > 0) {
+                for (EpUserRolesRequestDet epRequestUpdateData : epUserAppRolessDetailList) {
+                    epRequestUpdateData.setRequestType(updateStatus);
+                    epRequestUpdateData.setReqId(epUserAppRolesRequest);
+                    epRequestUpdateData.setReqId(epUserAppRolesRequest);
+                    epUserRolesRequestDetService.saveOne(epRequestUpdateData);
+                }
+            }
+            logger.debug(EELFLoggerDelegate.debugLogger, "The request is set to complete");
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "applyChangesToAppRolesRequest failed", e);
+        }
+    }
+
+    public List<FnRole> getRolesByApp(final Long appId) {
+        return fnRoleService.retrieveActiveRolesOfApplication(appId);
+    }
 }
diff --git a/portal-BE/src/main/java/org/onap/portal/service/BulkUploadUserRolesService.java b/portal-BE/src/main/java/org/onap/portal/service/BulkUploadUserRolesService.java
new file mode 100644 (file)
index 0000000..0b8dac7
--- /dev/null
@@ -0,0 +1,72 @@
+package org.onap.portal.service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import javax.persistence.EntityManager;
+import javax.transaction.Transactional;
+import org.onap.portal.domain.dto.transport.BulkUploadRoleFunction;
+import org.onap.portal.domain.dto.transport.BulkUploadUserRoles;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Service
+@Transactional
+class BulkUploadUserRolesService {
+
+    private static final String getBulkUsersForSingleRole = "select fr.role_name as roleName, fu.org_user_id as orgUserId, fa.auth_namespace as appNameSpace from fn_user_role fur "
+        + "left outer join fn_role fr on fr.role_id = fur.role_id "
+        + "left outer join fn_app fa on fa.app_id = fur.app_id "
+        + "left outer join fn_user fu on fu.user_id = fur.user_id "
+        + "where fa.ueb_key =:uebKey and fr.role_id =:roleId";
+
+    private static final String uploadAllRoleFunctions = "select fr.function_cd, fn.function_name from fn_role_function fr "
+        + "left outer join fn_function fn on fr.function_cd = fn.function_cd "
+        + "where role_id =:roleId";
+    
+    private static final String getBulkUserRoles = "select fr.role_name, fu.org_user_id, fa.auth_namespace from fn_user_role fur "
+        + "left outer join fn_role fr on fr.role_id = fur.role_id "
+        + "left outer join fn_app fa on fa.app_id = fur.app_id "
+        + "left outer join fn_user fu on fu.user_id = fur.user_id where fa.ueb_key =:uebKey";
+
+    private static final String uploadPartnerRoleFunctions = "select distinct eprf.function_cd, epfn.function_name "
+        + "from ep_app_role_function eprf "
+        + "left outer join ep_app_function epfn on eprf.function_cd = epfn.function_cd "
+        + "where eprf.role_id =:roleId";
+
+    private final EntityManager entityManager;
+
+    @Autowired
+    public BulkUploadUserRolesService(EntityManager entityManager) {
+        this.entityManager = entityManager;
+    }
+
+    List<BulkUploadUserRoles>  getBulkUsersForSingleRole(final String uebKey, final Long roleId){
+        return Optional.of(entityManager
+            .createQuery(getBulkUsersForSingleRole)
+            .setParameter("uebKey", uebKey)
+            .setParameter("roleId", roleId)
+            .getResultList()).orElse(new ArrayList());
+    }
+
+    List<BulkUploadRoleFunction> uploadAllRoleFunctions(final Long roleId){
+        return Optional.of(entityManager
+            .createQuery(uploadAllRoleFunctions)
+            .setParameter("roleId", roleId)
+            .getResultList()).orElse(new ArrayList());
+    }
+
+    public List<BulkUploadUserRoles> getBulkUserRoles(String uebKey) {
+        return Optional.of(entityManager
+            .createQuery(getBulkUserRoles)
+            .setParameter("uebKey", uebKey)
+            .getResultList()).orElse(new ArrayList());
+    }
+
+    public List<BulkUploadRoleFunction> uploadPartnerRoleFunctions(Long roleId) {
+        return Optional.of(entityManager
+            .createQuery(uploadPartnerRoleFunctions)
+            .setParameter("roleId", roleId)
+            .getResultList()).orElse(new ArrayList());
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/service/CentralizedAppService.java b/portal-BE/src/main/java/org/onap/portal/service/CentralizedAppService.java
new file mode 100644 (file)
index 0000000..d4f3e0d
--- /dev/null
@@ -0,0 +1,29 @@
+package org.onap.portal.service;
+
+import java.util.List;
+import javax.persistence.EntityManager;
+import org.onap.portal.domain.dto.ecomp.CentralizedApp;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional
+public class CentralizedAppService {
+
+    private final EntityManager entityManager;
+
+    @Autowired
+    public CentralizedAppService(EntityManager entityManager) {
+        this.entityManager = entityManager;
+    }
+
+    public List<CentralizedApp> getCentralizedAppsOfUser(final String userId) {
+        String query = "select distinct fa.app_id, fa.app_name "
+            + "from  fn_role fr, fn_user_role fur, fn_app fa, fn_user fu "
+            + "Where  fu.user_id =  fur.user_id and fur.role_id = fr.role_id and fa.app_id = fur.app_id "
+            + "and fu.org_user_id = :userId and (fur.role_id = 999 or fur.role_id = 1) and fr.active_yn='Y' and ((fa.enabled = 'Y' and fa.auth_central='Y') or fa.app_id =1)";
+
+        return entityManager.createQuery(query).getResultList();
+    }
+}
index b9f161f..fbe02af 100644 (file)
 
 package org.onap.portal.service;
 
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.DeserializationFeature;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
 import java.util.stream.Collectors;
+import javax.management.InvalidApplicationException;
 import javax.persistence.EntityManager;
+import javax.persistence.Query;
 import javax.persistence.Tuple;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.onap.portal.domain.db.DomainVo;
 import org.onap.portal.domain.db.ep.EpAppFunction;
+import org.onap.portal.domain.db.ep.EpAppRoleFunction;
 import org.onap.portal.domain.db.fn.FnApp;
 import org.onap.portal.domain.db.fn.FnFunction;
 import org.onap.portal.domain.db.fn.FnRole;
 import org.onap.portal.domain.db.fn.FnRoleFunction;
+import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.domain.db.fn.FnUserRole;
+import org.onap.portal.domain.dto.ecomp.EPAppRoleFunction;
+import org.onap.portal.domain.dto.ecomp.EPUserAppRolesRequest;
+import org.onap.portal.domain.dto.ecomp.ExternalRoleDetails;
+import org.onap.portal.domain.dto.ecomp.UploadRoleFunctionExtSystem;
+import org.onap.portal.domain.dto.model.ExternalSystemUser;
+import org.onap.portal.domain.dto.transport.BulkUploadRoleFunction;
+import org.onap.portal.domain.dto.transport.BulkUploadUserRoles;
+import org.onap.portal.domain.dto.transport.CentralApp;
+import org.onap.portal.domain.dto.transport.CentralRole;
+import org.onap.portal.domain.dto.transport.CentralRoleFunction;
+import org.onap.portal.domain.dto.transport.CentralUser;
+import org.onap.portal.domain.dto.transport.CentralUserApp;
 import org.onap.portal.domain.dto.transport.CentralV2Role;
+import org.onap.portal.domain.dto.transport.CentralV2User;
+import org.onap.portal.domain.dto.transport.CentralV2UserApp;
+import org.onap.portal.domain.dto.transport.EPUserAppCurrentRoles;
+import org.onap.portal.domain.dto.transport.EcompUserRoles;
+import org.onap.portal.domain.dto.transport.ExternalAccessPerms;
+import org.onap.portal.domain.dto.transport.ExternalAccessPermsDetail;
+import org.onap.portal.domain.dto.transport.ExternalAccessRole;
+import org.onap.portal.domain.dto.transport.ExternalAccessRolePerms;
+import org.onap.portal.domain.dto.transport.ExternalAccessUser;
+import org.onap.portal.domain.dto.transport.ExternalRequestFieldsValidator;
 import org.onap.portal.domain.dto.transport.GlobalRoleWithApplicationRoleFunction;
+import org.onap.portal.domain.dto.transport.LocalRole;
+import org.onap.portal.exception.DeleteDomainObjectFailedException;
+import org.onap.portal.exception.ExternalAuthSystemException;
+import org.onap.portal.exception.InactiveApplicationException;
+import org.onap.portal.exception.InvalidUserException;
 import org.onap.portal.exception.RoleFunctionException;
 import org.onap.portal.logging.logic.EPLogUtil;
-import org.onap.portal.service.appFunction.EpAppFunctionService;
 import org.onap.portal.service.app.FnAppService;
+import org.onap.portal.service.appFunction.EpAppFunctionService;
+import org.onap.portal.service.appRoleFunction.EpAppRoleFunctionService;
 import org.onap.portal.service.role.FnRoleService;
+import org.onap.portal.service.roleFunction.FnRoleFunctionService;
+import org.onap.portal.service.user.FnUserService;
 import org.onap.portal.utils.EPCommonSystemProperties;
 import org.onap.portal.utils.EPUserUtils;
 import org.onap.portal.utils.EcompPortalUtils;
 import org.onap.portal.utils.PortalConstants;
+import org.onap.portalsdk.core.domain.Role;
+import org.onap.portalsdk.core.domain.RoleFunction;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.restful.domain.EcompRole;
+import org.onap.portalsdk.core.restful.domain.EcompRoleFunction;
+import org.onap.portalsdk.core.restful.domain.EcompUser;
 import org.onap.portalsdk.core.util.SystemProperties;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
 import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
 import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Propagation;
+import org.springframework.transaction.annotation.Transactional;
+import org.springframework.web.client.HttpClientErrorException;
 import org.springframework.web.client.RestTemplate;
 
+@SuppressWarnings("unchecked")
 @Service
 public class ExternalAccessRolesService {
 
-  private static final String APP_ROLE_NAME_PARAM = "appRoleName";
-  private static final String GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM = "getRoletoUpdateInExternalAuthSystem";
-  private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
-  private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
-  private static final String FUNCTION_CODE_PARAMS = "functionCode";
-  private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
-  private static final String OWNER = ".owner";
-  private static final String ADMIN = ".admin";
-  private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
-  private static final String FUNCTION_PIPE = "|";
-  private static final String EXTERNAL_AUTH_PERMS = "perms";
-  private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
-  private static final String IS_EMPTY_JSON_STRING = "{}";
-  private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
-  private static final String APP_ID = "appId";
-  private static final String ROLE_NAME = "name";
-  private static final String APP_ID_EQUALS = " app_id = ";
-
-  private static final String GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS = "select"
-      + "  distinct d.roleId as roleId,"
-      + "  d.roleName as roleName,"
-      + "  d.activeYn as active,"
-      + "  d.priority as priority,"
-      + "  c.epAppFunction.functionCd as functionCd,"
-      + "  e.functionName as functionName,"
-      + "  c.epAppFunction.appId as appId,"
-      + "  c.roleAppId as roleAppId"
-      + " from"
-      + "  FnUserRole a,"
-      + "  FnApp b,"
-      + "  EpAppRoleFunction c,"
-      + "  FnRole d,"
-      + "  EpAppFunction e"
-      + " where"
-      + "  b.appId = c.appId.appId"
-      + "  and a.appId = c.roleAppId"
-      + "  and b.enabled = 'Y'"
-      + "  and c.fnRole.roleId = d.roleId"
-      + "  and d.activeYn = 'Y'"
-      + "  and e.functionCd = c.epAppFunction.functionCd"
-      + "  and c.appId.appId = :appId"
-      + "  and e.appId.appId = c.appId.appId";
-
-  private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesService.class);
-  private final RestTemplate template = new RestTemplate();
-
-  private final FnRoleService fnRoleService;
-  private final FnAppService fnAppService;
-  private final EntityManager entityManager;
-  private final EpAppFunctionService epAppFunctionService;
-
-  @Autowired
-  public ExternalAccessRolesService(FnRoleService fnRoleService,
-      FnAppService fnAppService, EntityManager entityManager,
-      EpAppFunctionService epAppFunctionService) {
-    this.fnRoleService = fnRoleService;
-    this.fnAppService = fnAppService;
-    this.entityManager = entityManager;
-    this.epAppFunctionService = epAppFunctionService;
-  }
-
-  String getFunctionCodeType(String roleFuncItem) {
-    String type = null;
-    if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
-        || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
-      type = "menu";
-    } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
-        || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
-      type = "url";
-    } else if (roleFuncItem.contains(FUNCTION_PIPE)
-        && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
-      type = EcompPortalUtils.getFunctionType(roleFuncItem);
-    }
-    return type;
-  }
-
-  private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
-    return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
-  }
-
-  private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
-    return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
-  }
-
-  private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
-    return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
-  }
-
-  List<FnRole> getPortalAppRoleInfo(Long roleId) {
-    return fnRoleService.retrieveAppRoleByRoleIdWhereAppIdIsNull(roleId);
-  }
-
-  ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
-    logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
-    ResponseEntity<String> getResponse = template
-        .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
-            + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
-    if (getResponse.getStatusCode().value() == 200) {
-      logger.debug(EELFLoggerDelegate.debugLogger,
-          "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
-          getResponse.getBody());
-    } else {
-      logger.error(EELFLoggerDelegate.errorLogger,
-          "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
-          getResponse.getBody());
-      EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
-    }
-    return getResponse;
-  }
-
-  Map<String, FnRole> getAppRoleNamesWithUnderscoreMap(FnApp app) {
-    final Map<String, FnRole> currentRolesInDB = new HashMap<>();
-    List<FnRole> getCurrentRoleList = null;
-    final Map<String, Long> appParams = new HashMap<>();
-    if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
-      getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
-    } else {
-      appParams.put("appId", app.getId());
-      getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(app.getId());
-    }
-    for (FnRole role : getCurrentRoleList) {
-      currentRolesInDB.put(role.getRoleName()
-          .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
-    }
-    return currentRolesInDB;
-  }
-
-  List<CentralV2Role> createCentralRoleObject(List<FnApp> app, List<FnRole> roleInfo,
-      List<CentralV2Role> roleList) throws RoleFunctionException {
-    for (FnRole role : roleInfo) {
-      List<EpAppFunction> cenRoleFuncList = epAppFunctionService
-          .getAppRoleFunctionList(role.getId(), app.get(0).getId());
-      SortedSet<FnRoleFunction> roleFunctionSet = new TreeSet<>();
-      for (EpAppFunction roleFunc : cenRoleFuncList) {
-        String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
-        functionCode = EPUserUtils.decodeFunctionCode(functionCode);
-        String type = getFunctionCodeType(roleFunc.getFunctionCd());
-        String action = getFunctionCodeAction(roleFunc.getFunctionCd());
-        FnRoleFunction cenRoleFunc = new FnRoleFunction(role, FnFunction.builder().code(functionCode).name(roleFunc.getFunctionName()).type(type).action(action).build());
-      }
-      SortedSet<CentralV2Role> childRoles = new TreeSet<>();
-      SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
-      CentralV2Role cenRole;
-      if (role.getAppRoleId() == null) {
-        cenRole = CentralV2Role.builder().id(role.getId()).created(role.getCreated())
-            .modified(role.getModified())
-.rowNum(role.getRowNum()).name(role.getRoleName())
-            .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
-            .childRoles(childRoles).parentRoles(parentRoles).build();
-      } else {
-        cenRole = CentralV2Role.builder().id(role.getAppRoleId())
-            .created(role.getCreated()).modified(role.getModified())
-.rowNum(role.getRowNum()).name(role.getRoleName())
-            .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
-            .childRoles(childRoles).parentRoles(parentRoles).build();
-      }
-      roleList.add(cenRole);
-    }
-    return roleList;
-  }
-
-  String getFunctionCodeAction(String roleFuncItem) {
-    return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
-  }
-
-  List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
-    logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
-    List<CentralV2Role> roleList = new ArrayList<>();
-    try {
-      List<FnApp> app = fnAppService.getByUebKey(uebkey);
-      List<FnRole> appRolesList = fnRoleService.getAppRoles(app.get(0).getId());
-      roleList = createCentralRoleObject(app, appRolesList, roleList);
-      if (!Objects.equals(app.get(0).getId(), PortalConstants.PORTAL_APP_ID)) {
-        List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
-        List<FnRole> globalRolesList = fnRoleService.getGlobalRolesOfPortal();
-        List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
-        if (!globalRolesList.isEmpty()) {
-          for (FnRole eprole : globalRolesList) {
-            CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
-            portalsGlobalRolesFinlaList.add(cenRole);
-          }
-          roleList.addAll(globalRoleList);
-          for (CentralV2Role role : portalsGlobalRolesFinlaList) {
-            CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
-                .orElse(null);
-            if (result == null) {
-              roleList.add(role);
-            }
-          }
+    private static final String APP_ROLE_NAME_PARAM = "appRoleName";
+    private static final String GET_PORTAL_APP_ROLES_QUERY = "getPortalAppRoles";
+    private static final String GET_ROLE_FUNCTION_QUERY = "getRoleFunction";
+    private static final String FUNCTION_CODE_PARAMS = "functionCode";
+    private static final String AND_FUNCTION_CD_EQUALS = " and function_cd = '";
+    private static final String OWNER = ".owner";
+    private static final String ADMIN = ".admin";
+    private static final String ACCOUNT_ADMINISTRATOR = ".Account_Administrator";
+    private static final String FUNCTION_PIPE = "|";
+    private static final String EXTERNAL_AUTH_PERMS = "perms";
+    private static final String EXTERNAL_AUTH_ROLE_DESCRIPTION = "description";
+    private static final String IS_EMPTY_JSON_STRING = "{}";
+    private static final String CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE = "Connecting to External Auth system";
+    private static final String APP_ID = "appId";
+    private static final String ROLE_NAME = "name";
+    private static final String APP_ID_EQUALS = " app_id = ";
+
+    private static final String GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS = "select"
+        + "  distinct d.roleId as roleId,"
+        + "  d.roleName as roleName,"
+        + "  d.activeYn as active,"
+        + "  d.priority as priority,"
+        + "  c.epAppFunction.functionCd as functionCd,"
+        + "  e.functionName as functionName,"
+        + "  c.epAppFunction.appId as appId,"
+        + "  c.roleAppId as roleAppId"
+        + " from"
+        + "  FnUserRole a,"
+        + "  FnApp b,"
+        + "  EpAppRoleFunction c,"
+        + "  FnRole d,"
+        + "  EpAppFunction e"
+        + " where"
+        + "  b.appId = c.appId.appId"
+        + "  and a.appId = c.roleAppId"
+        + "  and b.enabled = 'Y'"
+        + "  and c.fnRole.roleId = d.roleId"
+        + "  and d.activeYn = 'Y'"
+        + "  and e.functionCd = c.epAppFunction.functionCd"
+        + "  and c.appId.appId = :appId"
+        + "  and e.appId.appId = c.appId.appId";
+
+    private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ExternalAccessRolesService.class);
+    private final RestTemplate template = new RestTemplate();
+
+    private final FnUserService fnUserService;
+    private final FnRoleService fnRoleService;
+    private final FnAppService fnAppService;
+    private final EntityManager entityManager;
+    private final FnRoleFunctionService fnRoleFunctionService;
+    private final EpAppFunctionService epAppFunctionService;
+    private final EpAppRoleFunctionService epAppRoleFunctionService;
+    private final LocalRoleService localRoleService;
+    private final BulkUploadUserRolesService bulkUploadUserRolesService;
+
+    @Autowired
+    public ExternalAccessRolesService(
+        final FnUserService fnUserService,
+        final FnRoleService fnRoleService,
+        final FnAppService fnAppService, EntityManager entityManager,
+        FnRoleFunctionService fnRoleFunctionService,
+        final EpAppFunctionService epAppFunctionService,
+        final EpAppRoleFunctionService epAppRoleFunctionService,
+        final LocalRoleService localRoleService,
+        BulkUploadUserRolesService bulkUploadUserRolesService) {
+        this.fnUserService = fnUserService;
+        this.fnRoleService = fnRoleService;
+        this.fnAppService = fnAppService;
+        this.entityManager = entityManager;
+        this.fnRoleFunctionService = fnRoleFunctionService;
+        this.epAppFunctionService = epAppFunctionService;
+        this.epAppRoleFunctionService = epAppRoleFunctionService;
+        this.localRoleService = localRoleService;
+        this.bulkUploadUserRolesService = bulkUploadUserRolesService;
+    }
+
+    public String getFunctionCodeType(String roleFuncItem) {
+        String type = null;
+        if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))
+            || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) {
+            type = "menu";
+        } else if (checkIfCodeHasNoPipesAndHasTypeUrl(roleFuncItem) || checkIfCodeHasPipesAndHasTypeUrl(roleFuncItem)
+            || checkIfCodeHasNoPipesAndHasNoTypeUrl(roleFuncItem)) {
+            type = "url";
+        } else if (roleFuncItem.contains(FUNCTION_PIPE)
+            && (!roleFuncItem.contains("menu") || roleFuncItem.contains("url"))) {
+            type = EcompPortalUtils.getFunctionType(roleFuncItem);
+        }
+        return type;
+    }
+
+    private boolean checkIfCodeHasNoPipesAndHasTypeUrl(String roleFuncItem) {
+        return !roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
+    }
+
+    private boolean checkIfCodeHasPipesAndHasTypeUrl(String roleFuncItem) {
+        return roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("url");
+    }
+
+    private boolean checkIfCodeHasNoPipesAndHasNoTypeUrl(String roleFuncItem) {
+        return !roleFuncItem.contains(FUNCTION_PIPE) && !roleFuncItem.contains("url");
+    }
+
+    List<FnRole> getPortalAppRoleInfo(Long roleId) {
+        return fnRoleService.retrieveAppRoleByRoleIdWhereAppIdIsNull(roleId);
+    }
+
+    ResponseEntity<String> getUserRolesFromExtAuthSystem(String name, HttpEntity<String> getUserRolesEntity) {
+        logger.debug(EELFLoggerDelegate.debugLogger, "Connecting to external system to get current user roles");
+        ResponseEntity<String> getResponse = template
+            .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                + "roles/user/" + name, HttpMethod.GET, getUserRolesEntity, String.class);
+        if (getResponse.getStatusCode().value() == 200) {
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "getAllUserRoleFromExtAuthSystem: Finished GET user roles from external system and received user roles {}",
+                getResponse.getBody());
+        } else {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "getAllUserRoleFromExtAuthSystem: Failed GET user roles from external system and received user roles {}",
+                getResponse.getBody());
+            EPLogUtil.logExternalAuthAccessAlarm(logger, getResponse.getStatusCode());
+        }
+        return getResponse;
+    }
+
+    Map<String, FnRole> getAppRoleNamesWithUnderscoreMap(FnApp app) {
+        final Map<String, FnRole> currentRolesInDB = new HashMap<>();
+        List<FnRole> getCurrentRoleList = null;
+        final Map<String, Long> appParams = new HashMap<>();
+        if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+            getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
         } else {
-          for (FnRole role : globalRolesList) {
-            CentralV2Role cenRole = convertRoleToCentralV2Role(role);
+            appParams.put("appId", app.getId());
+            getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(app.getId());
+        }
+        for (FnRole role : getCurrentRoleList) {
+            currentRolesInDB.put(role.getRoleName()
+                .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), role);
+        }
+        return currentRolesInDB;
+    }
+
+    List<CentralV2Role> createCentralRoleObject(List<FnApp> app, List<FnRole> roleInfo,
+        List<CentralV2Role> roleList) throws RoleFunctionException {
+        for (FnRole role : roleInfo) {
+            List<EpAppFunction> cenRoleFuncList = epAppFunctionService
+                .getAppRoleFunctionList(role.getId(), app.get(0).getId());
+            SortedSet<DomainVo> roleFunctionSet = new TreeSet<>();
+            for (EpAppFunction roleFunc : cenRoleFuncList) {
+                String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
+                functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+                String type = getFunctionCodeType(roleFunc.getFunctionCd());
+                String action = getFunctionCodeAction(roleFunc.getFunctionCd());
+                FnRoleFunction cenRoleFunc = new FnRoleFunction(role,
+                    FnFunction.builder().code(functionCode).name(roleFunc.getFunctionName()).type(type).action(action)
+                        .build());
+            }
+            SortedSet<CentralV2Role> childRoles = new TreeSet<>();
+            SortedSet<CentralV2Role> parentRoles = new TreeSet<>();
+            CentralV2Role cenRole;
+            if (role.getAppRoleId() == null) {
+                cenRole = CentralV2Role.builder().id(role.getId()).created(role.getCreated())
+                    .modified(role.getModified())
+                    .rowNum(role.getRowNum()).name(role.getRoleName())
+                    .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
+                    .childRoles(childRoles).parentRoles(parentRoles).build();
+            } else {
+                cenRole = CentralV2Role.builder().id(role.getAppRoleId())
+                    .created(role.getCreated()).modified(role.getModified())
+                    .rowNum(role.getRowNum()).name(role.getRoleName())
+                    .active(role.getActiveYn()).priority(role.getPriority()).roleFunctions(roleFunctionSet)
+                    .childRoles(childRoles).parentRoles(parentRoles).build();
+            }
             roleList.add(cenRole);
-          }
-        }
-      }
-    } catch (Exception e) {
-      logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
-      throw e;
-    }
-    logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
-    return roleList.stream().distinct().collect(Collectors.toList());
-  }
-
-  private CentralV2Role convertRoleToCentralV2Role(FnRole role) {
-    return CentralV2Role.builder().id(role.getId()).created(role.getCreated())
-        .modified(role.getModified())
-        .rowNum(role.getRowNum()).name(role.getRoleName()).active(role.getActiveYn())
-        .priority(role.getPriority()).roleFunctions(new TreeSet<>()).childRoles(new TreeSet<>())
-        .parentRoles(new TreeSet<>()).build();
-  }
-
-  private List<CentralV2Role> getGlobalRolesOfApplication(Long appId) {
-    List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
-    try {
-      List<Tuple> tuples = entityManager.createQuery(GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS, Tuple.class)
-          .setParameter("appId", appId)
-          .getResultList();
-      globalRoles = tuples.stream().map(this::tupleToGlobalRoleWithApplicationRoleFunction).collect(Collectors.toList());
-    } catch (Exception e) {
-      logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
-    }
-    List<CentralV2Role> roleList = new ArrayList<>();
-    if (globalRoles.size() > 0) {
-      roleList = finalListOfCentralRoles(globalRoles);
-    }
-    return roleList;
-  }
-
-  private GlobalRoleWithApplicationRoleFunction tupleToGlobalRoleWithApplicationRoleFunction(Tuple tuple) {
-    return GlobalRoleWithApplicationRoleFunction.builder().roleId((Long) tuple.get("roleId"))
-        .roleName((String) tuple.get("roleName"))
-        .functionCd((String) tuple.get("functionCd")).functionName((String) tuple.get("functionName"))
-        .active((Boolean) tuple.get("active")).priority((Integer) tuple.get("priority"))
-        .appId((Long) tuple.get("appId")).roleAppId((Long) tuple.get("roleAppId")).build();
-  }
-
-  private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
-    List<CentralV2Role> rolesfinalList = new ArrayList<>();
-    for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
-      boolean found = false;
-      for (CentralV2Role cenRole : rolesfinalList) {
-        if (role.getRoleId().equals(cenRole.getId())) {
-          SortedSet<FnRoleFunction> roleFunctions = cenRole.getRoleFunctions();
-          FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
-          roleFunctions.add(cenRoleFun);
-          cenRole.setRoleFunctions(roleFunctions);
-          found = true;
-          break;
-        }
-      }
-      if (!found) {
-        CentralV2Role cenrole = new CentralV2Role();
-        cenrole.setName(role.getRoleName());
-        cenrole.setId(role.getRoleId());
-        cenrole.setActive(role.getActive());
-        cenrole.setPriority(role.getPriority());
-        SortedSet<FnRoleFunction> roleFunctions = new TreeSet<>();
-        FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
-        roleFunctions.add(cenRoleFun);
-        cenrole.setRoleFunctions(roleFunctions);
-        rolesfinalList.add(cenrole);
-      }
-    }
-    return rolesfinalList;
-  }
-
-  private FnRoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
-    String instance;
-    String type;
-    String action;
-    FnRoleFunction cenRoleFun = null;
-    if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
-      instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
-      type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
-      action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
-      cenRoleFun = FnRoleFunction.builder().build();
-      FnRole fnRole = new FnRole();
-      FnFunction fnFunction = FnFunction.builder().functionCd(instance).name(role.getFunctionName()).type(type).action(action).build();
-      cenRoleFun.setRole(fnRole);
-      cenRoleFun.setFunctionCd(fnFunction);
-    } else {
-      type = getFunctionCodeType(role.getFunctionCd());
-      action = getFunctionCodeAction(role.getFunctionCd());
-      FnFunction fnFunction = FnFunction.builder().functionCd(role.getFunctionCd()).name(role.getFunctionName()).type(type).action(action).build();
-      cenRoleFun.setRole(new FnRole());
-      cenRoleFun.setFunctionCd(fnFunction);
-    }
-    return cenRoleFun;
-  }
+        }
+        return roleList;
+    }
+
+    public String getFunctionCodeAction(String roleFuncItem) {
+        return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem);
+    }
+
+    public List<CentralV2Role> getRolesForApp(String uebkey) throws Exception {
+        logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Entering into getRolesForApp");
+        List<CentralV2Role> roleList = new ArrayList<>();
+        try {
+            List<FnApp> app = fnAppService.getByUebKey(uebkey);
+            List<FnRole> appRolesList = fnRoleService.getAppRoles(app.get(0).getId());
+            roleList = createCentralRoleObject(app, appRolesList, roleList);
+            if (!Objects.equals(app.get(0).getId(), PortalConstants.PORTAL_APP_ID)) {
+                List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
+                List<FnRole> globalRolesList = fnRoleService.getGlobalRolesOfPortal();
+                List<CentralV2Role> portalsGlobalRolesFinlaList = new ArrayList<>();
+                if (!globalRolesList.isEmpty()) {
+                    for (FnRole eprole : globalRolesList) {
+                        CentralV2Role cenRole = convertRoleToCentralV2Role(eprole);
+                        portalsGlobalRolesFinlaList.add(cenRole);
+                    }
+                    roleList.addAll(globalRoleList);
+                    for (CentralV2Role role : portalsGlobalRolesFinlaList) {
+                        CentralV2Role result = roleList.stream().filter(x -> role.getId().equals(x.getId())).findAny()
+                            .orElse(null);
+                        if (result == null) {
+                            roleList.add(role);
+                        }
+                    }
+                } else {
+                    for (FnRole role : globalRolesList) {
+                        CentralV2Role cenRole = convertRoleToCentralV2Role(role);
+                        roleList.add(cenRole);
+                    }
+                }
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getRolesForApp: Failed!", e);
+            throw e;
+        }
+        logger.debug(EELFLoggerDelegate.debugLogger, "getRolesForApp: Finished!");
+        return roleList.stream().distinct().collect(Collectors.toList());
+    }
+
+    private List<CentralV2Role> getGlobalRolesOfApplication(final Long appId) {
+        List<GlobalRoleWithApplicationRoleFunction> globalRoles = new ArrayList<>();
+        try {
+            List<Tuple> tuples = entityManager.createQuery(GET_GLOBAL_ROLE_WITH_APPLICATION_ROLE_FUNCTIONS, Tuple.class)
+                .setParameter("appId", appId)
+                .getResultList();
+            globalRoles = tuples.stream().map(this::tupleToGlobalRoleWithApplicationRoleFunction)
+                .collect(Collectors.toList());
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getCentralizedAppsOfUser failed", e);
+        }
+        List<CentralV2Role> roleList = new ArrayList<>();
+        if (globalRoles.size() > 0) {
+            roleList = finalListOfCentralRoles(globalRoles);
+        }
+        return roleList;
+    }
+
+    private GlobalRoleWithApplicationRoleFunction tupleToGlobalRoleWithApplicationRoleFunction(Tuple tuple) {
+        return GlobalRoleWithApplicationRoleFunction.builder().roleId((Long) tuple.get("roleId"))
+            .roleName((String) tuple.get("roleName"))
+            .functionCd((String) tuple.get("functionCd")).functionName((String) tuple.get("functionName"))
+            .active((Boolean) tuple.get("active")).priority((Integer) tuple.get("priority"))
+            .appId((Long) tuple.get("appId")).roleAppId((Long) tuple.get("roleAppId")).build();
+    }
+
+    private List<CentralV2Role> finalListOfCentralRoles(List<GlobalRoleWithApplicationRoleFunction> globalRoles) {
+        List<CentralV2Role> rolesfinalList = new ArrayList<>();
+        for (GlobalRoleWithApplicationRoleFunction role : globalRoles) {
+            boolean found = false;
+            for (CentralV2Role cenRole : rolesfinalList) {
+                if (role.getRoleId().equals(cenRole.getId())) {
+                    SortedSet<DomainVo> roleFunctions = new TreeSet<>();
+                    for (DomainVo vo : cenRole.getRoleFunctions()) {
+                        Optional<FnRoleFunction> roleFunction = fnRoleFunctionService.findById(vo.getId());
+                        roleFunction.ifPresent(roleFunctions::add);
+                    }
+                    FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
+                    roleFunctions.add(cenRoleFun);
+                    cenRole.setRoleFunctions(roleFunctions);
+                    found = true;
+                    break;
+                }
+            }
+            if (!found) {
+                CentralV2Role cenrole = new CentralV2Role();
+                cenrole.setName(role.getRoleName());
+                cenrole.setId(role.getRoleId());
+                cenrole.setActive(role.getActive());
+                cenrole.setPriority(role.getPriority());
+                SortedSet<DomainVo> roleFunctions = new TreeSet<>();
+                FnRoleFunction cenRoleFun = createCentralRoleFunctionForGlobalRole(role);
+                roleFunctions.add(cenRoleFun);
+                cenrole.setRoleFunctions(roleFunctions);
+                rolesfinalList.add(cenrole);
+            }
+        }
+        return rolesfinalList;
+    }
+
+    public String getV2UserWithRoles(String loginId, String uebkey) throws Exception {
+        final Map<String, String> params = new HashMap<>();
+        FnUser user = null;
+        CentralV2User cenV2User = null;
+        String result = null;
+        try {
+            params.put("orgUserIdValue", loginId);
+            List<FnApp> appList = getApp(uebkey);
+            if (!appList.isEmpty()) {
+                user = fnUserService.loadUserByUsername(loginId);
+                ObjectMapper mapper = new ObjectMapper();
+                cenV2User = getV2UserAppRoles(loginId, uebkey);
+                result = mapper.writeValueAsString(cenV2User);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getUser: failed", e);
+            throw e;
+        }
+        return result;
+    }
+
+    public void syncApplicationRolesWithEcompDB(FnApp app) {
+        try {
+            logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Started");
+            // Sync functions and roles assigned to it which also creates new roles if does
+            // not exits in portal
+            syncRoleFunctionFromExternalAccessSystem(app);
+            logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: Finished");
+            ObjectMapper mapper = new ObjectMapper();
+            logger.debug(EELFLoggerDelegate.debugLogger, "Entering to getAppRolesJSONFromExtAuthSystem");
+            // Get Permissions from External Auth System
+            JSONArray extRole = getAppRolesJSONFromExtAuthSystem(app.getId(), app.getAuthNamespace());
+            logger.debug(EELFLoggerDelegate.debugLogger, "Entering into getExternalRoleDetailsList");
+            // refactoring done
+            List<ExternalRoleDetails> externalRoleDetailsList = getExternalRoleDetailsList(app, mapper, extRole);
+            List<FnRole> finalRoleList = new ArrayList<>();
+            for (ExternalRoleDetails externalRole : externalRoleDetailsList) {
+                FnRole ecompRole = convertExternalRoleDetailsToEpRole(externalRole);
+                finalRoleList.add(ecompRole);
+            }
+            List<FnRole> applicationRolesList;
+            applicationRolesList = getAppRoles(app.getId());
+            List<String> applicationRoleIdList = new ArrayList<>();
+            for (FnRole applicationRole : applicationRolesList) {
+                applicationRoleIdList.add(applicationRole.getRoleName());
+            }
+            List<FnRole> roleListToBeAddInEcompDB = new ArrayList<>();
+            for (FnRole aafRole : finalRoleList) {
+                if (!applicationRoleIdList.contains(aafRole.getRoleName())) {
+                    roleListToBeAddInEcompDB.add(aafRole);
+                }
+            }
+            logger.debug(EELFLoggerDelegate.debugLogger, "Entering into inactiveRolesNotInExternalAuthSystem");
+            // Check if roles exits in external Access system and if not make inactive in DB
+            inactiveRolesNotInExternalAuthSystem(app.getId(), finalRoleList, applicationRolesList);
+            logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addNewRoleInEcompDBUpdateDescInExtAuthSystem");
+            // Add new roles in DB and updates role description in External Auth System
+            addNewRoleInEcompDBUpdateDescInExtAuthSystem(app, roleListToBeAddInEcompDB);
+            logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: Finished");
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "syncApplicationRolesWithEcompDB: Failed due to the External Auth System", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "syncApplicationRolesWithEcompDB: Failed ", e);
+        }
+    }
+
+    public List<FnRole> getAppRoles(Long appId) {
+        List<FnRole> applicationRoles;
+        try {
+            if (appId == 1) {
+                applicationRoles = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
+            } else {
+                applicationRoles = fnRoleService.retrieveAppRolesByAppId(appId);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getAppRoles: failed", e);
+            throw e;
+        }
+        return applicationRoles;
+    }
+
+    private FnRole convertExternalRoleDetailsToEpRole(ExternalRoleDetails externalRoleDetails) {
+        FnRole role = new FnRole();
+        role.setActiveYn(true);
+        role.setAppId(externalRoleDetails.getAppId());
+        role.setAppRoleId(externalRoleDetails.getAppRoleId());
+        role.setRoleName(externalRoleDetails.getName());
+        role.setPriority(externalRoleDetails.getPriority());
+        return role;
+    }
+
+    public List<ExternalRoleDetails> getExternalRoleDetailsList(FnApp app, ObjectMapper mapper, JSONArray extRole)
+        throws IOException {
+        List<ExternalRoleDetails> externalRoleDetailsList = new ArrayList<>();
+        ExternalAccessPerms externalAccessPerms;
+        List<String> functionCodelist = new ArrayList<>();
+        Map<String, FnRole> curRolesMap = getAppRoleNamesMap(app.getId());
+        Map<String, FnRole> curRolesUnderscoreMap = getAppRoleNamesWithUnderscoreMap(app);
+        for (int i = 0; i < extRole.length(); i++) {
+            ExternalRoleDetails externalRoleDetail = new ExternalRoleDetails();
+            EPAppRoleFunction ePAppRoleFunction = new EPAppRoleFunction();
+            JSONObject Role = (JSONObject) extRole.get(i);
+            String name = extRole.getJSONObject(i).getString(ROLE_NAME);
+            String actualRoleName = name.substring(app.getAuthNamespace().length() + 1);
+            if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
+                actualRoleName = extRole.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
+            }
+            SortedSet<ExternalAccessPerms> externalAccessPermsOfRole = new TreeSet<>();
+            if (extRole.getJSONObject(i).has(EXTERNAL_AUTH_PERMS)) {
+                JSONArray extPerm = (JSONArray) Role.get(EXTERNAL_AUTH_PERMS);
+                for (int j = 0; j < extPerm.length(); j++) {
+                    JSONObject perms = extPerm.getJSONObject(j);
+                    boolean isNamespaceMatching = EcompPortalUtils.checkNameSpaceMatching(perms.getString("type"),
+                        app.getAuthNamespace());
+                    if (isNamespaceMatching) {
+                        externalAccessPerms = new ExternalAccessPerms(perms.getString("type"),
+                            perms.getString("instance"), perms.getString("action"));
+                        ePAppRoleFunction.setCode(externalAccessPerms.getInstance());
+                        functionCodelist.add(ePAppRoleFunction.getCode());
+                        externalAccessPermsOfRole.add(externalAccessPerms);
+                    }
+                }
+            }
+            externalRoleDetail.setActive(true);
+            externalRoleDetail.setName(actualRoleName);
+            if (app.getId() == 1) {
+                externalRoleDetail.setAppId(null);
+            } else {
+                externalRoleDetail.setAppId(app.getId());
+            }
+            FnRole currRole = null;
+            currRole = (!extRole.getJSONObject(i).has(EXTERNAL_AUTH_ROLE_DESCRIPTION))
+                ? curRolesUnderscoreMap.get(actualRoleName)
+                : curRolesMap.get(actualRoleName);
+            Long roleId = null;
+            if (currRole != null) {
+                roleId = currRole.getId();
+            }
+            final Map<String, EpAppRoleFunction> roleFunctionsMap = new HashMap<>();
+            if (roleId != null) {
+                List<EpAppRoleFunction> appRoleFunctions = epAppRoleFunctionService
+                    .getAppRoleFunctionOnRoleIdAndAppId(app.getId(), roleId);
+                if (!appRoleFunctions.isEmpty()) {
+                    for (EpAppRoleFunction roleFunc : appRoleFunctions) {
+                        roleFunctionsMap.put(roleFunc.getEpAppFunction().getFunctionCd(), roleFunc);
+                    }
+                }
+            }
+            if (!externalAccessPermsOfRole.isEmpty()) {
+                // Adding functions to role
+                for (ExternalAccessPerms externalpermission : externalAccessPermsOfRole) {
+                    EpAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance());
+                    if (checkRoleFunctionExits == null) {
+                        String funcCode = externalpermission.getType().substring(app.getAuthNamespace().length() + 1)
+                            + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE
+                            + externalpermission.getAction();
+                        EpAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode);
+                        if (checkRoleFunctionPipeExits == null) {
+                            try {
+                                logger.debug(EELFLoggerDelegate.debugLogger,
+                                    "SyncApplicationRolesWithEcompDB: Adding function to the role: {}",
+                                    externalpermission.getInstance());
+                                List<EpAppFunction> roleFunction = epAppFunctionService
+                                    .getAppFunctionOnCodeAndAppId(app.getId(), externalpermission.getInstance());
+                                if (roleFunction.isEmpty()) {
+                                    roleFunction = epAppFunctionService
+                                        .getAppFunctionOnCodeAndAppId(app.getId(), funcCode);
+                                }
+                                if (!roleFunction.isEmpty()) {
+                                    EpAppRoleFunction apRoleFunction = new EpAppRoleFunction();
+                                    apRoleFunction.setAppId(app);
+                                    apRoleFunction.setFnRole(currRole);
+                                    apRoleFunction.setEpAppFunction(roleFunction.get(0));
+                                    epAppRoleFunctionService.save(apRoleFunction);
+                                }
+                            } catch (Exception e) {
+                                logger.error(EELFLoggerDelegate.errorLogger,
+                                    "SyncApplicationRolesWithEcompDB: Failed to add role function", e);
+                            }
+                        }
+                    }
+                }
+            }
+            externalRoleDetailsList.add(externalRoleDetail);
+        }
+        return externalRoleDetailsList;
+    }
+
+    private Map<String, FnRole> getAppRoleNamesMap(final Long appId) {
+        final Map<String, FnRole> currentRolesInDB = new HashMap<>();
+        List<FnRole> getCurrentRoleList = null;
+        final Map<String, Long> appParams = new HashMap<>();
+        if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
+            getCurrentRoleList = fnRoleService.retrieveAppRolesWhereAppIdIsNull();
+        } else {
+            getCurrentRoleList = fnRoleService.retrieveAppRolesByAppId(appId);
+        }
+        for (FnRole role : getCurrentRoleList) {
+            currentRolesInDB.put(role.getRoleName(), role);
+        }
+        return currentRolesInDB;
+    }
+
+    public JSONArray getAppRolesJSONFromExtAuthSystem(final long appId, final String authNamespace) throws Exception {
+        ResponseEntity<String> response = null;
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        HttpEntity<String> entity = new HttpEntity<>(headers);
+        logger.debug(EELFLoggerDelegate.debugLogger, "syncApplicationRolesWithEcompDB: {} ",
+            CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+        response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+            + "roles/ns/" + authNamespace, HttpMethod.GET, entity, String.class);
+        String res = response.getBody();
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "syncApplicationRolesWithEcompDB: Finished GET roles from External Auth system and the result is :",
+            res);
+        JSONObject jsonObj = new JSONObject(res);
+        JSONArray extRole = jsonObj.getJSONArray("role");
+        for (int i = 0; i < extRole.length(); i++) {
+            if (extRole.getJSONObject(i).getString(ROLE_NAME).equals(authNamespace + ADMIN)
+                || extRole.getJSONObject(i).getString(ROLE_NAME).equals(authNamespace + OWNER)
+                || (extRole.getJSONObject(i).getString(ROLE_NAME).equals(authNamespace + ACCOUNT_ADMINISTRATOR)
+                && !(appId == PortalConstants.PORTAL_APP_ID))) {
+                extRole.remove(i);
+                i--;
+            }
+        }
+        return extRole;
+    }
+
+    private void addNewRoleInEcompDBUpdateDescInExtAuthSystem(FnApp app, List<FnRole> roleListToBeAddInEcompDB) {
+        FnRole roleToBeAddedInEcompDB;
+        for (FnRole fnRole : roleListToBeAddInEcompDB) {
+            try {
+                roleToBeAddedInEcompDB = fnRole;
+                if (app.getId() == 1) {
+                    roleToBeAddedInEcompDB.setAppRoleId(null);
+                }
+                fnRoleService.saveOne(roleToBeAddedInEcompDB);
+                List<FnRole> getRoleCreatedInSync = null;
+                if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                    getRoleCreatedInSync = fnRoleService
+                        .retrieveAppRolesByRoleNameAndByAppId(roleToBeAddedInEcompDB.getRoleName(), app.getId());
+                    FnRole epUpdateRole = getRoleCreatedInSync.get(0);
+                    epUpdateRole.setAppRoleId(epUpdateRole.getId());
+                    fnRoleService.saveOne(epUpdateRole);
+                }
+                List<FnRole> roleList;
+                final Map<String, String> params = new HashMap<>();
+                params.put(APP_ROLE_NAME_PARAM, roleToBeAddedInEcompDB.getRoleName());
+                boolean isPortalRole;
+                if (app.getId() == 1) {
+                    isPortalRole = true;
+                    roleList = fnRoleService
+                        .retrieveAppRolesByRoleNameAndWhereAppIdIsNull(roleToBeAddedInEcompDB.getRoleName());
+                } else {
+                    isPortalRole = false;
+                    roleList = fnRoleService
+                        .retrieveAppRolesByRoleNameAndByAppId(roleToBeAddedInEcompDB.getRoleName(), app.getId());
+                }
+                FnRole role = roleList.get(0);
+                Role aaFrole = new Role();
+                aaFrole.setId(role.getId());
+                aaFrole.setActive(role.getActiveYn());
+                aaFrole.setPriority(role.getPriority());
+                aaFrole.setName(role.getRoleName());
+                updateRoleInExternalSystem(aaFrole, app, isPortalRole);
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "SyncApplicationRolesWithEcompDB: Failed to add or update role in external auth system", e);
+            }
+        }
+    }
+
+    private void updateRoleInExternalSystem(Role updateExtRole, FnApp app, boolean isGlobalRole) throws Exception {
+        ObjectMapper mapper = new ObjectMapper();
+        ResponseEntity<String> deleteResponse = null;
+        List<FnRole> epRoleList = null;
+        if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
+            || (isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
+            epRoleList = getPortalAppRoleInfo(updateExtRole.getId());
+        } else {
+            epRoleList = getPartnerAppRoleInfo(updateExtRole.getId(), app.getId());
+        }
+        // Assigning functions to global role
+        if ((isGlobalRole && !app.getId().equals(PortalConstants.PORTAL_APP_ID))) {
+            List<FnFunction> functions = new ArrayList<>();
+            for (FnRoleFunction roleFunction : convertSetToListOfRoleFunctions(updateExtRole)) {
+                functions.add(roleFunction.getFunctionCd());
+            }
+            // TODO HARDCODED ID
+            FnApp portalAppInfo = fnAppService.getById(PortalConstants.PORTAL_APP_ID);
+            addFunctionsTOGlobalRole(epRoleList, updateExtRole, functions, mapper, app, portalAppInfo);
+        } else {
+            String appRole = getSingleAppRole(epRoleList.get(0).getRoleName(), app);
+            List<FnRoleFunction> roleFunctionListNew = convertSetToListOfRoleFunctions(updateExtRole);
+            if (!appRole.equals(IS_EMPTY_JSON_STRING)) {
+                JSONObject jsonObj = new JSONObject(appRole);
+                JSONArray extRole = jsonObj.getJSONArray("role");
+                if (!extRole.getJSONObject(0).has(EXTERNAL_AUTH_ROLE_DESCRIPTION)) {
+                    String roleName = extRole.getJSONObject(0).getString(ROLE_NAME);
+                    Map<String, String> delRoleKeyMapper = new HashMap<>();
+                    delRoleKeyMapper.put(ROLE_NAME, roleName);
+                    String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
+                    deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
+                    if (deleteResponse.getStatusCode().value() != 200) {
+                        throw new ExternalAuthSystemException(deleteResponse.getBody());
+                    }
+                    addRole(updateExtRole, app.getUebKey());
+                } else {
+                    String desc = extRole.getJSONObject(0).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
+                    String name = extRole.getJSONObject(0).getString(ROLE_NAME);
+                    List<ExternalAccessPerms> list = new ArrayList<>();
+                    if (extRole.getJSONObject(0).has(EXTERNAL_AUTH_PERMS)) {
+                        JSONArray perms = extRole.getJSONObject(0).getJSONArray(EXTERNAL_AUTH_PERMS);
+                        list = mapper.readValue(perms.toString(), TypeFactory.defaultInstance()
+                            .constructCollectionType(List.class, ExternalAccessPerms.class));
+                    }
+                    // If role name or role functions are updated then delete
+                    // record in External System and add new record to avoid
+                    // conflicts
+                    boolean isRoleNameChanged = false;
+                    if (!desc.equals(updateExtRole.getName())) {
+                        isRoleNameChanged = true;
+                        deleteRoleInExtSystem(mapper, name);
+                        addRole(updateExtRole, app.getUebKey());
+                        // add partner functions to the global role in External
+                        // Auth System
+                        if (!list.isEmpty() && isGlobalRole) {
+                            addPartnerHasRoleFunctionsToGlobalRole(list, mapper, app, updateExtRole);
+                        }
+                        list.removeIf(
+                            perm -> EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getAuthNamespace()));
+                        // if role name is changes please ignore the previous
+                        // functions in External Auth
+                        // and update with user requested functions
+                        addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name, list);
+                    }
+                    // Delete role in External System if role is inactive
+                    if (!updateExtRole.getActive()) {
+                        deleteRoleInExtSystem(mapper, name);
+                    }
+                    if (!isRoleNameChanged) {
+                        addRemoveFunctionsToRole(updateExtRole, app, mapper, roleFunctionListNew, name,
+                            list);
+                    }
+                }
+            } else {
+                // It seems like role exists in local DB but not in External
+                // Access system
+                if (updateExtRole.getActive()) {
+                    addRole(updateExtRole, app.getUebKey());
+                    ExternalAccessRolePerms extAddRolePerms = null;
+                    ExternalAccessPerms extAddPerms = null;
+                    List<FnRoleFunction> roleFunctionListAdd = convertSetToListOfRoleFunctions(updateExtRole);
+                    HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+                    for (FnRoleFunction roleFunc : roleFunctionListAdd) {
+                        extAddPerms = new ExternalAccessPerms(
+                            app.getAuthNamespace() + "." + roleFunc.getFunctionCd().getType(),
+                            roleFunc.getFunctionCd().getCode(), roleFunc.getFunctionCd().getAction());
+                        extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
+                            app.getAuthNamespace() + "." + updateExtRole.getName().replaceAll(
+                                EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+                        addRoleFuncExtSysRestAPI(mapper, extAddRolePerms, headers);
+                    }
+                }
+            }
+        }
+    }
+
+    private void addRemoveFunctionsToRole(Role updateExtRole, FnApp app, ObjectMapper mapper,
+        List<FnRoleFunction> fnRoleFunctions, String name, List<ExternalAccessPerms> list) throws Exception {
+        boolean response;
+        List<FnFunction> roleFunctionListNew = new ArrayList<>();
+        for (FnRoleFunction roleFunction : fnRoleFunctions) {
+            roleFunctionListNew.add(roleFunction.getFunctionCd());
+        }
+        Map<String, FnFunction> updateRoleFunc = new HashMap<>();
+        for (FnFunction addPerm : roleFunctionListNew) {
+            updateRoleFunc.put(addPerm.getCode(), addPerm);
+        }
+        final Map<String, ExternalAccessPerms> extRolePermMap = new HashMap<>();
+        final Map<String, ExternalAccessPerms> extRolePermMapPipes = new HashMap<>();
+        list.removeIf(perm -> !EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getAuthNamespace()));
+        // Update permissions in the ExternalAccess System
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        if (!list.isEmpty()) {
+            for (ExternalAccessPerms perm : list) {
+                FnFunction roleFunc = updateRoleFunc.get(perm.getType().substring(app.getAuthNamespace().length() + 1)
+                    + FUNCTION_PIPE + perm.getInstance() + FUNCTION_PIPE + perm.getAction());
+                if (roleFunc == null) {
+                    FnFunction roleFuncPipeFilter = updateRoleFunc.get(perm.getInstance());
+                    if (roleFuncPipeFilter == null) {
+                        removePermForRole(perm, mapper, name, headers);
+                    }
+                }
+                extRolePermMap.put(perm.getInstance(), perm);
+                extRolePermMapPipes.put(perm.getType().substring(app.getAuthNamespace().length() + 1) + FUNCTION_PIPE
+                    + perm.getInstance() + FUNCTION_PIPE + perm.getAction(), perm);
+            }
+        }
+        response = true;
+        if (!roleFunctionListNew.isEmpty()) {
+            for (FnFunction roleFunc : roleFunctionListNew) {
+                if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
+                    ExternalAccessPerms perm = extRolePermMapPipes.get(roleFunc.getCode());
+                    if (perm == null) {
+                        response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
+                            roleFunc);
+                    }
+                } else {
+                    if (!extRolePermMap.containsKey(EcompPortalUtils.getFunctionCode(roleFunc.getCode()))) {
+                        response = addFunctionsToRoleInExternalAuthSystem(updateExtRole, app, mapper, headers,
+                            roleFunc);
+                    }
+                }
+            }
+        }
+    }
+
+    private boolean addFunctionsToRoleInExternalAuthSystem(Role updateExtRole, FnApp app, ObjectMapper mapper,
+        HttpHeaders headers, FnFunction roleFunc) throws JsonProcessingException {
+        boolean response;
+        ExternalAccessRolePerms extRolePerms;
+        ExternalAccessPerms extPerms;
+        String code;
+        String type;
+        String action;
+        if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
+            code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+            type = EcompPortalUtils.getFunctionType(roleFunc.getCode());
+            action = getFunctionCodeAction(roleFunc.getCode());
+        } else {
+            code = roleFunc.getCode();
+            type = roleFunc.getCode().contains("menu") ? "menu" : "url";
+            action = "*";
+        }
+        extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, code, action);
+        extRolePerms = new ExternalAccessRolePerms(extPerms, app.getAuthNamespace() + "." + updateExtRole.getName()
+            .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+        String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+        HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+        logger.debug(EELFLoggerDelegate.debugLogger, "updateRoleInExternalSystem: {} for POST: {}",
+            CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
+        ResponseEntity<String> addResponse = template.exchange(
+            SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+            HttpMethod.POST, entity, String.class);
+        if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
+            response = false;
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "updateRoleInExternalSystem: Connected to External Auth system but something went wrong! due to {} and statuscode: {}",
+                addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
+        } else {
+            response = true;
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "updateRoleInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
+                updateRolePerms, addResponse.getStatusCode().value());
+        }
+        return response;
+    }
+
+    private void addRoleFuncExtSysRestAPI(ObjectMapper addPermsMapper, ExternalAccessRolePerms extAddRolePerms,
+        HttpHeaders headers) throws JsonProcessingException {
+        boolean response;
+        String updateRolePerms = addPermsMapper.writeValueAsString(extAddRolePerms);
+        HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+        logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} for POST: {} ",
+            CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
+        ResponseEntity<String> addResponse = template.exchange(
+            SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+            HttpMethod.POST, entity, String.class);
+        if (addResponse.getStatusCode().value() != 201 && addResponse.getStatusCode().value() != 409) {
+            response = false;
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
+                addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
+        } else {
+            response = true;
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system {} and status code: {} ",
+                updateRolePerms, addResponse.getStatusCode().value());
+        }
+    }
+
+    private void addPartnerHasRoleFunctionsToGlobalRole(List<ExternalAccessPerms> permslist, ObjectMapper mapper,
+        FnApp app, Role updateExtRole) throws Exception {
+        for (ExternalAccessPerms perm : permslist) {
+            if (!EcompPortalUtils.checkNameSpaceMatching(perm.getType(), app.getAuthNamespace())) {
+                ExternalAccessRolePerms extAddGlobalRolePerms = null;
+                ExternalAccessPerms extAddPerms = null;
+                extAddPerms = new ExternalAccessPerms(perm.getType(), perm.getInstance(), perm.getAction());
+                extAddGlobalRolePerms = new ExternalAccessRolePerms(extAddPerms,
+                    app.getAuthNamespace() + "." + updateExtRole.getName().replaceAll(
+                        EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+                String addPerms = mapper.writeValueAsString(extAddGlobalRolePerms);
+                HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+                HttpEntity<String> entity = new HttpEntity<>(addPerms, headers);
+                logger.debug(EELFLoggerDelegate.debugLogger, "addPartnerHasRoleFunctionsToGlobalRole: {} ",
+                    CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+                try {
+                    ResponseEntity<String> addResponse = template
+                        .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                            + "role/perm", HttpMethod.POST, entity, String.class);
+                    if (addResponse.getStatusCode().value() != 201) {
+                        logger.debug(EELFLoggerDelegate.debugLogger,
+                            "addPartnerHasRoleFunctionsToGlobalRole: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
+                            addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
+                    } else {
+                        logger.debug(EELFLoggerDelegate.debugLogger,
+                            "addPartnerHasRoleFunctionsToGlobalRole: Finished adding permissions to roles in External Auth system and status code: {} ",
+                            addResponse.getStatusCode().value());
+                    }
+                } catch (Exception e) {
+                    logger.error(EELFLoggerDelegate.errorLogger,
+                        "addPartnerHasRoleFunctionsToGlobalRole: Failed for POST request: {} due to ", addPerms, e);
+                }
+            }
+        }
+    }
+
+    private void deleteRoleInExtSystem(ObjectMapper mapper, String name)
+        throws JsonProcessingException, Exception, ExternalAuthSystemException {
+        ResponseEntity<String> deleteResponse;
+        Map<String, String> delRoleKeyMapper = new HashMap<>();
+        delRoleKeyMapper.put(ROLE_NAME, name);
+        String delRoleKeyValue = mapper.writeValueAsString(delRoleKeyMapper);
+        deleteResponse = deleteRoleInExternalSystem(delRoleKeyValue);
+        if (deleteResponse.getStatusCode().value() != 200) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "updateRoleInExternalSystem:  Failed to delete role in external system due to {} ",
+                deleteResponse.getBody());
+            throw new ExternalAuthSystemException(deleteResponse.getBody());
+        }
+    }
+
+    public void addRole(Role addRole, String uebkey) throws Exception {
+        boolean response = false;
+        ResponseEntity<String> addResponse = null;
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        FnApp app = getApp(uebkey).get(0);
+        String newRole = updateExistingRoleInExternalSystem(addRole.getName(), app.getAuthNamespace());
+        HttpEntity<String> entity = new HttpEntity<>(newRole, headers);
+        logger.debug(EELFLoggerDelegate.debugLogger, "addRole: Connecting to External Auth system");
+        addResponse = template.exchange(
+            SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+            HttpMethod.POST, entity, String.class);
+        if (addResponse.getStatusCode().value() == 201) {
+            response = true;
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "addRole: Finished adding role in the External Auth system  and response code: {} ",
+                addResponse.getStatusCode().value());
+        }
+        if (addResponse.getStatusCode().value() == 406) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "addRole: Failed to add in the External Auth system due to {} and status code: {}",
+                addResponse.getBody(), addResponse.getStatusCode().value());
+        }
+    }
+
+    private ResponseEntity<String> deleteRoleInExternalSystem(String delRole) throws Exception {
+        ResponseEntity<String> delResponse = null;
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        HttpEntity<String> entity = new HttpEntity<>(delRole, headers);
+        logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleInExternalSystem: {} for DELETE: {}",
+            CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, delRole);
+        delResponse = template.exchange(
+            SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role?force=true",
+            HttpMethod.DELETE, entity, String.class);
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "deleteRoleInExternalSystem: Finished DELETE operation in the External Auth system {} and status code: {} ",
+            delRole, delResponse.getStatusCode().value());
+        return delResponse;
+    }
+
+    private String getSingleAppRole(String addRole, FnApp app) throws Exception {
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        HttpEntity<String> entity = new HttpEntity<>(headers);
+        ResponseEntity<String> response = null;
+        logger.debug(EELFLoggerDelegate.debugLogger, "getSingleAppRole: Connecting to External Auth system");
+        response = template.exchange(
+            SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
+                + app.getAuthNamespace() + "." + addRole
+                .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+            HttpMethod.GET, entity, String.class);
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "getSingleAppRole: Finished GET app role from External Auth system and status code: {} ",
+            response.getStatusCode().value());
+        return response.getBody();
+    }
+
+    private void addFunctionsTOGlobalRole(List<FnRole> epRoleList, Role updateExtRole,
+        List<FnFunction> roleFunctionListNew, ObjectMapper mapper, FnApp app, FnApp portalAppInfo)
+        throws Exception {
+        try {
+            logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addFunctionsTOGlobalRole");
+            // GET Permissions from External Auth System
+            JSONArray extPerms = getExtAuthPermissions(app.getAuthNamespace());
+            List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
+            final Map<String, ExternalAccessPermsDetail> existingPermsWithRoles = new HashMap<>();
+            final Map<String, ExternalAccessPermsDetail> existingPermsWithRolesWithPipes = new HashMap<>();
+            final Map<String, FnFunction> userRquestedFunctionsMap = new HashMap<>();
+            final Map<String, FnFunction> userRquestedFunctionsMapPipesFilter = new HashMap<>();
+            for (ExternalAccessPermsDetail permDetail : permsDetailList) {
+                existingPermsWithRoles.put(EcompPortalUtils.getFunctionCode(permDetail.getInstance()), permDetail);
+                existingPermsWithRolesWithPipes.put(permDetail.getInstance(), permDetail);
+            }
+            // Add If function does not exists for role in External Auth System
+            for (FnFunction roleFunc : roleFunctionListNew) {
+                String roleFuncCode = "";
+                ExternalAccessPermsDetail permsDetail;
+                if (roleFunc.getCode().contains(FUNCTION_PIPE)) {
+                    roleFuncCode = roleFunc.getCode();
+                    permsDetail = existingPermsWithRolesWithPipes.get(roleFunc.getCode());
+                } else {
+                    roleFuncCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+                    permsDetail = existingPermsWithRoles.get(roleFuncCode);
+                }
+                if (null == permsDetail.getRoles()
+                    || !permsDetail.getRoles()
+                    .contains(portalAppInfo.getAuthNamespace() + FUNCTION_PIPE
+                        + epRoleList.get(0).getRoleName().replaceAll(
+                        EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS,
+                        "_"))) {
+                    addRoleFunctionsToGlobalRoleInExternalSystem(roleFunc, updateExtRole, mapper, app, portalAppInfo);
+                }
+                userRquestedFunctionsMap.put(roleFuncCode, roleFunc);
+                userRquestedFunctionsMapPipesFilter.put(EcompPortalUtils.getFunctionCode(roleFuncCode), roleFunc);
+            }
+            List<GlobalRoleWithApplicationRoleFunction> globalRoleFunctionList = entityManager
+                .createNamedQuery("getGlobalRoleForRequestedApp")
+                .setParameter("requestedAppId", app.getId())
+                .setParameter("roleId", updateExtRole.getId())
+                .getResultList();
+            for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFunctionList) {
+                String globalRoleFuncWithoutPipes = "";
+                FnFunction roleFunc = null;
+                if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
+                    globalRoleFuncWithoutPipes = globalRoleFunc.getFunctionCd();
+                    roleFunc = userRquestedFunctionsMap.get(globalRoleFuncWithoutPipes);
+                } else {
+                    globalRoleFuncWithoutPipes = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
+                    roleFunc = userRquestedFunctionsMapPipesFilter.get(globalRoleFuncWithoutPipes);
+                }
+                if (roleFunc == null) {
+                    ExternalAccessPermsDetail permDetailFromMap = globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)
+                        ? existingPermsWithRolesWithPipes.get(globalRoleFuncWithoutPipes)
+                        : existingPermsWithRoles.get(globalRoleFuncWithoutPipes);
+                    ExternalAccessPerms perm = new ExternalAccessPerms(permDetailFromMap.getType(),
+                        EcompPortalUtils.getFunctionCode(permDetailFromMap.getInstance()),
+                        permDetailFromMap.getAction());
+                    String roleName = portalAppInfo.getAuthNamespace() + "." + globalRoleFunc.getRoleName()
+                        .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
+                    HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+                    removePermForRole(perm, mapper, roleName, headers);
+                }
+            }
+            logger.debug(EELFLoggerDelegate.debugLogger, "Finished addFunctionsTOGlobalRole");
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "addFunctionsTOGlobalRole: Failed", e);
+            throw e;
+        }
+    }
+
+    private void removePermForRole(ExternalAccessPerms perm, ObjectMapper permMapper, String name, HttpHeaders headers)
+        throws ExternalAuthSystemException, JsonProcessingException {
+        ExternalAccessRolePerms extAccessRolePerms = new ExternalAccessRolePerms(perm, name);
+        String permDetails = permMapper.writeValueAsString(extAccessRolePerms);
+        try {
+            HttpEntity<String> deleteEntity = new HttpEntity<>(permDetails, headers);
+            logger.debug(EELFLoggerDelegate.debugLogger, "removePermForRole: {} for DELETE: {} ",
+                CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, permDetails);
+            ResponseEntity<String> deletePermResponse = template
+                .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                    + "role/" + name + "/perm", HttpMethod.DELETE, deleteEntity, String.class);
+            if (deletePermResponse.getStatusCode().value() != 200) {
+                throw new ExternalAuthSystemException(deletePermResponse.getBody());
+            }
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "removePermForRole: Finished deleting permission to role in External Auth system: {} and status code: {}",
+                permDetails, deletePermResponse.getStatusCode().value());
+        } catch (Exception e) {
+            if (e.getMessage().contains("404")) {
+                logger.error(EELFLoggerDelegate.errorLogger, "Failed to add role for DELETE request: {} due to {}",
+                    permDetails, e.getMessage());
+            } else {
+                throw e;
+            }
+        }
+    }
+
+    private void addRoleFunctionsToGlobalRoleInExternalSystem(FnFunction addFunction, Role globalRole,
+        ObjectMapper mapper, FnApp app, FnApp portalAppInfo) throws Exception {
+        try {
+            logger.debug(EELFLoggerDelegate.debugLogger, "Entering into addRoleFunctionsToGlobalRoleInExternalSystem");
+            ExternalAccessRolePerms extAddRolePerms = null;
+            ExternalAccessPerms extAddPerms = null;
+            HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+            String code = "";
+            String type = "";
+            String action = "";
+            if (addFunction.getFunctionCd().contains(FUNCTION_PIPE)) {
+                code = EcompPortalUtils.getFunctionCode(addFunction.getFunctionCd());
+                type = getFunctionCodeType(addFunction.getFunctionCd());
+                action = getFunctionCodeAction(addFunction.getFunctionCd());
+            } else {
+                code = addFunction.getFunctionCd();
+                type = addFunction.getFunctionCd().contains("menu") ? "menu" : "url";
+                action = "*";
+            }
+            extAddPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, code, action);
+            extAddRolePerms = new ExternalAccessRolePerms(extAddPerms,
+                portalAppInfo.getAuthNamespace() + "." + globalRole
+                    .getName().replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+            String updateRolePerms = mapper.writeValueAsString(extAddRolePerms);
+            HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+            logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionsInExternalSystem: {} ",
+                CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+            ResponseEntity<String> addResponse = template.exchange(
+                SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+                HttpMethod.POST, entity, String.class);
+            if (addResponse.getStatusCode().value() != 201) {
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    "addRoleFunctionsInExternalSystem: While adding permission to the role in  External Auth system something went wrong! due to {} and statuscode: {}",
+                    addResponse.getStatusCode().getReasonPhrase(), addResponse.getStatusCode().value());
+            } else {
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    "addRoleFunctionsInExternalSystem: Finished adding permissions to roles in External Auth system and status code: {} ",
+                    addResponse.getStatusCode().value());
+            }
+            logger.debug(EELFLoggerDelegate.debugLogger, "Finished addRoleFunctionsToGlobalRoleInExternalSystem");
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "addRoleFunctionsToGlobalRoleInExternalSystem: Failed", e);
+            throw e;
+        }
+    }
+
+    private List<FnRoleFunction> convertSetToListOfRoleFunctions(Role updateExtRole) {
+        Set<FnRoleFunction> roleFunctionSetList = updateExtRole.getRoleFunctions();
+        List<FnRoleFunction> roleFunctionList = new ArrayList<>();
+        ObjectMapper roleFuncMapper = new ObjectMapper();
+        for (Object nextValue : roleFunctionSetList) {
+            FnRoleFunction roleFunction = roleFuncMapper.convertValue(nextValue, FnRoleFunction.class);
+            roleFunctionList.add(roleFunction);
+        }
+        return roleFunctionList.stream().distinct().collect(Collectors.toList());
+    }
+
+    private List<FnRole> getPartnerAppRoleInfo(Long roleId, Long appId) {
+        List<FnRole> roleInfo = fnRoleService.retrieveAppRoleByAppRoleIdAndByAppId(roleId, appId);
+        if (roleInfo.isEmpty()) {
+            roleInfo = fnRoleService.retrieveAppRoleByAppRoleIdAndByAppId(appId, roleId);
+        }
+        return roleInfo;
+    }
+
+    private void inactiveRolesNotInExternalAuthSystem(final Long appId, List<FnRole> finalRoleList,
+        List<FnRole> applicationRolesList) {
+        final Map<String, FnRole> checkRolesInactive = new HashMap<>();
+        for (FnRole extrole : finalRoleList) {
+            checkRolesInactive.put(extrole.getRoleName(), extrole);
+        }
+        for (FnRole role : applicationRolesList) {
+            try {
+                List<FnRole> roleList;
+                if (!checkRolesInactive.containsKey(role.getRoleName())) {
+                    if (appId == 1) {
+                        roleList = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(role.getRoleName());
+                    } else {
+                        roleList = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role.getRoleName(), appId);
+                    }
+                    if (!roleList.isEmpty()) {
+                        FnRole updateRoleInactive = roleList.get(0);
+                        updateRoleInactive.setActiveYn(false);
+                        fnRoleService.saveOne(updateRoleInactive);
+                    }
+                }
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "syncApplicationRolesWithEcompDB: Failed to de-activate role ", e);
+            }
+        }
+    }
+
+    private JSONArray getExtAuthPermissions(String authNamespace) throws Exception {
+        ResponseEntity<String> response = null;
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        HttpEntity<String> entity = new HttpEntity<>(headers);
+        logger.debug(EELFLoggerDelegate.debugLogger, "syncRoleFunctionFromExternalAccessSystem: {} ",
+            CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+        response = template.exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+            + "perms/ns/" + authNamespace, HttpMethod.GET, entity, String.class);
+        String res = response.getBody();
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "syncRoleFunctionFromExternalAccessSystem: Finished GET permissions from External Auth system and response: {} ",
+            response.getBody());
+        JSONObject jsonObj = new JSONObject(res);
+        JSONArray extPerms = jsonObj.getJSONArray("perm");
+        for (int i = 0; i < extPerms.length(); i++) {
+            if (extPerms.getJSONObject(i).getString("type").equals(authNamespace + ".access")) {
+                extPerms.remove(i);
+                i--;
+            }
+        }
+        return extPerms;
+    }
+
+    public void syncRoleFunctionFromExternalAccessSystem(FnApp app) {
+        try {
+            // get Permissions from External Auth System
+            JSONArray extPerms = getExtAuthPermissions(app.getAuthNamespace());
+            List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPerms);
+            final Map<String, EpAppFunction> roleFuncMap = new HashMap<>();
+            List<EpAppFunction> appFunctions = epAppFunctionService.getAllRoleFunctions(app.getId());
+            if (!appFunctions.isEmpty()) {
+                for (EpAppFunction roleFunc : appFunctions) {
+                    roleFuncMap.put(roleFunc.getFunctionCd(), roleFunc);
+                }
+            }
+            // get Roles for portal in DB
+            List<FnRole> portalRoleList = getGlobalRolesOfPortal();
+            final Map<String, FnRole> existingPortalRolesMap = new HashMap<>();
+            for (FnRole epRole : portalRoleList) {
+                existingPortalRolesMap.put(epRole.getRoleName().replaceAll(
+                    EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), epRole);
+            }
+            // get Roles in DB
+            final Map<String, FnRole> currentRolesInDB = getAppRoleNamesWithUnderscoreMap(app);
+            // store External Permissions with Pipe and without Pipe (just
+            // instance)
+            final Map<String, ExternalAccessPermsDetail> extAccessPermsContainsPipeMap = new HashMap<>();
+            final Map<String, ExternalAccessPermsDetail> extAccessPermsMap = new HashMap<>();
+            for (ExternalAccessPermsDetail permsDetailInfoWithPipe : permsDetailList) {
+                extAccessPermsContainsPipeMap.put(permsDetailInfoWithPipe.getInstance(), permsDetailInfoWithPipe);
+                String finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetailInfoWithPipe.getInstance());
+                extAccessPermsMap.put(finalFunctionCodeVal, permsDetailInfoWithPipe);
+            }
+            // Add if new functions and app role functions were added in
+            // external auth system
+            for (ExternalAccessPermsDetail permsDetail : permsDetailList) {
+                String code = permsDetail.getInstance();
+                EpAppFunction getFunctionCodeKey = roleFuncMap.get(permsDetail.getInstance());
+                List<EpAppFunction> roleFunctionList = addGetLocalFunction(app, roleFuncMap, permsDetail, code,
+                    getFunctionCodeKey);
+                List<String> roles = permsDetail.getRoles();
+                if (roles != null) {
+                    addRemoveIfFunctionsRolesIsSyncWithExternalAuth(app, currentRolesInDB, roleFunctionList, roles,
+                        existingPortalRolesMap);
+                }
+            }
+            // Check if function does exits in External Auth System but exits in
+            // local then delete function and its dependencies
+            for (EpAppFunction roleFunc : appFunctions) {
+                try {
+                    ExternalAccessPermsDetail getFunctionCodeContainsPipeKey = extAccessPermsContainsPipeMap
+                        .get(roleFunc.getFunctionCd());
+                    if (null == getFunctionCodeContainsPipeKey) {
+                        ExternalAccessPermsDetail getFunctionCodeKey = extAccessPermsMap.get(roleFunc.getFunctionCd());
+                        if (null == getFunctionCodeKey) {
+                            deleteAppRoleFuncDoesNotExitsInExtSystem(app.getId(), roleFunc.getFunctionCd());
+                        }
+                    }
+                } catch (Exception e) {
+                    logger.error(EELFLoggerDelegate.errorLogger,
+                        "syncRoleFunctionFromExternalAccessSystem: Failed to delete function", e);
+                }
+            }
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "syncRoleFunctionFromExternalAccessSystem: Finished syncRoleFunctionFromExternalAccessSystem");
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "syncRoleFunctionFromExternalAccessSystem: Failed syncRoleFunctionFromExternalAccessSystem", e);
+        }
+    }
+
+    private List<EpAppFunction> addGetLocalFunction(FnApp app,
+        final Map<String, EpAppFunction> roleFuncMap, ExternalAccessPermsDetail permsDetail, String code,
+        EpAppFunction getFunctionCodeKey) {
+        String finalFunctionCodeVal = addToLocalIfFunctionNotExists(app, roleFuncMap, permsDetail, code,
+            getFunctionCodeKey);
+        List<EpAppFunction> roleFunctionList = epAppFunctionService
+            .getAppFunctionOnCodeAndAppId(app.getId(), finalFunctionCodeVal);
+        if (roleFunctionList.isEmpty()) {
+            roleFunctionList = epAppFunctionService.getAppFunctionOnCodeAndAppId(app.getId(), code);
+        }
+        return roleFunctionList;
+    }
+
+    private String addToLocalIfFunctionNotExists(FnApp app, final Map<String, EpAppFunction> roleFuncMap,
+        ExternalAccessPermsDetail permsDetail, String code, EpAppFunction getFunctionCodeKey) {
+        String finalFunctionCodeVal = "";
+        if (null == getFunctionCodeKey) {
+            finalFunctionCodeVal = EcompPortalUtils.getFunctionCode(permsDetail.getInstance());
+            EpAppFunction checkIfCodeStillExits = roleFuncMap.get(finalFunctionCodeVal);
+            // If function does not exist in local then add!
+            if (null == checkIfCodeStillExits) {
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    "syncRoleFunctionFromExternalAccessSystem: Adding function: {} ", code);
+                addFunctionInEcompDB(app, permsDetail, code);
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    "syncRoleFunctionFromExternalAccessSystem: Finished adding function: {} ", code);
+            }
+        }
+        return finalFunctionCodeVal;
+    }
+
+    private void addFunctionInEcompDB(FnApp app, ExternalAccessPermsDetail permsDetail, String code) {
+        try {
+            EpAppFunction addFunction = new EpAppFunction();
+            addFunction.setAppId(app);
+            addFunction.setFunctionCd(code);
+            addFunction.setFunctionName(permsDetail.getDescription());
+            epAppFunctionService.save(addFunction);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "addFunctionInEcompDB: Failed to add function", e);
+        }
+    }
+
+    private List<ExternalAccessPermsDetail> getExtAuthPerrmissonList(FnApp app, JSONArray extPerms) throws IOException {
+        ExternalAccessPermsDetail permDetails = null;
+        List<ExternalAccessPermsDetail> permsDetailList = new ArrayList<>();
+        for (int i = 0; i < extPerms.length(); i++) {
+            String description = null;
+            if (extPerms.getJSONObject(i).has("description")) {
+                description = extPerms.getJSONObject(i).getString(EXTERNAL_AUTH_ROLE_DESCRIPTION);
+            } else {
+                description =
+                    extPerms.getJSONObject(i).getString("type").substring(app.getAuthNamespace().length() + 1) + "|"
+                        + extPerms.getJSONObject(i).getString("instance") + "|"
+                        + extPerms.getJSONObject(i).getString("action");
+            }
+            if (extPerms.getJSONObject(i).has("roles")) {
+                ObjectMapper rolesListMapper = new ObjectMapper();
+                JSONArray resRoles = extPerms.getJSONObject(i).getJSONArray("roles");
+                List<String> list = rolesListMapper.readValue(resRoles.toString(),
+                    TypeFactory.defaultInstance().constructCollectionType(List.class, String.class));
+                permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
+                    extPerms.getJSONObject(i).getString("type").substring(app.getAuthNamespace().length() + 1)
+                        + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
+                        + extPerms.getJSONObject(i).getString("action"),
+                    extPerms.getJSONObject(i).getString("action"), list, description);
+                permsDetailList.add(permDetails);
+            } else {
+                permDetails = new ExternalAccessPermsDetail(extPerms.getJSONObject(i).getString("type"),
+                    extPerms.getJSONObject(i).getString("type").substring(app.getAuthNamespace().length() + 1)
+                        + FUNCTION_PIPE + extPerms.getJSONObject(i).getString("instance") + FUNCTION_PIPE
+                        + extPerms.getJSONObject(i).getString("action"),
+                    extPerms.getJSONObject(i).getString("action"), description);
+                permsDetailList.add(permDetails);
+            }
+        }
+        return permsDetailList;
+    }
+
+    public List<FnRole> getGlobalRolesOfPortal() {
+        List<FnRole> globalRoles = new ArrayList<>();
+        try {
+            globalRoles = fnRoleService.getGlobalRolesOfPortal();
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRolesOfPortal failed", e);
+        }
+        return globalRoles;
+    }
+
+    private void deleteAppRoleFuncDoesNotExitsInExtSystem(final Long appId, final String roleFunc) {
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "syncRoleFunctionFromExternalAccessSystem: Deleting app role function {}", roleFunc);
+        epAppRoleFunctionService.deleteByAppIdAndFunctionCd(appId, roleFunc);
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "syncRoleFunctionFromExternalAccessSystem: Deleted app role function {}", roleFunc);
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "syncRoleFunctionFromExternalAccessSystem: Deleting app function {}", roleFunc);
+        epAppFunctionService.deleteByAppIdAndFunctionCd(appId, roleFunc);
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "syncRoleFunctionFromExternalAccessSystem: Deleted app function {}", roleFunc);
+    }
+
+    private CentralV2Role convertRoleToCentralV2Role(FnRole role) {
+        return CentralV2Role.builder().id(role.getId()).created(role.getCreated())
+            .modified(role.getModified()).createdId(role.getCreatedId().getId())
+            .modifiedId(role.getModifiedId().getId())
+            .rowNum(role.getRowNum()).name(role.getRoleName()).active(role.getActiveYn())
+            .priority(role.getPriority()).roleFunctions(new TreeSet<>()).childRoles(new TreeSet<>())
+            .parentRoles(new TreeSet<>()).build();
+    }
+
+    private void addRemoveIfFunctionsRolesIsSyncWithExternalAuth(FnApp app, final Map<String, FnRole> currentRolesInDB,
+        List<EpAppFunction> roleFunctionList, List<String> roles,
+        Map<String, FnRole> existingPortalRolesMap) throws Exception {
+        if (!roleFunctionList.isEmpty()) {
+            final Map<String, LocalRole> currentAppRoleFunctionsMap = new HashMap<>();
+            final Map<String, String> currentRolesInExtSystem = new HashMap<>();
+            List<LocalRole> localRoleList = localRoleService
+                .getCurrentAppRoleFunctions(app.getId(), roleFunctionList.get(0).getFunctionCd());
+            for (LocalRole localRole : localRoleList) {
+                currentAppRoleFunctionsMap.put(localRole.getRolename().replaceAll(
+                    EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"), localRole);
+            }
+            for (String addRole : roles) {
+                currentRolesInExtSystem.put(addRole.substring(addRole.indexOf(FUNCTION_PIPE) + 1), addRole);
+            }
+            for (String extAuthrole : roles) {
+                String roleNameSpace = extAuthrole.substring(0, extAuthrole.indexOf(FUNCTION_PIPE));
+                boolean isNameSpaceMatching = EcompPortalUtils.checkNameSpaceMatching(roleNameSpace,
+                    app.getAuthNamespace());
+                if (isNameSpaceMatching) {
+                    if (!currentAppRoleFunctionsMap
+                        .containsKey(extAuthrole.substring(app.getAuthNamespace().length() + 1))) {
+                        FnRole localAddFuntionRole = currentRolesInDB
+                            .get(extAuthrole.substring(app.getAuthNamespace().length() + 1));
+                        if (localAddFuntionRole == null) {
+                            checkAndAddRoleInDB(app, currentRolesInDB, roleFunctionList, extAuthrole);
+                        } else {
+                            EpAppRoleFunction addAppRoleFunc = new EpAppRoleFunction();
+                            addAppRoleFunc.setAppId(app);
+                            addAppRoleFunc.setEpAppFunction(roleFunctionList.get(0));
+                            addAppRoleFunc.setFnRole(localAddFuntionRole);
+                            epAppRoleFunctionService.save(addAppRoleFunc);
+                        }
+                    }
+                    // This block is to save global role function if exists
+                } else {
+                    String extAuthAppRoleName = extAuthrole.substring(extAuthrole.indexOf(FUNCTION_PIPE) + 1);
+                    boolean checkIfGlobalRoleExists = existingPortalRolesMap.containsKey(extAuthAppRoleName);
+                    if (checkIfGlobalRoleExists) {
+                        FnRole role = existingPortalRolesMap.get(extAuthAppRoleName);
+                        EpAppRoleFunction addGlobalRoleFunctions = new EpAppRoleFunction();
+                        List<EpAppRoleFunction> currentGlobalRoleFunctionsList = epAppRoleFunctionService
+                            .getAppRoleFunctionOnRoleIdAndAppId(app.getId(), role.getId());
+                        boolean checkIfRoleFunctionExists = currentGlobalRoleFunctionsList.stream()
+                            .anyMatch(currentGlobalRoleFunction -> currentGlobalRoleFunction.getEpAppFunction()
+                                .getFunctionCd()
+                                .equals(roleFunctionList.get(0).getFunctionCd()));
+                        if (!checkIfRoleFunctionExists) {
+                            addGlobalRoleFunctions.setAppId(app);
+                            addGlobalRoleFunctions.setFnRole(role);
+                            if (!app.getId().equals(role.getAppRoleId())) {
+                                addGlobalRoleFunctions.setRoleAppId((PortalConstants.PORTAL_APP_ID).toString());
+                            } else {
+                                addGlobalRoleFunctions.setRoleAppId(null);
+                            }
+                            addGlobalRoleFunctions.setEpAppFunction(roleFunctionList.get(0));
+                            epAppRoleFunctionService.save(addGlobalRoleFunctions);
+                        }
+                    }
+                }
+            }
+            for (LocalRole localRoleDelete : localRoleList) {
+                if (!currentRolesInExtSystem.containsKey(localRoleDelete.getRolename()
+                    .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"))) {
+                    epAppRoleFunctionService
+                        .deleteByAppIdAndFunctionCdAndRoleId(app.getId(), roleFunctionList.get(0).getFunctionCd(),
+                            localRoleDelete.getRoleId());
+                }
+            }
+        }
+    }
+
+    private void checkAndAddRoleInDB(FnApp app, final Map<String, FnRole> currentRolesInDB,
+        List<EpAppFunction> roleFunctionList, String roleList) throws Exception {
+        if (!currentRolesInDB.containsKey(roleList.substring(app.getAuthNamespace().length() + 1))) {
+            FnRole role = addRoleInDBIfDoesNotExists(app.getId(),
+                roleList.substring(app.getAuthNamespace().length() + 1));
+            addRoleDescriptionInExtSystem(role.getRoleName(), app.getAuthNamespace());
+            if (!roleFunctionList.isEmpty()) {
+                try {
+                    EpAppRoleFunction addAppRoleFunc = new EpAppRoleFunction();
+                    addAppRoleFunc.setAppId(app);
+                    addAppRoleFunc.setEpAppFunction(roleFunctionList.get(0));
+                    addAppRoleFunc.setFnRole(role);
+                    epAppRoleFunctionService.save(addAppRoleFunc);
+                } catch (Exception e) {
+                    logger.error(EELFLoggerDelegate.errorLogger,
+                        "syncRoleFunctionFromExternalAccessSystem: Failed to save app role function ", e);
+                }
+            }
+        }
+    }
+
+    private FnRole addRoleInDBIfDoesNotExists(final Long appId, final String role) {
+        FnRole setNewRole = new FnRole();
+        try {
+            boolean isCreated = checkIfRoleExitsElseCreateInSyncFunctions(role, appId);
+            List<FnRole> getRoleCreated = null;
+            if (!appId.equals(PortalConstants.PORTAL_APP_ID)) {
+                List<FnRole> roleCreated = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role, appId);
+                if (!isCreated) {
+                    FnRole epUpdateRole = roleCreated.get(0);
+                    epUpdateRole.setAppRoleId(epUpdateRole.getId());
+                    fnRoleService.saveOne(epUpdateRole);
+                    getRoleCreated = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role, appId);
+                } else {
+                    getRoleCreated = roleCreated;
+                }
+            } else {
+                getRoleCreated = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(role);
+            }
+            if (getRoleCreated != null && !getRoleCreated.isEmpty()) {
+                FnRole roleObject = getRoleCreated.get(0);
+                setNewRole.setId(roleObject.getId());
+                setNewRole.setRoleName(roleObject.getRoleName());
+                setNewRole.setActiveYn(roleObject.getActiveYn());
+                setNewRole.setPriority(roleObject.getPriority());
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "addRoleInDBIfDoesNotExists: Failed", e);
+        }
+        return setNewRole;
+    }
+
+    private boolean checkIfRoleExitsElseCreateInSyncFunctions(final String role, final long appId) {
+        boolean isCreated;
+        List<FnRole> roleCreated = null;
+        if (appId == PortalConstants.PORTAL_APP_ID) {
+            roleCreated = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(role);
+        } else {
+            roleCreated = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(role, appId);
+        }
+        if (roleCreated == null || roleCreated.isEmpty()) {
+            FnRole epRoleNew = new FnRole();
+            epRoleNew.setActiveYn(true);
+            epRoleNew.setRoleName(role);
+            if (appId == PortalConstants.PORTAL_APP_ID) {
+                epRoleNew.setAppId(null);
+            } else {
+                epRoleNew.setAppId(appId);
+            }
+            fnRoleService.saveOne(epRoleNew);
+            isCreated = false;
+        } else {
+            isCreated = true;
+        }
+        return isCreated;
+    }
+
+    private String updateExistingRoleInExternalSystem(final String roleName, final String authNamespace)
+        throws JsonProcessingException {
+        ObjectMapper mapper = new ObjectMapper();
+        String addNewRole = "";
+        ExternalAccessRole extRole = new ExternalAccessRole();
+        extRole.setName(authNamespace + "." + roleName
+            .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+        extRole.setDescription(String.valueOf(roleName));
+        addNewRole = mapper.writeValueAsString(extRole);
+        return addNewRole;
+    }
+
+    private boolean addRoleDescriptionInExtSystem(final String roleName, final String authNamespace) throws Exception {
+        boolean status = false;
+        try {
+            String addRoleNew = updateExistingRoleInExternalSystem(roleName, authNamespace);
+            HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+            HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
+            template.exchange(
+                SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+                HttpMethod.PUT, entity, String.class);
+            status = true;
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "HttpClientErrorException - Failed to addRoleDescriptionInExtSystem", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "addRoleDescriptionInExtSystem: Failed", e);
+        }
+        return status;
+    }
+
+    public List<CentralRole> convertV2CentralRoleListToOldVerisonCentralRoleList(List<CentralV2Role> v2CenRoleList) {
+        List<CentralRole> cenRoleList = new ArrayList<>();
+        for (CentralV2Role v2CenRole : v2CenRoleList) {
+            SortedSet<EpAppFunction> cenRoleFuncList = new TreeSet<>();
+            for (DomainVo vo : v2CenRole.getRoleFunctions()) {
+                Optional<FnRoleFunction> v2CenRoleFunc = fnRoleFunctionService.findById(vo.getId());
+                if (v2CenRoleFunc.isPresent()) {
+                    EpAppFunction roleFunc = EpAppFunction.builder()
+                        .functionCd(v2CenRoleFunc.get().getFunctionCd().getCode())
+                        .functionName(v2CenRoleFunc.get().getRole().getRoleName())
+                        .build();
+                    cenRoleFuncList.add(roleFunc);
+                }
+            }
+            CentralRole role = new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(),
+                v2CenRole.getPriority(), cenRoleFuncList);
+            cenRoleList.add(role);
+        }
+        return cenRoleList;
+    }
+
+    public ExternalRequestFieldsValidator saveRoleForApplication(Role saveRole, String uebkey) throws Exception {
+        boolean response = false;
+        String message = "";
+        try {
+            FnApp app = getApp(uebkey).get(0);
+            addRoleInEcompDB(saveRole, app);
+            response = true;
+        } catch (Exception e) {
+            message = e.getMessage();
+            logger.error(EELFLoggerDelegate.errorLogger, "saveRoleForApplication failed", e);
+        }
+        return new ExternalRequestFieldsValidator(response, message);
+    }
+
+    @Transactional(rollbackFor = Exception.class)
+    public void addRoleInEcompDB(Role addRoleInDB, FnApp app) throws Exception {
+        boolean result;
+        FnRole epRole;
+        Set<FnFunction> roleFunctionList = addRoleInDB.getRoleFunctions();
+        List<FnFunction> roleFunctionListNew = new ArrayList<>();
+        ObjectMapper mapper = new ObjectMapper();
+        for (Object nextValue : roleFunctionList) {
+            FnFunction roleFunction = mapper.convertValue(nextValue, FnFunction.class);
+            roleFunctionListNew.add(roleFunction);
+        }
+        List<FnFunction> listWithoutDuplicates = roleFunctionListNew.stream().distinct().collect(Collectors.toList());
+        try {
+            if (addRoleInDB.getId() == null) { // check if it is new role
+                if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                    checkIfRoleExitsInExternalSystem(addRoleInDB, app);
+                }
+                FnRole epRoleNew = new FnRole();
+                epRoleNew.setActiveYn(addRoleInDB.getActive());
+                epRoleNew.setRoleName(addRoleInDB.getName());
+                epRoleNew.setPriority(addRoleInDB.getPriority());
+                if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                    epRoleNew.setAppId(null);
+                } else {
+                    epRoleNew.setAppId(app.getId());
+                }
+                fnRoleService.saveOne(epRoleNew);
+                List<FnRole> getRoleCreated = null;
+                if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                    List<FnRole> roleCreated = fnRoleService
+                        .retrieveAppRolesByRoleNameAndByAppId(addRoleInDB.getName(), app.getId());
+                    FnRole epUpdateRole = roleCreated.get(0);
+                    epUpdateRole.setAppRoleId(epUpdateRole.getId());
+                    fnRoleService.saveOne(epUpdateRole);
+                    getRoleCreated = fnRoleService
+                        .retrieveAppRolesByRoleNameAndByAppId(addRoleInDB.getName(), app.getId());
+                } else {
+                    getRoleCreated = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(addRoleInDB.getName());
+                }
+                // Add role in External Auth system
+                if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                    addNewRoleInExternalSystem(getRoleCreated, app);
+                }
+                result = true;
+            } else { // if role already exists then update it
+                FnRole globalRole = null;
+                List<FnRole> applicationRoles;
+                List<FnRole> globalRoleList = getGlobalRolesOfPortal();
+                boolean isGlobalRole = false;
+                if (!globalRoleList.isEmpty()) {
+                    FnRole role = globalRoleList.stream().filter(x -> addRoleInDB.getId().equals(x.getId())).findAny()
+                        .orElse(null);
+                    if (role != null) {
+                        globalRole = role;
+                        isGlobalRole = true;
+                    }
+                }
+                if (app.getId().equals(PortalConstants.PORTAL_APP_ID)
+                    || (globalRole != null && app.getId() != globalRole.getAppId())) {
+                    applicationRoles = getPortalAppRoleInfo(addRoleInDB.getId());
+                } else {
+                    applicationRoles = getPartnerAppRoleInfo(addRoleInDB.getId(), app.getId());
+                }
+                if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                    updateRoleInExternalSystem(addRoleInDB, app, isGlobalRole);
+                    // Add all user to the re-named role in external auth system
+                    if (!applicationRoles.isEmpty()
+                        && !addRoleInDB.getName().equals(applicationRoles.get(0).getRoleName())) {
+                        bulkUploadUsersSingleRole(app.getUebKey(), applicationRoles.get(0).getId(),
+                            addRoleInDB.getName());
+                    }
+                }
+                deleteRoleFunction(app, applicationRoles);
+                if (!applicationRoles.isEmpty()) {
+                    epRole = applicationRoles.get(0);
+                    epRole.setRoleName(addRoleInDB.getName());
+                    epRole.setPriority(addRoleInDB.getPriority());
+                    epRole.setActiveYn(addRoleInDB.getActive());
+                    if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                        epRole.setAppId(null);
+                        epRole.setAppRoleId(null);
+                    } else if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)
+                        && applicationRoles.get(0).getAppRoleId() == null) {
+                        epRole.setAppRoleId(epRole.getId());
+                    }
+                    fnRoleService.saveOne(epRole);
+                }
+                Long roleAppId = null;
+                if (globalRole != null && !app.getId().equals(globalRole.getAppId())) {
+                    roleAppId = PortalConstants.PORTAL_APP_ID;
+                }
+                saveRoleFunction(listWithoutDuplicates, app, applicationRoles, roleAppId);
+                result = true;
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "addRoleInEcompDB is failed", e);
+            throw e;
+        }
+    }
+
+    private void saveRoleFunction(List<FnFunction> roleFunctionListNew, FnApp app, List<FnRole> applicationRoles,
+        Long roleAppId) {
+        for (FnFunction roleFunc : roleFunctionListNew) {
+            String code = EcompPortalUtils.getFunctionCode(roleFunc.getCode());
+            EpAppRoleFunction appRoleFunc = new EpAppRoleFunction();
+            appRoleFunc.setAppId(app);
+            appRoleFunc.setFnRole(applicationRoles.get(0));
+            appRoleFunc.setRoleAppId(String.valueOf(roleAppId));
+            List<EpAppFunction> roleFunction = epAppFunctionService.getRoleFunction(roleFunc.getCode(), app.getId());
+            if (roleFunction.isEmpty()) {
+                roleFunction = epAppFunctionService.getRoleFunction(code, app.getId());
+            }
+            if (roleFunction.size() > 1) {
+                EpAppFunction getExactFunctionCode = appFunctionListFilter(code, roleFunction);
+                appRoleFunc.setEpAppFunction(getExactFunctionCode);
+            } else {
+                appRoleFunc.setEpAppFunction(roleFunction.get(0));
+            }
+            epAppRoleFunctionService.save(appRoleFunc);
+        }
+    }
+
+    @Transactional(propagation = Propagation.REQUIRED)
+    public boolean deleteRoleForApplication(String deleteRole, String uebkey) throws Exception {
+        boolean result;
+        try {
+            List<FnRole> epRoleList;
+            FnApp app = getApp(uebkey).get(0);
+            if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                epRoleList = fnRoleService.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(deleteRole);
+            } else {
+                epRoleList = fnRoleService.retrieveAppRolesByRoleNameAndByAppId(deleteRole, app.getId());
+            }
+            if (!epRoleList.isEmpty()) {
+                // Delete app role functions before deleting role
+                deleteRoleFunction(app, epRoleList);
+                if (app.getId() == 1) {
+                    // Delete fn_user_ role
+                    String query =
+                        "DELETE FROM FN_USER_ROLE WHERE " + APP_ID_EQUALS + app.getId() + " and role_id = " + epRoleList
+                            .get(0).getId();
+                    entityManager.createQuery(query).executeUpdate();
+                    boolean isPortalRequest = false;
+                    deleteRoleDependencyRecords(epRoleList.get(0).getId(), app.getId(), isPortalRequest);
+                }
+                deleteRoleInExternalAuthSystem(epRoleList, app);
+                logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: committed the transaction");
+                fnRoleService.delete(epRoleList.get(0));
+            }
+            result = true;
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteRoleForApplication: failed", e);
+            result = false;
+        }
+        return result;
+    }
+
+    private void deleteRoleInExternalAuthSystem(List<FnRole> epRoleList, FnApp app) throws Exception {
+        ResponseEntity<String> deleteResponse;
+        ResponseEntity<String> res = getNameSpaceIfExists(app);
+        if (res.getStatusCode() == HttpStatus.OK) {
+            // Delete Role in External System
+            String deleteRoleKey = "{\"name\":\"" + app.getAuthNamespace() + "." + epRoleList.get(0).getRoleName()
+                .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_") + "\"}";
+            deleteResponse = deleteRoleInExternalSystem(deleteRoleKey);
+            if (deleteResponse.getStatusCode().value() != 200 && deleteResponse.getStatusCode().value() != 404) {
+                EPLogUtil.logExternalAuthAccessAlarm(logger, deleteResponse.getStatusCode());
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "deleteRoleForApplication: Failed to delete role in external auth system! due to {} ",
+                    deleteResponse.getBody());
+            }
+            logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleForApplication: about to commit the transaction");
+        }
+    }
+
+    private void deleteRoleFunction(FnApp app, List<FnRole> role) {
+        List<EpAppRoleFunction> appRoleFunctionList = epAppRoleFunctionService
+            .getAppRoleFunctionOnRoleIdAndAppId(app.getId(), role.get(0).getId());
+        epAppRoleFunctionService.deleteInBatch(appRoleFunctionList);
+    }
+
+    public List<CentralV2Role> getActiveRoles(String uebkey) throws Exception {
+        List<CentralV2Role> roleList = new ArrayList<>();
+        try {
+            List<FnApp> app = getApp(uebkey);
+            Long appId = null;
+            if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                appId = app.get(0).getId();
+            }
+            List<FnRole> epRole;
+            if (appId == null) {
+                epRole = fnRoleService.retrieveActiveRolesWhereAppIdIsNull();
+            } else {
+                epRole = fnRoleService.retrieveActiveRolesOfApplication(appId);
+            }
+            roleList = createCentralRoleObject(app, epRole, roleList);
+            List<CentralV2Role> globalRoleList = getGlobalRolesOfApplication(app.get(0).getId());
+            if (globalRoleList.size() > 0) {
+                roleList.addAll(globalRoleList);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getActiveRoles: failed", e);
+            throw e;
+        }
+        return roleList;
+    }
+
+    public Integer bulkUploadRoles(String uebkey) throws Exception {
+        List<FnApp> app = getApp(uebkey);
+        List<FnRole> roles = getAppRoles(app.get(0).getId());
+        List<CentralV2Role> cenRoleList = new ArrayList<>();
+        final Map<String, Long> params = new HashMap<>();
+        Integer rolesListAdded = 0;
+        try {
+            cenRoleList = createCentralRoleObject(app, roles, cenRoleList);
+            ObjectMapper mapper = new ObjectMapper();
+            mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
+            String roleList = mapper.writeValueAsString(cenRoleList);
+            List<Role> roleObjectList = mapper.readValue(roleList,
+                TypeFactory.defaultInstance().constructCollectionType(List.class, Role.class));
+            for (Role role : roleObjectList) {
+                addRoleInExternalSystem(role, app.get(0));
+                rolesListAdded++;
+            }
+            if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                // Add Account Admin role in External AUTH System
+                try {
+                    String addAccountAdminRole = "";
+                    ExternalAccessRole extRole = new ExternalAccessRole();
+                    extRole.setName(app.get(0).getAuthNamespace() + "." + PortalConstants.ADMIN_ROLE
+                        .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+                    addAccountAdminRole = mapper.writeValueAsString(extRole);
+                    HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+                    HttpEntity<String> entity = new HttpEntity<>(addAccountAdminRole, headers);
+                    template.exchange(
+                        SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+                        HttpMethod.POST, entity, String.class);
+                    rolesListAdded++;
+                } catch (HttpClientErrorException e) {
+                    logger.error(EELFLoggerDelegate.errorLogger,
+                        "HttpClientErrorException - Failed to create Account Admin role", e);
+                    EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+                } catch (Exception e) {
+                    if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+                        logger.error(EELFLoggerDelegate.errorLogger,
+                            "bulkUploadRoles: Account Admin Role already exits but does not break functionality",
+                            e);
+                    } else {
+                        logger.error(EELFLoggerDelegate.errorLogger,
+                            "bulkUploadRoles: Failed to create Account Admin role", e.getMessage());
+                    }
+                }
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRoles: failed", e);
+            throw e;
+        }
+        return rolesListAdded;
+    }
+
+    private void addRoleInExternalSystem(Role role, FnApp app) throws Exception {
+        String addRoleNew = updateExistingRoleInExternalSystem(role.getName(), app.getAuthNamespace());
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        try {
+            HttpEntity<String> entity = new HttpEntity<>(addRoleNew, headers);
+            template.exchange(
+                SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+                HttpMethod.POST, entity, String.class);
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - Failed to addRoleInExternalSystem",
+                e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+        } catch (Exception e) {
+            if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "addRoleInExternalSystem: Role already exits but does not break functionality", e);
+            } else {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "addRoleInExternalSystem: Failed to addRoleInExternalSystem", e.getMessage());
+            }
+        }
+    }
+
+    public Integer bulkUploadFunctions(String uebkey) throws Exception {
+        FnApp app = getApp(uebkey).get(0);
+        List<FnRoleFunction> roleFuncList = fnRoleFunctionService.findAll();
+        EpAppFunction cenRoleFunc;
+        Integer functionsAdded = 0;
+        try {
+            for (FnRoleFunction roleFunc : roleFuncList) {
+                cenRoleFunc = EpAppFunction.builder()
+                    .functionCd(roleFunc.getFunctionCd().getName())
+                    .roleId(roleFunc.getRole().getId())
+                    .build();
+                addRoleFunctionInExternalSystem(cenRoleFunc, app);
+                functionsAdded++;
+            }
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadFunctions failed", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadFunctions: failed", e.getMessage(), e);
+        }
+        return functionsAdded;
+    }
+
+    public Integer bulkUploadRolesFunctions(String uebkey) throws Exception {
+        FnApp app = getApp(uebkey).get(0);
+        List<FnRole> roles = getAppRoles(app.getId());
+        Integer roleFunctions = 0;
+        try {
+            for (FnRole role : roles) {
+                List<BulkUploadRoleFunction> appRoleFunc = bulkUploadUserRolesService
+                    .uploadAllRoleFunctions(role.getId());
+                if (!appRoleFunc.isEmpty()) {
+                    for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
+                        addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
+                        roleFunctions++;
+                    }
+                }
+            }
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
+        }
+        return roleFunctions;
+    }
+
+    private void addRoleFunctionsInExternalSystem(BulkUploadRoleFunction addRoleFunc, FnRole role, FnApp app) {
+        String type;
+        String instance = "";
+        String action = "";
+        if (addRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
+            type = EcompPortalUtils.getFunctionType(addRoleFunc.getFunctionCd());
+            instance = EcompPortalUtils.getFunctionCode(addRoleFunc.getFunctionCd());
+            action = EcompPortalUtils.getFunctionAction(addRoleFunc.getFunctionCd());
+        } else {
+            type = addRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
+            instance = addRoleFunc.getFunctionCd();
+            action = "*";
+        }
+        ExternalAccessRolePerms extRolePerms = null;
+        ExternalAccessPerms extPerms = null;
+        ObjectMapper mapper = new ObjectMapper();
+        try {
+            HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+            extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, instance, action,
+                addRoleFunc.getFunctionName());
+            extRolePerms = new ExternalAccessRolePerms(extPerms, app.getAuthNamespace() + "." + role.getRoleName()
+                .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+            String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+            HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+            template.exchange(
+                SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+                HttpMethod.POST, entity, String.class);
+        } catch (Exception e) {
+            if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "addRoleFunctionsInExternalSystem: RoleFunction already exits but does not break functionality",
+                    e);
+            } else {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "addRoleFunctionsInExternalSystem: Failed to addRoleFunctionsInExternalSystem", e.getMessage());
+            }
+        }
+    }
+
+
+    public Integer bulkUploadUserRoles(String uebkey) throws Exception {
+        FnApp app = getApp(uebkey).get(0);
+        List<BulkUploadUserRoles> userRolesList;
+        Integer userRolesAdded = 0;
+        if (app.getAuthCentral()) {
+            userRolesList = bulkUploadUserRolesService.getBulkUserRoles(app.getUebKey());
+            for (BulkUploadUserRoles userRolesUpload : userRolesList) {
+                if (!userRolesUpload.getOrgUserId().equals("su1234")) {
+                    addUserRoleInExternalSystem(userRolesUpload);
+                    userRolesAdded++;
+                }
+            }
+        }
+        return userRolesAdded;
+    }
+
+    public Integer bulkUploadPartnerFunctions(String uebkey) throws Exception {
+        FnApp app = getApp(uebkey).get(0);
+        List<EpAppFunction> roleFuncList = epAppFunctionService.getAllRoleFunctions(app.getId());
+        Integer functionsAdded = 0;
+        try {
+            for (EpAppFunction roleFunc : roleFuncList) {
+                addFunctionInExternalSystem(roleFunc, app);
+                functionsAdded++;
+            }
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "HttpClientErrorException - bulkUploadPartnerFunctions failed",
+                e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadPartnerFunctions: failed", e.getMessage(), e);
+        }
+        return functionsAdded;
+    }
+
+    public void bulkUploadPartnerRoles(String uebkey, List<Role> roleList) throws Exception {
+        FnApp app = getApp(uebkey).get(0);
+        for (Role role : roleList) {
+            addRoleInExternalSystem(role, app);
+        }
+    }
+
+    private void addFunctionInExternalSystem(EpAppFunction roleFunc, FnApp app) throws Exception {
+        ObjectMapper mapper = new ObjectMapper();
+        ExternalAccessPerms extPerms = new ExternalAccessPerms();
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        String type = "";
+        String instance = "";
+        String action = "";
+        if ((roleFunc.getFunctionCd().contains(FUNCTION_PIPE))
+            || (roleFunc.getType() != null && roleFunc.getAction() != null)) {
+            type = EcompPortalUtils.getFunctionType(roleFunc.getFunctionCd());
+            instance = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
+            action = EcompPortalUtils.getFunctionAction(roleFunc.getFunctionCd());
+        } else {
+            type = roleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
+            instance = roleFunc.getFunctionCd();
+            action = "*";
+        }
+        try {
+            extPerms.setAction(action);
+            extPerms.setInstance(instance);
+            extPerms.setType(app.getAuthNamespace() + "." + type);
+            extPerms.setDescription(roleFunc.getFunctionName());
+            String addFunction = mapper.writeValueAsString(extPerms);
+            HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
+            logger.debug(EELFLoggerDelegate.debugLogger, "addFunctionInExternalSystem: {} for POST: {}",
+                CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
+            ResponseEntity<String> addPermResponse = template.exchange(
+                SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
+                HttpMethod.POST, entity, String.class);
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "addFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
+                addPermResponse.getStatusCode().value(), addFunction);
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "HttpClientErrorException - Failed to add function in external central auth system", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+            throw e;
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "addFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
+            throw e;
+        }
+    }
+
+    public Integer bulkUploadPartnerRoleFunctions(String uebkey) throws Exception {
+        FnApp app = getApp(uebkey).get(0);
+        List<FnRole> roles = getAppRoles(app.getId());
+        Integer roleFunctions = 0;
+        try {
+            for (FnRole role : roles) {
+                List<BulkUploadRoleFunction> appRoleFunc = bulkUploadUserRolesService
+                    .uploadPartnerRoleFunctions(role.getId());
+                if (!appRoleFunc.isEmpty()) {
+                    for (BulkUploadRoleFunction addRoleFunc : appRoleFunc) {
+                        addRoleFunctionsInExternalSystem(addRoleFunc, role, app);
+                        roleFunctions++;
+                    }
+                }
+            }
+            // upload global role functions to ext auth system
+            if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                roleFunctions = bulkUploadGlobalRoleFunctions(app, roleFunctions);
+            }
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "HttpClientErrorException - Failed to bulkUploadRolesFunctions", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "bulkUploadRolesFunctions: failed", e);
+        }
+        return roleFunctions;
+    }
+
+    private Integer bulkUploadGlobalRoleFunctions(FnApp app, Integer roleFunctions) throws Exception {
+        try {
+            //TODO HARDCODED ID!!!!!
+            FnApp portalApp = fnAppService.getById(1L);
+            String getBulkUploadPartnerGlobalRoleFunctions =
+                "select distinct fr.role_id, fr.role_name, fr.active_yn, fr.priority, epr.function_cd, ep.function_name, ep.app_id, epr.role_app_id"
+                    + " from fn_role fr, ep_app_function ep, ep_app_role_function epr"
+                    + " where fr.role_id = epr.role_id and ep.function_cd = epr.function_cd and ep.app_id = epr.app_id and  epr.app_id = :appId and epr.role_app_id = 1";
+            List<GlobalRoleWithApplicationRoleFunction> globalRoleFuncs = entityManager
+                .createQuery(getBulkUploadPartnerGlobalRoleFunctions)
+                .setParameter("appId", app.getId())
+                .getResultList();
+            ObjectMapper mapper = new ObjectMapper();
+            HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+            for (GlobalRoleWithApplicationRoleFunction globalRoleFunc : globalRoleFuncs) {
+                ExternalAccessRolePerms extRolePerms;
+                ExternalAccessPerms extPerms;
+                String type = "";
+                String instance = "";
+                String action = "";
+                if (globalRoleFunc.getFunctionCd().contains(FUNCTION_PIPE)) {
+                    type = EcompPortalUtils.getFunctionType(globalRoleFunc.getFunctionCd());
+                    instance = EcompPortalUtils.getFunctionCode(globalRoleFunc.getFunctionCd());
+                    action = EcompPortalUtils.getFunctionAction(globalRoleFunc.getFunctionCd());
+                } else {
+                    type = globalRoleFunc.getFunctionCd().contains("menu") ? "menu" : "url";
+                    instance = globalRoleFunc.getFunctionCd();
+                    action = "*";
+                }
+                extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + type, instance, action);
+                extRolePerms = new ExternalAccessRolePerms(extPerms,
+                    portalApp.getAuthNamespace() + "." + globalRoleFunc.getRoleName().replaceAll(
+                        EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+                String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+                HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+                updateRoleFunctionInExternalSystem(updateRolePerms, entity);
+                roleFunctions++;
+            }
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "HttpClientErrorException - Failed to add role function in external central auth system", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+            throw e;
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "bulkUploadGlobalRoleFunctions: Failed to add role fucntion in external central auth system", e);
+            throw e;
+        }
+        return roleFunctions;
+    }
+
+    private void updateRoleFunctionInExternalSystem(String updateRolePerms, HttpEntity<String> entity) {
+        logger.debug(EELFLoggerDelegate.debugLogger, "bulkUploadRoleFunc: {} for POST: {}",
+            CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRolePerms);
+        ResponseEntity<String> addPermResponse = template.exchange(
+            SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role/perm",
+            HttpMethod.POST, entity, String.class);
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "bulkUploadRoleFunc: Finished adding permission for POST: {} and status code: {} ",
+            addPermResponse.getStatusCode().value(), updateRolePerms);
+    }
+
+    public List<String> getMenuFunctionsList(String uebkey) throws Exception {
+        List<String> appMenuFunctionsList = null;
+        List<String> appMenuFunctionsFinalList = new ArrayList<>();
+        try {
+            FnApp app = getApp(uebkey).get(0);
+            String getMenuFunctions = "select f.function_cd from ep_app_function f"
+                + " where f.app_id =:appId"
+                + " UNION"
+                + " select epa.function_cd from fn_role fnr, ep_app_role_function epr, ep_app_function epa where epr.role_id = fnr.role_id"
+                + " and epa.function_cd = epr.function_cd and fnr.role_name like 'global%' and fnr.app_id is null and epr.app_id = 1";
+            appMenuFunctionsList = entityManager.createQuery(getMenuFunctions).setParameter(APP_ID, app.getId())
+                .getResultList();
+            for (String appMenuFunction : appMenuFunctionsList) {
+                if (appMenuFunction.contains(FUNCTION_PIPE)) {
+                    appMenuFunctionsFinalList.add(EcompPortalUtils.getFunctionCode(appMenuFunction));
+                } else {
+                    appMenuFunctionsFinalList.add(appMenuFunction);
+                }
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getMenuFunctionsList: Failed", e);
+            return appMenuFunctionsFinalList;
+        }
+        return appMenuFunctionsFinalList;
+    }
+
+    public List<EcompUser> getAllAppUsers(String uebkey) throws Exception {
+        List<String> usersList = new ArrayList<>();
+        List<EcompUser> usersfinalList = new ArrayList<>();
+        try {
+            FnApp app = getApp(uebkey).get(0);
+            String ApplicationUserRoles =
+                "select distinct fu.org_id, fu.manager_id, fu.first_name, fu.middle_name, fu.last_name, fu.phone, fu.email, fu.hrid, fu.org_user_id, fu.org_code, fu.org_manager_userid, fu.job_title, fu.login_id, \n"
+                    + " fu.active_yn , fr.app_role_id, fr.role_name, epr.function_cd , epf.function_name\n"
+                    + " from fn_user fu, fn_role fr, fn_user_role fur, ep_app_role_function epr , ep_app_function epf\n"
+                    + " where fu.user_id = fur.user_id and fu.active_yn='Y' and fur.role_id = fr.role_id and fr.app_id =:appId and fr.active_yn='Y' and epr.function_cd= epf.function_cd and epf.app_id=epr.app_id and fur.role_id=epr.role_id\n"
+                    + " union\n"
+                    + " select distinct fu.org_id, fu.manager_id, fu.first_name, fu.middle_name, fu.last_name, fu.phone, fu.email, fu.hrid, fu.org_user_id, fu.org_code, fu.org_manager_userid, fu.job_title, \n"
+                    + " fu.login_id, fu.active_yn , fr.role_id, fr.role_name, earf.function_cd , eaf.function_name\n"
+                    + " from fn_user_role a, fn_role fr, fn_user fu , ep_app_role_function earf, ep_app_function eaf\n"
+                    + " where a.role_id in (select b.role_id from ep_app_role_function b where b.role_app_id = 1 and b.app_id =:appId) and a.user_id =fu.user_id and a.role_id = fr.role_id and fr.active_yn='Y' and fu.active_yn='Y'\n"
+                    + " and earf.role_id = a.role_id and earf.function_cd = eaf.function_cd and earf.app_id = eaf.app_id  and earf.role_app_id = 1 and fr.active_yn='Y' and fu.active_yn='Y'";
+
+            List<EcompUserRoles> userList = entityManager.createQuery(ApplicationUserRoles)
+                .setParameter("appId", app.getId()).getResultList();
+            for (EcompUserRoles ecompUserRole : userList) {
+                boolean found = false;
+                Set<EcompRole> roles = null;
+                for (EcompUser user : usersfinalList) {
+                    if (user.getOrgUserId().equals(ecompUserRole.getOrgUserId())) {
+                        EcompRole ecompRole = new EcompRole();
+                        ecompRole.setId(ecompUserRole.getRoleId());
+                        ecompRole.setName(ecompUserRole.getRoleName());
+                        roles = user.getRoles();
+                        EcompRole role = roles.stream().filter(x -> x.getName().equals(ecompUserRole.getRoleName()))
+                            .findAny().orElse(null);
+                        SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
+                        if (role != null) {
+                            roleFunctionSet = (SortedSet<EcompRoleFunction>) role.getRoleFunctions();
+                        }
+                        String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
+                        functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+                        EcompRoleFunction epRoleFunction = new EcompRoleFunction();
+                        epRoleFunction.setName(ecompUserRole.getFunctionName());
+                        epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
+                        epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
+                        epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
+                        roleFunctionSet.add(epRoleFunction);
+                        ecompRole.setRoleFunctions(roleFunctionSet);
+                        roles.add(ecompRole);
+                        user.setRoles(roles);
+                        found = true;
+                        break;
+                    }
+                }
+                if (!found) {
+                    EcompUser epUser = new EcompUser();
+                    epUser.setOrgId(ecompUserRole.getOrgId());
+                    epUser.setManagerId(ecompUserRole.getManagerId());
+                    epUser.setFirstName(ecompUserRole.getFirstName());
+                    epUser.setLastName(ecompUserRole.getLastName());
+                    epUser.setPhone(ecompUserRole.getPhone());
+                    epUser.setEmail(ecompUserRole.getEmail());
+                    epUser.setOrgUserId(ecompUserRole.getOrgUserId());
+                    epUser.setOrgCode(ecompUserRole.getOrgCode());
+                    epUser.setOrgManagerUserId(ecompUserRole.getOrgManagerUserId());
+                    epUser.setJobTitle(ecompUserRole.getJobTitle());
+                    epUser.setLoginId(ecompUserRole.getLoginId());
+                    epUser.setActive(true);
+                    roles = new HashSet<>();
+                    EcompRole ecompRole = new EcompRole();
+                    ecompRole.setId(ecompUserRole.getRoleId());
+                    ecompRole.setName(ecompUserRole.getRoleName());
+                    SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
+                    String functionCode = EcompPortalUtils.getFunctionCode(ecompUserRole.getFunctionCode());
+                    functionCode = EPUserUtils.decodeFunctionCode(functionCode);
+                    EcompRoleFunction epRoleFunction = new EcompRoleFunction();
+                    epRoleFunction.setName(ecompUserRole.getFunctionName());
+                    epRoleFunction.setCode(EPUserUtils.decodeFunctionCode(functionCode));
+                    epRoleFunction.setType(getFunctionCodeType(ecompUserRole.getFunctionCode()));
+                    epRoleFunction.setAction(getFunctionCodeAction(ecompUserRole.getFunctionCode()));
+                    roleFunctionSet.add(epRoleFunction);
+                    ecompRole.setRoleFunctions(roleFunctionSet);
+                    roles.add(ecompRole);
+                    epUser.setRoles(roles);
+                    usersfinalList.add(epUser);
+                }
+            }
+            ObjectMapper mapper = new ObjectMapper();
+            for (EcompUser u1 : usersfinalList) {
+                String str = mapper.writeValueAsString(u1);
+                usersList.add(str);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getAllUsers failed", e);
+            throw e;
+        }
+        return usersfinalList;
+    }
+
+    public List<EcompRole> missingUserApplicationRoles(String uebkey, String loginId, Set<EcompRole> CurrentUserRoles)
+        throws Exception {
+        List<FnApp> appList = getApp(uebkey);
+        FnApp app = appList.get(0);
+        List<FnUser> epUserList;
+        epUserList = getUser(loginId);
+        List<EcompRole> missingUserAppRoles = new ArrayList<>();
+        List<String> roleNamesList = CurrentUserRoles.stream().map(EcompRole::getName).collect(Collectors.toList());
+        logger.debug(EELFLoggerDelegate.debugLogger, "Roles of User from hibernate :" + roleNamesList);
+        List<EcompRole> userApplicationsRolesfromDB = getUserAppRoles(app, epUserList.get(0));
+        if (userApplicationsRolesfromDB.size() > 0) {
+            missingUserAppRoles = userApplicationsRolesfromDB.stream().filter(x -> !roleNamesList.contains(x.getName()))
+                .collect(Collectors.toList());
+        }
+        List<String> missingroleNamesList = missingUserAppRoles.stream().map(EcompRole::getName)
+            .collect(Collectors.toList());
+        logger.debug(EELFLoggerDelegate.debugLogger, "MissingUserAppRoles():" + missingroleNamesList);
+
+        List<EcompRole> finalMissingRoleList = new ArrayList<>();
+        if (missingUserAppRoles.size() > 0) {
+            final Map<String, Long> params = new HashMap<>();
+            for (EcompRole role : missingUserAppRoles) {
+                EcompRole epRole = new EcompRole();
+                epRole.setId(role.getId());
+                epRole.setName(role.getName());
+                String getAppRoleFunctionList =
+                    "SELECT DISTINCT f.app_id , f.function_cd, f.function_name from ep_app_role_function rf, ep_app_function f"
+                        + " where rf.role_id =:roleId and rf.app_id =:appId and rf.app_id = f.app_id and rf.function_cd = f.function_cd";
+                List<EpAppFunction> appRoleFunctionList = entityManager.createQuery(getAppRoleFunctionList)
+                    .setParameter("roleId", role.getId()).setParameter(APP_ID, app.getId()).getResultList();
+                SortedSet<EcompRoleFunction> roleFunctionSet = new TreeSet<>();
+                for (EpAppFunction roleFunc : appRoleFunctionList) {
+                    String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
+                    String type = getFunctionCodeType(roleFunc.getFunctionCd());
+                    String action = getFunctionCodeAction(roleFunc.getFunctionCd());
+                    EcompRoleFunction fun = new EcompRoleFunction();
+                    fun.setAction(action);
+                    fun.setCode(functionCode);
+                    fun.setType(type);
+                    fun.setName(roleFunc.getFunctionName());
+                    roleFunctionSet.add(fun);
+
+                }
+                epRole.setRoleFunctions(roleFunctionSet);
+                finalMissingRoleList.add(epRole);
+            }
+        }
+
+        return finalMissingRoleList;
+    }
+
+    private List<EcompRole> getUserAppRoles(FnApp app, FnUser user) {
+        String getUserAppCurrentRoles = "select distinct fu.role_id, fr.user_id, fu.role_name, fu.priority from fn_role fu left outer join fn_user_role fr ON fu.role_id = fr.role_id and fu.app_id = fr.app_id and fr.role_id != 999 where fu.app_id =:appId and fr.user_id =:userId and fu.active_yn='Y' \n";
+        List<EPUserAppCurrentRoles> userAppsRolesList = entityManager.createQuery(getUserAppCurrentRoles)
+            .setParameter("appId", app.getId())
+            .setParameter("userId", user.getId())
+            .getResultList();
+        List<EcompRole> setUserRoles = new ArrayList<>();
+        for (EPUserAppCurrentRoles role : userAppsRolesList) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userRolename = {}",
+                role.getRoleName());
+            EcompRole ecompRole = new EcompRole();
+            ecompRole.setId(role.getRoleId());
+            ecompRole.setName(role.getRoleName());
+            setUserRoles.add(ecompRole);
+        }
+        logger.debug(EELFLoggerDelegate.debugLogger, "In getUserAppRoles()- get userrole list size = {}",
+            setUserRoles.size());
+        return setUserRoles;
+    }
+
+    public List<FnUser> getUser(String loginId) throws InvalidUserException {
+        List<FnUser> userList = fnUserService.getUserWithOrgUserId(loginId);
+        if (userList.isEmpty()) {
+            throw new InvalidUserException("User not found");
+        }
+        return userList;
+    }
+
+    @Transactional(propagation = Propagation.REQUIRED)
+    public ExternalRequestFieldsValidator deleteDependencyRoleRecord(Long roleId, String uebkey, String LoginId)
+        throws Exception {
+        String message = "";
+        boolean response = false;
+        FnApp app = null;
+        try {
+            List<FnRole> epRoleList = null;
+            app = getApp(uebkey).get(0);
+            if (app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                epRoleList = getPortalAppRoleInfo(roleId);
+            } else {
+                epRoleList = getPartnerAppRoleInfo(roleId, app.getId());
+            }
+            if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                // Delete User Role in External System before deleting role
+                deleteUserRoleInExternalSystem(epRoleList.get(0), app, LoginId);
+            }
+            // Delete user app roles
+            fnRoleService.delete(epRoleList.get(0));
+            boolean isPortalRequest = false;
+            deleteRoleDependencyRecords(epRoleList.get(0).getId(), app.getId(), isPortalRequest);
+            if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                // Final call to delete role once all dependencies has been
+                // deleted
+                deleteRoleInExternalAuthSystem(epRoleList, app);
+            }
+            fnRoleService.delete(epRoleList.get(0));
+            logger.debug(EELFLoggerDelegate.debugLogger, "deleteDependencyRoleRecord: committed the transaction");
+            response = true;
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord: HttpClientErrorException", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+            message = e.getMessage();
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteDependencyRoleRecord failed", e);
+            message = e.getMessage();
+        }
+        return new ExternalRequestFieldsValidator(response, message);
+    }
+
+    @Transactional(propagation = Propagation.REQUIRED)
+    public void deleteRoleDependencyRecords(Long roleId, Long appId, boolean isPortalRequest)
+        throws Exception {
+        try {
+            String sql = "";
+            Query query = null;
+            // It should delete only when it portal's roleId
+            if (appId.equals(PortalConstants.PORTAL_APP_ID)) {
+                // Delete from fn_role_function
+                sql = "DELETE FROM fn_role_function WHERE role_id=" + roleId;
+                logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+                query = entityManager.createQuery(sql);
+                query.executeUpdate();
+                // Delete from fn_role_composite
+                sql = "DELETE FROM fn_role_composite WHERE parent_role_id=" + roleId + " OR child_role_id=" + roleId;
+                logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+                query = entityManager.createQuery(sql);
+                query.executeUpdate();
+            }
+            // Delete from ep_app_role_function
+            sql = "DELETE FROM ep_app_role_function WHERE role_id=" + roleId;
+            logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+            query = entityManager.createQuery(sql);
+            query.executeUpdate();
+            // Delete from ep_role_notification
+            sql = "DELETE FROM ep_role_notification WHERE role_id=" + roleId;
+            logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+            query = entityManager.createQuery(sql);
+            query.executeUpdate();
+            // Delete from fn_user_pseudo_role
+            sql = "DELETE FROM fn_user_pseudo_role WHERE pseudo_role_id=" + roleId;
+            logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+            query = entityManager.createQuery(sql);
+            query.executeUpdate();
+            // Delete form EP_WIDGET_CATALOG_ROLE
+            sql = "DELETE FROM EP_WIDGET_CATALOG_ROLE WHERE role_id=" + roleId;
+            logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+            query = entityManager.createQuery(sql);
+            query.executeUpdate();
+            // Delete form EP_WIDGET_CATALOG_ROLE
+            sql = "DELETE FROM ep_user_roles_request_det WHERE requested_role_id=" + roleId;
+            logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+            query = entityManager.createQuery(sql);
+            query.executeUpdate();
+            if (!isPortalRequest) {
+                // Delete form fn_menu_functional_roles
+                sql = "DELETE FROM fn_menu_functional_roles WHERE role_id=" + roleId;
+                logger.debug(EELFLoggerDelegate.debugLogger, "Executing query: " + sql);
+                query = entityManager.createQuery(sql);
+                query.executeUpdate();
+            }
+        } catch (Exception e) {
+            logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleDependeciesRecord: failed ", e);
+            throw new DeleteDomainObjectFailedException("delete Failed" + e.getMessage());
+        }
+    }
+
+    private void deleteUserRoleInExternalSystem(FnRole role, FnApp app, String LoginId) throws Exception {
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        HttpEntity<String> entity = new HttpEntity<>(headers);
+        getNameSpaceIfExists(app);
+        logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
+            CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+        ResponseEntity<String> getResponse = template.exchange(
+            SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
+                + LoginId
+                + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
+                + "/" + app.getAuthNamespace() + "."
+                + role.getRoleName()
+                .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+            HttpMethod.GET, entity, String.class);
+        logger.debug(EELFLoggerDelegate.debugLogger,
+            "deleteUserRoleInExternalSystem: Finished GET user roles from External Auth system and response: {} ",
+            getResponse.getBody());
+        if (getResponse.getStatusCode().value() != 200) {
+            throw new ExternalAuthSystemException(getResponse.getBody());
+        }
+        String res = getResponse.getBody();
+        if (!res.equals(IS_EMPTY_JSON_STRING)) {
+            HttpEntity<String> userRoleentity = new HttpEntity<>(headers);
+            logger.debug(EELFLoggerDelegate.debugLogger, "deleteUserRoleInExternalSystem: {} ",
+                CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+            ResponseEntity<String> deleteResponse = template.exchange(
+                SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole/"
+                    + LoginId
+                    + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)
+                    + "/" + app.getAuthNamespace() + "."
+                    + role.getRoleName().replaceAll(
+                    EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"),
+                HttpMethod.DELETE, userRoleentity, String.class);
+            if (deleteResponse.getStatusCode().value() != 200) {
+                throw new ExternalAuthSystemException("Failed to delete user role");
+            }
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "deleteUserRoleInExternalSystem: Finished deleting user role in External Auth system and status code: {} ",
+                deleteResponse.getStatusCode().value());
+        }
+    }
+
+    public Integer bulkUploadUsersSingleRole(String uebkey, Long roleId, String modifiedRoleName) throws Exception {
+        FnApp app = getApp(uebkey).get(0);
+        List<BulkUploadUserRoles> userRolesList;
+        Integer userRolesAdded = 0;
+        if (app.getAuthCentral()) {
+            userRolesList = bulkUploadUserRolesService.getBulkUsersForSingleRole(app.getUebKey(), roleId);
+            for (BulkUploadUserRoles userRolesUpload : userRolesList) {
+                userRolesUpload.setRoleName(modifiedRoleName);
+                if (!userRolesUpload.getOrgUserId().equals("su1234")) {
+                    addUserRoleInExternalSystem(userRolesUpload);
+                    userRolesAdded++;
+                }
+            }
+        }
+        return userRolesAdded;
+    }
+
+    private void addUserRoleInExternalSystem(BulkUploadUserRoles userRolesUpload) {
+        try {
+            String name = "";
+            ObjectMapper mapper = new ObjectMapper();
+            if (EPCommonSystemProperties
+                .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+                name = userRolesUpload.getOrgUserId()
+                    + SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+            }
+            ExternalAccessUser extUser = new ExternalAccessUser(name,
+                userRolesUpload.getAppNameSpace() + "." + userRolesUpload.getRoleName()
+                    .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+            String userRole = mapper.writeValueAsString(extUser);
+            HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+            HttpEntity<String> entity = new HttpEntity<>(userRole, headers);
+            template.exchange(
+                SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "userRole",
+                HttpMethod.POST, entity, String.class);
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "HttpClientErrorException - Failed to addUserRoleInExternalSystem", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+        } catch (Exception e) {
+            if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "addUserRoleInExternalSystem: UserRole already exits but does not break functionality");
+            } else {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "addUserRoleInExternalSystem: Failed to addUserRoleInExternalSystem", e);
+            }
+        }
+    }
+
+    private void addNewRoleInExternalSystem(List<FnRole> newRole, FnApp app)
+        throws Exception {
+        try {
+            HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+            ObjectMapper mapper = new ObjectMapper();
+            String addNewRole;
+            ExternalAccessRole extRole = new ExternalAccessRole();
+            extRole.setName(app.getAuthNamespace() + "." + newRole.get(0).getRoleName()
+                .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+            extRole.setDescription(String.valueOf(newRole.get(0).getRoleName()));
+            addNewRole = mapper.writeValueAsString(extRole);
+            HttpEntity<String> postEntity = new HttpEntity<>(addNewRole, headers);
+            logger.debug(EELFLoggerDelegate.debugLogger, "addNewRoleInExternalSystem: {} for POST: {} ",
+                CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addNewRole);
+            ResponseEntity<String> addNewRoleInExternalSystem = template.exchange(
+                SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "role",
+                HttpMethod.POST, postEntity, String.class);
+            if (addNewRoleInExternalSystem.getStatusCode().value() == 201) {
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    "addNewRoleInExternalSystem: Finished adding into External Auth system for POST: {} and status code: {}",
+                    addNewRole, addNewRoleInExternalSystem.getStatusCode().value());
+            }
+        } catch (HttpClientErrorException ht) {
+            fnRoleService.delete(newRole.get(0));
+            logger.error(EELFLoggerDelegate.debugLogger,
+                "addNewRoleInExternalSystem: Failed to add in External Auth system and status code: {}", ht);
+            throw new HttpClientErrorException(ht.getStatusCode());
+        }
+    }
+
+    private void checkIfRoleExitsInExternalSystem(Role checkRole, FnApp app) throws Exception {
+        getNameSpaceIfExists(app);
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        String roleName = app.getAuthNamespace() + "." + checkRole.getName()
+            .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_");
+        HttpEntity<String> checkRoleEntity = new HttpEntity<>(headers);
+        logger.debug(EELFLoggerDelegate.debugLogger, "checkIfRoleExitsInExternalSystem: {} ",
+            CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE);
+        ResponseEntity<String> checkRoleInExternalSystem = template
+            .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "roles/"
+                + roleName, HttpMethod.GET, checkRoleEntity, String.class);
+        if (!checkRoleInExternalSystem.getBody().equals(IS_EMPTY_JSON_STRING)) {
+            logger.debug(
+                "checkIfRoleExitsInExternalSystem: Role already exists in external system {} and status code: {} ",
+                checkRoleInExternalSystem.getBody(), checkRoleInExternalSystem.getStatusCode().value());
+            throw new ExternalAuthSystemException(" Role already exists in external system");
+        }
+    }
+
+    public ResponseEntity<String> getNameSpaceIfExists(FnApp app) throws Exception {
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        HttpEntity<String> entity = new HttpEntity<>(headers);
+        logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Connecting to External Auth system");
+        ResponseEntity<String> response = null;
+        try {
+            response = template
+                .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                    + "nss/" + app.getAuthNamespace(), HttpMethod.GET, entity, String.class);
+            logger.debug(EELFLoggerDelegate.debugLogger, "checkIfNameSpaceExists: Finished ",
+                response.getStatusCode().value());
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "checkIfNameSpaceExists failed", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+            if (e.getStatusCode() == HttpStatus.NOT_FOUND) {
+                throw new InvalidApplicationException("Invalid NameSpace");
+            } else {
+                throw e;
+            }
+        }
+        return response;
+    }
+
+    private FnRoleFunction createCentralRoleFunctionForGlobalRole(GlobalRoleWithApplicationRoleFunction role) {
+        String instance;
+        String type;
+        String action;
+        FnRoleFunction cenRoleFun = null;
+        if (role.getFunctionCd().contains(FUNCTION_PIPE)) {
+            instance = EcompPortalUtils.getFunctionCode(role.getFunctionCd());
+            type = EcompPortalUtils.getFunctionType(role.getFunctionCd());
+            action = EcompPortalUtils.getFunctionAction(role.getFunctionCd());
+            cenRoleFun = FnRoleFunction.builder().build();
+            FnRole fnRole = new FnRole();
+            FnFunction fnFunction = FnFunction.builder().functionCd(instance).name(role.getFunctionName()).type(type)
+                .action(action).build();
+            cenRoleFun.setRole(fnRole);
+            cenRoleFun.setFunctionCd(fnFunction);
+        } else {
+            type = getFunctionCodeType(role.getFunctionCd());
+            action = getFunctionCodeAction(role.getFunctionCd());
+            FnFunction fnFunction = FnFunction.builder().functionCd(role.getFunctionCd()).name(role.getFunctionName())
+                .type(type).action(action).build();
+            cenRoleFun.setRole(new FnRole());
+            cenRoleFun.setFunctionCd(fnFunction);
+        }
+        return cenRoleFun;
+    }
+
+    public CentralUser getUserRoles(String loginId, String uebkey) throws Exception {
+        CentralUser sendUserRoles = null;
+        try {
+            CentralV2User cenV2User = getV2UserAppRoles(loginId, uebkey);
+            sendUserRoles = convertV2UserRolesToOlderVersion(cenV2User);
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getUserRoles: failed", e);
+            throw e;
+        }
+        return sendUserRoles;
+    }
+
+    private CentralV2User getV2UserAppRoles(String loginId, String uebkey) throws Exception {
+        FnApp app;
+        List<FnApp> appList = getApp(uebkey);
+        app = appList.get(0);
+        FnUser user = fnUserService.loadUserByUsername(loginId);
+        Set<FnUserRole> userAppSet = user.getUserApps();
+        return createEPUser(user, userAppSet, app);
+    }
+
+    public List<FnApp> getApp(String uebkey) throws Exception {
+        List<FnApp> app = null;
+        try {
+            app = fnAppService.getByUebKey(uebkey);
+            if (!app.isEmpty() && !app.get(0).getEnabled()
+                && !app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                throw new InactiveApplicationException("Application:" + app.get(0).getAppName() + " is Unavailable");
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getApp: failed", e);
+            throw e;
+        }
+        return app;
+    }
+
+    private CentralV2User createEPUser(FnUser userInfo, Set<FnUserRole> userAppSet, FnApp app) {
+        CentralV2User userAppList = CentralV2User.builder().build();
+        CentralV2User user1;
+        List<FnRole> globalRoleList = new ArrayList<>();
+        try {
+            if (!app.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                globalRoleList = fnRoleService.userAppGlobalRoles(userInfo.getId(), app.getId());
+            }
+            userAppList.setUserApps(new TreeSet<>());
+            for (FnUserRole userApp : userAppSet) {
+                if (userApp.getRoleId().getActiveYn()) {
+                    FnApp epApp = userApp.getFnAppId();
+                    String globalRole = userApp.getRoleId().getRoleName().toLowerCase();
+                    if (((epApp.getId().equals(app.getId()))
+                        && (!userApp.getRoleId().getId().equals(PortalConstants.ACCOUNT_ADMIN_ROLE_ID)))
+                        || ((epApp.getId().equals(PortalConstants.PORTAL_APP_ID))
+                        && (globalRole.toLowerCase().startsWith("global_")))) {
+                        CentralV2UserApp cua = new CentralV2UserApp();
+                        cua.setUserId(null);
+                        CentralApp cenApp = CentralApp.builder().id(1L).created(epApp.getCreated())
+                            .modified(epApp.getModified()).createdId(epApp.getId())
+                            .modifiedId(epApp.getModifiedId().getId()).rowNum(epApp.getRowNum())
+                            .name(epApp.getAppName()).imageUrl(epApp.getAppImageUrl())
+                            .description(epApp.getAppDescription()).notes(epApp.getAppNotes())
+                            .url(epApp.getAppUrl()).alternateUrl(epApp.getAppAlternateUrl())
+                            .restEndpoint(epApp.getAppRestEndpoint()).mlAppName(epApp.getMlAppName())
+                            .mlAppAdminId(epApp.getMlAppAdminId()).motsId(String.valueOf(epApp.getMotsId()))
+                            .appPassword(epApp.getAppPassword()).open(String.valueOf(epApp.getOpen()))
+                            .enabled(String.valueOf(epApp.getEnabled())).thumbnail(epApp.getThumbnail())
+                            .username(epApp.getAppUsername()).uebKey(epApp.getUebKey())
+                            .uebSecret(epApp.getUebSecret()).uebTopicName(epApp.getUebTopicName())
+                            .build();
+                        cenApp.setAppPassword(EPCommonSystemProperties.APP_DISPLAY_PASSWORD);
+                        cua.setApp(cenApp);
+                        Long appId = null;
+                        if (globalRole.toLowerCase().startsWith("global_")
+                            && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)
+                            && !epApp.getId().equals(app.getId())) {
+                            appId = app.getId();
+                            FnRole result = null;
+                            if (globalRoleList.size() > 0) {
+                                result = globalRoleList.stream()
+                                    .filter(x -> userApp.getRoleId().getId().equals(x.getId())).findAny()
+                                    .orElse(null);
+                            }
+                            if (result == null) {
+                                continue;
+                            }
+                        } else {
+                            appId = userApp.getFnAppId().getId();
+                        }
+                        List<EpAppFunction> appRoleFunctionList = epAppFunctionService
+                            .getAppRoleFunctionList(userApp.getRoleId().getId(), appId);
+                        SortedSet<EpAppFunction> roleFunctionSet = new TreeSet<>();
+                        for (EpAppFunction roleFunc : appRoleFunctionList) {
+                            String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getFunctionCd());
+                            String type = getFunctionCodeType(roleFunc.getFunctionCd());
+                            String action = getFunctionCodeAction(roleFunc.getFunctionCd());
+                            EpAppFunction cenRoleFunc = new EpAppFunction(roleFunc.getId(),
+                                functionCode, roleFunc.getFunctionName(), null, type, action, null);
+                            roleFunctionSet.add(cenRoleFunc);
+                        }
+                        Long userRoleId;
+                        if (globalRole.toLowerCase().startsWith("global_")
+                            || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                            userRoleId = userApp.getRoleId().getId();
+                        } else {
+                            userRoleId = userApp.getRoleId().getAppRoleId();
+                        }
+                        CentralV2Role cenRole = CentralV2Role.builder().id(userRoleId)
+                            .created(userApp.getRoleId().getCreated()).modified(userApp.getRoleId().getModified())
+                            .createdId(userApp.getRoleId().getCreatedId().getId())
+                            .modifiedId(userApp.getRoleId().getModifiedId().getId())
+                            .rowNum(userApp.getRoleId().getRowNum()).name(userApp.getRoleId().getRoleName())
+                            .active(userApp.getRoleId().getActiveYn()).priority(userApp.getRoleId().getPriority())
+                            //.roleFunctions(roleFunctionSet).setChildRoles(null).setParentRoles(null)
+                            .build();
+                        cua.setRole(cenRole);
+                        userAppList.getUserApps().add(cua);
+                    }
+                }
+            }
+            user1 = CentralV2User.builder().id(null).created(userInfo.getCreated())
+                .modified(userInfo.getModified()).createdId(userInfo.getCreatedId().getId())
+                .modifiedId(userInfo.getModifiedId().getId()).rowNum(userInfo.getRowNum())
+                .orgId(userInfo.getOrgId().getOrgId()).managerId(userInfo.getOrgManagerUserId())
+                .firstName(userInfo.getFirstName()).middleInitial(userInfo.getMiddleName())
+                .lastName(userInfo.getLastName()).phone(userInfo.getPhone()).fax(userInfo.getFax())
+                .cellular(userInfo.getCellular()).email(userInfo.getEmail())
+                .addressId(userInfo.getAddressId()).alertMethodCd(userInfo.getAlertMethodCd().getAlertMethodCd())
+                .hrid(userInfo.getHrid()).orgUserId(userInfo.getOrgUserId()).orgCode(userInfo.getOrgCode())
+                .address1(userInfo.getAddressLine1()).address2(userInfo.getAddressLine2()).city(userInfo.getCity())
+                .state(userInfo.getStateCd()).zipCode(userInfo.getZipCode()).country(userInfo.getCountryCd())
+                .orgManagerUserId(userInfo.getOrgManagerUserId()).locationClli(userInfo.getLocationClli())
+                .businessCountryCode(userInfo.getBusinessUnit())
+                .businessCountryName(userInfo.getBusinessUnitName())
+                .businessUnit(userInfo.getBusinessUnit()).businessUnitName(userInfo.getBusinessUnitName())
+                .department(userInfo.getDepartment()).departmentName(userInfo.getDepartmentName())
+                .companyCode(userInfo.getOrgCode()).company(userInfo.getCompany())
+                .zipCodeSuffix(userInfo.getZipCode()).jobTitle(userInfo.getJobTitle())
+                //.commandChain(userInfo.getCommandChain()).siloStatus(userInfo.getSiloStatus())
+                .costCenter(userInfo.getCostCenter()).financialLocCode(userInfo.getFinLocCode())
+                .loginId(userInfo.getLoginId()).loginPwd(userInfo.getLoginPwd())
+                .lastLoginDate(userInfo.getLastLoginDate()).active(userInfo.getActiveYn())
+                //.internal(userInfo.getIsInternalYn()).selectedProfileId(userInfo.getSelectedProfileId())
+                //.timeZoneId(userInfo.getTimezone().getTimezoneId()).online(userInfo.isOnline())
+                //.chatId(userInfo.getChatId()).setUserApps(userAppList.getUserApps()).setPseudoRoles(null)
+                .build();
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "createEPUser: createEPUser failed", e);
+            throw e;
+        }
+        return user1;
+    }
+
+    private CentralUser convertV2UserRolesToOlderVersion(CentralV2User cenV2User) {
+        Set<CentralV2UserApp> userV2Apps = cenV2User.getUserApps();
+        Set<CentralUserApp> userApps = new TreeSet<>();
+        for (CentralV2UserApp userApp : userV2Apps) {
+            CentralApp app = userApp.getApp();
+            CentralUserApp cua = new CentralUserApp();
+            cua.setUserId(null);
+            cua.setApp(app);
+            SortedSet<EpAppFunction> cenRoleFunction = new TreeSet<>();
+            for (DomainVo vo : userApp.getRole().getRoleFunctions()) {
+                Optional<EpAppFunction> epApp = epAppFunctionService.getForId(vo.getId());
+                if (epApp.isPresent()) {
+                    EpAppFunction cenRoleFunc = EpAppFunction.builder().functionCd(epApp.get().getFunctionCd())
+                        .functionName(
+                            epApp.get().getFunctionName()).build();
+                    cenRoleFunction.add(cenRoleFunc);
+                }
+            }
+            CentralRole role = new CentralRole(userApp.getRole().getId(), userApp.getRole().getName(),
+                userApp.getRole().isActive(), userApp.getRole().getPriority(), cenRoleFunction);
+            cua.setRole(role);
+            userApps.add(cua);
+        }
+        return CentralUser.builder().id(cenV2User.getId()).created(cenV2User.getCreated())
+            .modified(cenV2User.getModified()).createdId(cenV2User.getCreatedId())
+            .modifiedId(cenV2User.getModifiedId()).rowNum(cenV2User.getRowNum())
+            .orgId(cenV2User.getOrgId()).managerId(cenV2User.getManagerId())
+            .firstName(cenV2User.getFirstName()).middleInitial(cenV2User.getMiddleInitial())
+            .lastName(cenV2User.getLastName()).phone(cenV2User.getPhone()).fax(cenV2User.getFax())
+            .cellular(cenV2User.getCellular()).email(cenV2User.getEmail())
+            .addressId(cenV2User.getAddressId()).alertMethodCd(cenV2User.getAlertMethodCd())
+            .hrid(cenV2User.getHrid()).orgUserId(cenV2User.getOrgUserId()).orgCode(cenV2User.getOrgCode())
+            .address1(cenV2User.getAddress1()).address2(cenV2User.getAddress2()).city(cenV2User.getCity())
+            .state(cenV2User.getState()).zipCode(cenV2User.getZipCode()).country(cenV2User.getCountry())
+            .orgManagerUserId(cenV2User.getOrgManagerUserId()).locationClli(cenV2User.getLocationClli())
+            .businessCountryCode(cenV2User.getBusinessCountryCode())
+            .businessCountryName(cenV2User.getBusinessCountryName()).businessUnit(cenV2User.getBusinessUnit())
+            .businessUnitName(cenV2User.getBusinessUnitName()).department(cenV2User.getDepartment())
+            .departmentName(cenV2User.getDepartmentName()).companyCode(cenV2User.getCompanyCode())
+            .company(cenV2User.getCompany()).zipCodeSuffix(cenV2User.getZipCodeSuffix())
+            .jobTitle(cenV2User.getJobTitle()).commandChain(cenV2User.getCommandChain())
+            .siloStatus(cenV2User.getSiloStatus()).costCenter(cenV2User.getCostCenter())
+            .financialLocCode(cenV2User.getFinancialLocCode()).loginId(cenV2User.getLoginId())
+            .loginPwd(cenV2User.getLoginPwd()).lastLoginDate(cenV2User.getLastLoginDate())
+            .active(cenV2User.isActive()).internal(cenV2User.isInternal())
+            .selectedProfileId(cenV2User.getSelectedProfileId()).timeZoneId(cenV2User.getTimeZoneId())
+            .online(cenV2User.isOnline()).chatId(cenV2User.getChatId()).userApps(userApps).build();
+    }
+
+    public CentralV2Role getRoleInfo(final Long roleId, final String uebkey) throws Exception {
+        List<CentralV2Role> roleList = new ArrayList<>();
+        CentralV2Role cenRole = CentralV2Role.builder().build();
+        List<FnRole> roleInfo;
+        List<FnApp> app;
+        try {
+            app = getApp(uebkey);
+            if (app.isEmpty()) {
+                throw new InactiveApplicationException("Application not found");
+            }
+            if (!app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                List<FnRole> globalRoleList = getGlobalRolesOfPortal();
+                if (globalRoleList.size() > 0) {
+                    FnRole result = globalRoleList.stream().filter(x -> roleId.equals(x.getId())).findAny()
+                        .orElse(null);
+                    if (result != null) {
+                        return getGlobalRoleForRequestedApp(app.get(0).getId(), roleId);
+                    }
+                }
+            }
+            if (app.get(0).getId().equals(PortalConstants.PORTAL_APP_ID)) {
+                roleInfo = getPortalAppRoleInfo(roleId);
+            } else {
+                roleInfo = getPartnerAppRoleInfo(roleId, app.get(0).getId());
+            }
+            roleList = createCentralRoleObject(app, roleInfo, roleList);
+            if (roleList.isEmpty()) {
+                return cenRole;
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getRoleInfo: failed", e);
+            throw e;
+        }
+        return roleList.get(0);
+    }
+
+    private CentralV2Role getGlobalRoleForRequestedApp(long requestedAppId, long roleId) {
+        CentralV2Role finalGlobalrole;
+        List<GlobalRoleWithApplicationRoleFunction> roleWithApplicationRoleFucntions = new ArrayList<>();
+        try {
+            roleWithApplicationRoleFucntions = entityManager
+                .createNamedQuery("getGlobalRoleForRequestedApp")
+                .setParameter("roleId", roleId)
+                .setParameter("requestedAppId", requestedAppId)
+                .getResultList();
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getGlobalRoleForRequestedApp failed", e);
+        }
+        if (roleWithApplicationRoleFucntions.size() > 0) {
+            List<CentralV2Role> rolesfinalList = finalListOfCentralRoles(roleWithApplicationRoleFucntions);
+            finalGlobalrole = rolesfinalList.get(0);
+        } else {
+            List<FnRole> roleList = getPortalAppRoleInfo(roleId);
+            finalGlobalrole = convertRoleToCentralV2Role(roleList.get(0));
+        }
+        return finalGlobalrole;
+    }
+
+    public EpAppFunction getRoleFunction(String functionCode, String uebkey) throws Exception {
+        String code = EcompPortalUtils.getFunctionCode(functionCode);
+        String encodedCode = EcompPortalUtils.encodeFunctionCode(code);
+        EpAppFunction roleFunc = null;
+        FnApp app = getApp(uebkey).get(0);
+        List<EpAppFunction> getRoleFuncList = null;
+        try {
+            getRoleFuncList = epAppFunctionService.getRoleFunction(functionCode, app.getId());
+            if (getRoleFuncList.isEmpty()) {
+                getRoleFuncList = epAppFunctionService.getRoleFunction(encodedCode, app.getId());
+                if (getRoleFuncList.isEmpty()) {
+                    return roleFunc;
+                }
+            }
+            if (getRoleFuncList.size() > 1) {
+                EpAppFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList);
+                if (cenV2RoleFunction == null) {
+                    return roleFunc;
+                }
+                roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction);
+            } else {
+                // Check even if single record have pipes
+                if (!getRoleFuncList.isEmpty() && getRoleFuncList.get(0).getFunctionCd().contains(FUNCTION_PIPE)) {
+                    roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0));
+                } else {
+                    roleFunc = getRoleFuncList.get(0);
+                }
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e);
+            throw e;
+        }
+        return roleFunc;
+    }
+
+    private EpAppFunction appFunctionListFilter(String roleFuncCode, List<EpAppFunction> roleFunction) {
+        final Map<String, EpAppFunction> appFunctionsFilter = new HashMap<>();
+        final Map<String, EpAppFunction> appFunctionsFilterPipes = new HashMap<>();
+        EpAppFunction getExactFunctionCode;
+        for (EpAppFunction cenRoleFunction : roleFunction) {
+            appFunctionsFilter.put(cenRoleFunction.getFunctionCd(), cenRoleFunction);
+            appFunctionsFilterPipes
+                .put(EcompPortalUtils.getFunctionCode(cenRoleFunction.getFunctionCd()), cenRoleFunction);
+        }
+        getExactFunctionCode = appFunctionsFilter.get(roleFuncCode);
+        if (getExactFunctionCode == null) {
+            getExactFunctionCode = appFunctionsFilterPipes.get(roleFuncCode);
+        }
+        return getExactFunctionCode;
+    }
+
+    private EpAppFunction checkIfPipesExitsInFunctionCode(EpAppFunction getRoleFuncList) {
+        EpAppFunction roleFunc;
+        String functionCodeFormat = getRoleFuncList.getFunctionCd();
+        if (functionCodeFormat.contains(FUNCTION_PIPE)) {
+            String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(functionCodeFormat);
+            String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(functionCodeFormat);
+            String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(functionCodeFormat);
+            roleFunc = new EpAppFunction(getRoleFuncList.getId(), newfunctionCodeFormat,
+                getRoleFuncList.getFunctionName(), getRoleFuncList.getAppId(), newfunctionTypeFormat,
+                newfunctionActionFormat, getRoleFuncList.getEditUrl());
+        } else {
+            roleFunc = EpAppFunction.builder()
+                .id(getRoleFuncList.getId())
+                .functionCd(functionCodeFormat)
+                .functionName(getRoleFuncList.getFunctionName())
+                .appId(getRoleFuncList.getAppId())
+                .editUrl(getRoleFuncList.getEditUrl())
+                .build();
+        }
+        return roleFunc;
+    }
+
+    public boolean saveCentralRoleFunction(EpAppFunction domainCentralRoleFunction, FnApp app)
+        throws Exception {
+        boolean saveOrUpdateFunction = false;
+        try {
+            if (EcompPortalUtils.checkFunctionCodeHasEncodePattern(domainCentralRoleFunction.getFunctionCd())) {
+                domainCentralRoleFunction
+                    .setFunctionCd(EcompPortalUtils.encodeFunctionCode(domainCentralRoleFunction.getFunctionCd()));
+            }
+            final Map<String, String> functionParams = new HashMap<>();
+            functionParams.put("appId", String.valueOf(app.getId()));
+            if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                addRoleFunctionInExternalSystem(domainCentralRoleFunction, app);
+            }
+            if (domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null) {
+                domainCentralRoleFunction.setFunctionCd(domainCentralRoleFunction.getType() + FUNCTION_PIPE
+                    + domainCentralRoleFunction.getFunctionCd() + FUNCTION_PIPE + domainCentralRoleFunction
+                    .getAction());
+            }
+            domainCentralRoleFunction.setAppId(app);
+            epAppFunctionService.save(domainCentralRoleFunction);
+            saveOrUpdateFunction = true;
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e);
+            throw e;
+        }
+        return saveOrUpdateFunction;
+    }
+
+    private void addRoleFunctionInExternalSystem(EpAppFunction domainCentralRoleFunction, FnApp app)
+        throws Exception {
+        ObjectMapper mapper = new ObjectMapper();
+        ExternalAccessPerms extPerms = new ExternalAccessPerms();
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        String type = "";
+        String instance = "";
+        String action = "";
+        if ((domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null)
+            || domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)) {
+            type = domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)
+                ? EcompPortalUtils.getFunctionType(domainCentralRoleFunction.getFunctionCd())
+                : domainCentralRoleFunction.getType();
+            instance = domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)
+                ? EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getFunctionCd())
+                : domainCentralRoleFunction.getFunctionCd();
+            action = domainCentralRoleFunction.getFunctionCd().contains(FUNCTION_PIPE)
+                ? EcompPortalUtils.getFunctionAction(domainCentralRoleFunction.getFunctionCd())
+                : domainCentralRoleFunction.getAction();
+        } else {
+            type = domainCentralRoleFunction.getFunctionCd().contains("menu") ? "menu" : "url";
+            instance = domainCentralRoleFunction.getFunctionCd();
+            action = "*";
+        }
+        // get Permissions from External Auth System
+        JSONArray extPermsList = getExtAuthPermissions(app.getAuthNamespace());
+        List<ExternalAccessPermsDetail> permsDetailList = getExtAuthPerrmissonList(app, extPermsList);
+        String requestedPerm = type + FUNCTION_PIPE + instance + FUNCTION_PIPE + action;
+        boolean checkIfFunctionsExits = permsDetailList.stream()
+            .anyMatch(permsDetail -> permsDetail.getInstance().equals(requestedPerm));
+        if (!checkIfFunctionsExits) {
+            try {
+                extPerms.setAction(action);
+                extPerms.setInstance(instance);
+                extPerms.setType(app.getAuthNamespace() + "." + type);
+                extPerms.setDescription(domainCentralRoleFunction.getFunctionName());
+                String addFunction = mapper.writeValueAsString(extPerms);
+                HttpEntity<String> entity = new HttpEntity<>(addFunction, headers);
+                logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for POST: {}",
+                    CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, addFunction);
+                ResponseEntity<String> addPermResponse = template.exchange(
+                    SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
+                    HttpMethod.POST, entity, String.class);
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    "addRoleFunctionInExternalSystem: Finished adding permission for POST: {} and status code: {} ",
+                    addPermResponse.getStatusCode().value(), addFunction);
+            } catch (HttpClientErrorException e) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "HttpClientErrorException - Failed to add function in external central auth system", e);
+                EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+                throw e;
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "addRoleFunctionInExternalSystem: Failed to add fucntion in external central auth system", e);
+                throw e;
+            }
+        } else {
+            try {
+                extPerms.setAction(action);
+                extPerms.setInstance(instance);
+                extPerms.setType(app.getAuthNamespace() + "." + type);
+                extPerms.setDescription(domainCentralRoleFunction.getFunctionName());
+                String updateRoleFunction = mapper.writeValueAsString(extPerms);
+                HttpEntity<String> entity = new HttpEntity<>(updateRoleFunction, headers);
+                logger.debug(EELFLoggerDelegate.debugLogger, "addRoleFunctionInExternalSystem: {} for PUT: {}",
+                    CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, updateRoleFunction);
+                ResponseEntity<String> updatePermResponse = template.exchange(
+                    SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL) + "perm",
+                    HttpMethod.PUT, entity, String.class);
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    "addRoleFunctionInExternalSystem: Finished updating permission in External Auth system {} and response: {} ",
+                    updateRoleFunction, updatePermResponse.getStatusCode().value());
+            } catch (HttpClientErrorException e) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "HttpClientErrorException - Failed to add function in external central auth system", e);
+                EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+                throw e;
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "addRoleFunctionInExternalSystem: Failed to update function in external central auth system",
+                    e);
+                throw e;
+            }
+        }
+    }
+
+    public CentralRole convertV2CentralRoleToOldVerisonCentralRole(CentralV2Role v2CenRole) {
+        SortedSet<EpAppFunction> cenRoleFuncList = new TreeSet<>();
+        for (DomainVo vo : v2CenRole.getRoleFunctions()) {
+            Optional<EpAppFunction> v2CenRoleFunc = epAppFunctionService.getForId(vo.getId());
+            if (v2CenRoleFunc.isPresent()) {
+                EpAppFunction roleFunc = EpAppFunction.builder()
+                    .functionCd(v2CenRoleFunc.get().getFunctionCd())
+                    .functionName(v2CenRoleFunc.get().getFunctionName())
+                    .build();
+                cenRoleFuncList.add(roleFunc);
+            }
+
+        }
+        return new CentralRole(v2CenRole.getId(), v2CenRole.getName(), v2CenRole.isActive(), v2CenRole.getPriority(),
+            cenRoleFuncList);
+    }
+
+    public List<EpAppFunction> getRoleFuncList(String uebkey) throws Exception {
+        FnApp app = getApp(uebkey).get(0);
+        List<EpAppFunction> finalRoleList = new ArrayList<>();
+        List<EpAppFunction> getRoleFuncList = epAppFunctionService.getAllRoleFunctions(app.getId());
+        for (EpAppFunction roleFuncItem : getRoleFuncList) {
+            String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getFunctionCd());
+            String type = "";
+            if (roleFuncItem.getFunctionCd().contains("|")) {
+                type = EcompPortalUtils.getFunctionType(roleFuncItem.getFunctionCd());
+            } else {
+                type = getFunctionCodeType(roleFuncItem.getFunctionCd());
+            }
+            String action = getFunctionCodeAction(roleFuncItem.getFunctionCd());
+            roleFuncItem.setFunctionCd(EPUserUtils.decodeFunctionCode(code));
+            roleFuncItem.setType(type);
+            roleFuncItem.setAction(action);
+            finalRoleList.add(roleFuncItem);
+        }
+        return finalRoleList;
+    }
+
+    public List<CentralRoleFunction> convertCentralRoleFunctionToRoleFunctionObject(
+        List<EpAppFunction> answer) {
+        List<CentralRoleFunction> addRoleFuncList = new ArrayList<>();
+        for (EpAppFunction cenRoleFunc : answer) {
+            CentralRoleFunction setRoleFunc = new CentralRoleFunction();
+            setRoleFunc.setCode(cenRoleFunc.getFunctionCd());
+            setRoleFunc.setName(cenRoleFunc.getFunctionName());
+            addRoleFuncList.add(setRoleFunc);
+        }
+        return addRoleFuncList;
+    }
+
+    @Transactional(rollbackFor = Exception.class)
+    public boolean deleteCentralRoleFunction(String code, FnApp app) {
+        boolean deleteFunctionResponse = false;
+        try {
+            List<EpAppFunction> domainCentralRoleFunction = epAppFunctionService.getRoleFunction(code, app.getId());
+            EpAppFunction appFunctionCode = appFunctionListFilter(code, domainCentralRoleFunction);
+            if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                deleteRoleFunctionInExternalSystem(appFunctionCode, app);
+                // Delete role function dependency records
+                deleteAppRoleFunctions(appFunctionCode.getFunctionCd(), app.getId());
+            }
+            epAppFunctionService.deleteOne(appFunctionCode);
+            deleteFunctionResponse = true;
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "deleteCentralRoleFunction: failed", e);
+        }
+        return deleteFunctionResponse;
+    }
+
+    private void deleteRoleFunctionInExternalSystem(EpAppFunction domainCentralRoleFunction, FnApp app) {
+        try {
+            ObjectMapper mapper = new ObjectMapper();
+            ExternalAccessPerms extPerms = new ExternalAccessPerms();
+            String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getFunctionCd());
+            String checkType = getFunctionCodeType(domainCentralRoleFunction.getFunctionCd());
+            String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getFunctionCd());
+            HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+            extPerms.setAction(actionValue);
+            extPerms.setInstance(instanceValue);
+            extPerms.setType(app.getAuthNamespace() + "." + checkType);
+            extPerms.setDescription(domainCentralRoleFunction.getFunctionName());
+            String deleteRoleFunction = mapper.writeValueAsString(extPerms);
+            HttpEntity<String> entity = new HttpEntity<>(deleteRoleFunction, headers);
+            logger.debug(EELFLoggerDelegate.debugLogger, "deleteRoleFunctionInExternalSystem: {} for DELETE: {} ",
+                CONNECTING_TO_EXTERNAL_AUTH_SYSTEM_LOG_MESSAGE, deleteRoleFunction);
+            ResponseEntity<String> delPermResponse = template
+                .exchange(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)
+                    + "perm?force=true", HttpMethod.DELETE, entity, String.class);
+            logger.debug(EELFLoggerDelegate.debugLogger,
+                "deleteRoleFunctionInExternalSystem: Finished deleting permission in External Auth system {} and status code: {} ",
+                deleteRoleFunction, delPermResponse.getStatusCode().value());
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "HttpClientErrorException - Failed to delete functions in External System", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+        } catch (Exception e) {
+            if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    " deleteRoleFunctionInExternalSystem: It seems like function is already deleted in external central auth system  but exists in local DB",
+                    e.getMessage());
+            } else {
+                logger.error(EELFLoggerDelegate.errorLogger,
+                    "deleteRoleFunctionInExternalSystem: Failed to delete functions in External System", e);
+            }
+        }
+    }
+
+    private void deleteAppRoleFunctions(final String code, final Long appId) {
+        epAppFunctionService.deleteByAppIdAndFunctionCd(appId, code);
+    }
+
+    public Integer updateAppRoleDescription(String uebkey) {
+        Integer roleDescUpdated = 0;
+        FnApp app;
+        try {
+            app = getApp(uebkey).get(0);
+            List<FnRole> roles = getAppRoles(app.getId());
+            for (FnRole epRole : roles) {
+                Role role = new Role();
+                role.setName(epRole.getRoleName());
+                boolean status = addRoleDescriptionInExtSystem(role.getName(), app.getAuthNamespace());
+                if (status) {
+                    roleDescUpdated++;
+                }
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "updateAppRoleDescription: Failed! ", e);
+        }
+        return roleDescUpdated;
+    }
+
+    public Role convertCentralRoleToRole(String result) {
+        ObjectMapper mapper = new ObjectMapper();
+        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+        Role newRole = new Role();
+        try {
+            newRole = mapper.readValue(result, Role.class);
+        } catch (IOException e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "Failed to convert the result to Role Object", e);
+        }
+        if (newRole.getRoleFunctions() != null) {
+            Set<RoleFunction> roleFunctionList = newRole.getRoleFunctions();
+            Set<RoleFunction> roleFunctionListNew = new HashSet<>();
+            for (Object nextValue : roleFunctionList) {
+                RoleFunction roleFun = mapper.convertValue(nextValue, RoleFunction.class);
+                roleFunctionListNew.add(roleFun);
+            }
+            newRole.setRoleFunctions(roleFunctionListNew);
+        }
+        return newRole;
+    }
+
+    public void bulkUploadRoleFunc(UploadRoleFunctionExtSystem data, FnApp app) throws Exception {
+        ObjectMapper mapper = new ObjectMapper();
+        HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+        try {
+            ExternalAccessRolePerms extRolePerms;
+            ExternalAccessPerms extPerms;
+            extPerms = new ExternalAccessPerms(app.getAuthNamespace() + "." + data.getType(),
+                EcompPortalUtils.encodeFunctionCode(data.getInstance()), data.getAction());
+            String appNameSpace = "";
+            if (data.isGlobalRolePartnerFunc()) {
+                //TODO HARDCODED ID
+                appNameSpace = fnAppService.getById(1L).getAuthNamespace();
+            } else {
+                appNameSpace = app.getAuthNamespace();
+            }
+            extRolePerms = new ExternalAccessRolePerms(extPerms, appNameSpace + "." + data.getRoleName()
+                .replaceAll(EcompPortalUtils.EXTERNAL_CENTRAL_AUTH_ROLE_HANDLE_SPECIAL_CHARACTERS, "_"));
+            String updateRolePerms = mapper.writeValueAsString(extRolePerms);
+            HttpEntity<String> entity = new HttpEntity<>(updateRolePerms, headers);
+            updateRoleFunctionInExternalSystem(updateRolePerms, entity);
+        } catch (HttpClientErrorException e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "HttpClientErrorException - Failed to add role function in external central auth system", e);
+            EPLogUtil.logExternalAuthAccessAlarm(logger, e.getStatusCode());
+            throw e;
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "addFunctionInExternalSystem: Failed to add role fucntion in external central auth system", e);
+            throw e;
+        }
+    }
 }
diff --git a/portal-BE/src/main/java/org/onap/portal/service/LocalRoleService.java b/portal-BE/src/main/java/org/onap/portal/service/LocalRoleService.java
new file mode 100644 (file)
index 0000000..e16bb32
--- /dev/null
@@ -0,0 +1,26 @@
+package org.onap.portal.service;
+
+import java.util.List;
+import javax.persistence.EntityManager;
+import javax.transaction.Transactional;
+import org.onap.portal.domain.dto.transport.LocalRole;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+
+@Service
+@Transactional
+public class LocalRoleService {
+
+    private final EntityManager entityManager;
+
+    @Autowired
+    public LocalRoleService(EntityManager entityManager) {
+        this.entityManager = entityManager;
+    }
+
+    public List<LocalRole> getCurrentAppRoleFunctions(final long appId, final String functionCd){
+        final String query = "select distinct fr.role_id, fr.role_name  from fn_role fr, ep_app_function ef, ep_app_role_function epr where fr.role_id = epr.role_id and epr.function_cd = ef.function_cd\n"
+            + " and ef.function_cd =:functionCd and epr.app_id =:appId";
+        return entityManager.createNamedQuery(query).setParameter("appId", appId).setParameter("functionCd", functionCd).getResultList();
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/service/MicroserviceProxyService.java b/portal-BE/src/main/java/org/onap/portal/service/MicroserviceProxyService.java
new file mode 100644 (file)
index 0000000..9273b28
--- /dev/null
@@ -0,0 +1,210 @@
+package org.onap.portal.service;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import javax.servlet.http.HttpServletRequest;
+import org.apache.commons.codec.binary.Base64;
+import org.onap.portal.domain.db.ep.EpMicroservice;
+import org.onap.portal.domain.db.ep.EpMicroserviceParameter;
+import org.onap.portal.domain.db.ep.EpWidgetCatalogParameter;
+import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.restTemplates.PortalWMSTemplate;
+import org.onap.portal.service.microservice.EpMicroserviceService;
+import org.onap.portal.service.widgetCatalogParameter.EpWidgetCatalogParameterService;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.MediaType;
+import org.springframework.http.ResponseEntity;
+import org.springframework.stereotype.Service;
+import org.springframework.web.client.HttpClientErrorException;
+import org.springframework.web.client.RestTemplate;
+
+@Service
+public class MicroserviceProxyService {
+
+    private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MicroserviceProxyService.class);
+
+    private static final String BASIC_AUTH = "Basic Authentication";
+    private static final String NO_AUTH = "No Authentication";
+    private static final String COOKIE_AUTH = "Cookie based Authentication";
+    private static final String QUESTION_MARK = "?";
+    private static final String ADD_MARK = "&";
+
+    private RestTemplate template = new RestTemplate();
+
+    private final EpMicroserviceService microserviceService;
+    private final EpWidgetCatalogParameterService widgetParameterService;
+
+    private final PortalWMSTemplate portalWMSTemplate;
+
+    @Autowired
+    public MicroserviceProxyService(EpMicroserviceService microserviceService,
+        EpWidgetCatalogParameterService widgetParameterService, WidgetMService widgetMService,
+        PortalWMSTemplate portalWMSTemplate) {
+        this.microserviceService = microserviceService;
+        this.widgetParameterService = widgetParameterService;
+        this.portalWMSTemplate = portalWMSTemplate;
+    }
+
+    public String proxyToDestination(long serviceId, FnUser user, HttpServletRequest request) throws Exception {
+        // get the microservice object by the id
+        Optional<EpMicroservice> data = microserviceService.getById(serviceId);
+        // No such microservice available
+        // can we return a better response than null?
+        return data
+            .map(epMicroservice -> authenticateAndRespond(epMicroservice, request, composeParams(epMicroservice, user)))
+            .orElse(null);
+    }
+
+    public String proxyToDestinationByWidgetId(long widgetId, FnUser user, HttpServletRequest request)
+        throws Exception {
+        ResponseEntity<Long> ans = portalWMSTemplate.proxyToDestinationByWidgetId(widgetId);
+        Long serviceId = ans.getBody();
+        // get the microservice object by the id
+        Optional<EpMicroservice> data = microserviceService.getById(serviceId);
+        // No such microservice available
+        if (!data.isPresent()) {
+            return null;
+        }
+        List<EpMicroserviceParameter> params = composeParams(data.get(), user);
+        for (EpMicroserviceParameter p : params) {
+            EpWidgetCatalogParameter userValue = widgetParameterService.getUserParamById(widgetId, user.getId(),
+                p.getId());
+            if (userValue != null) {
+                p.setParaValue(userValue.getUserValue());
+            }
+        }
+        return authenticateAndRespond(data.get(), request, params);
+    }
+
+    private String authenticateAndRespond(EpMicroservice data, HttpServletRequest request,
+        List<EpMicroserviceParameter> params) throws HttpClientErrorException, IllegalArgumentException {
+        String response = null;
+        switch (data.getSecurityType()) {
+            case NO_AUTH: {
+                HttpEntity<String> entity = new HttpEntity<>(headersForNoAuth());
+                String url = microserviceUrlConverter(data, params);
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    "authenticateAndRespond: Before making no authentication call: {}", url);
+                response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
+                logger.debug(EELFLoggerDelegate.debugLogger,
+                    "authenticateAndRespond: No authentication call response: {}",
+                    response);
+                break;
+            }
+            case BASIC_AUTH: {
+                // encoding the username and password
+                String plainCreds;
+                try {
+                    plainCreds = data.getUsername() + ":" + decryptedPassword(data.getPassword());
+                } catch (Exception e) {
+                    logger.error("authenticateAndRespond failed to decrypt password", e);
+                    throw new IllegalArgumentException("Failed to decrypt password", e);
+                }
+                byte[] plainCredsBytes = plainCreds.getBytes();
+                byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
+                String base64Creds = new String(base64CredsBytes);
+
+                HttpEntity<String> entity = new HttpEntity<>(headersForBasicAuth(request, base64Creds));
+
+                String url = microserviceUrlConverter(data, params);
+                try {
+                    response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
+                } catch (HttpClientErrorException e) {
+                    logger.error("authenticateAndRespond failed for basic security url " + url, e);
+                    throw e;
+                }
+                break;
+            }
+            case COOKIE_AUTH: {
+                HttpEntity<String> entity = new HttpEntity<>(headersForCookieAuth(request));
+                String url = microserviceUrlConverter(data, params);
+                try {
+                    response = template.exchange(url, HttpMethod.GET, entity, String.class).getBody();
+                } catch (HttpClientErrorException e) {
+                    logger.error("authenticateAndRespond failed for cookie auth url " + url, e);
+                    throw e;
+                }
+                break;
+            }
+        }
+
+        return response;
+    }
+
+    private String decryptedPassword(String encryptedPwd) throws Exception {
+        String result = "";
+        if (encryptedPwd != null && encryptedPwd.length() > 0) {
+            try {
+                result = CipherUtil.decryptPKC(encryptedPwd,
+                    SystemProperties.getProperty(SystemProperties.Decryption_Key));
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger, "decryptedPassword failed", e);
+                throw e;
+            }
+        }
+
+        return result;
+    }
+
+    private String microserviceUrlConverter(EpMicroservice data, List<EpMicroserviceParameter> params) {
+        String url = data.getEndpointUrl();
+        for (int i = 0; i < params.size(); i++) {
+            if (i == 0) {
+                url += QUESTION_MARK;
+            }
+            url += params.get(i).getParaKey() + "=" + params.get(i).getParaValue();
+            if (i != (params.size() - 1)) {
+                url += ADD_MARK;
+            }
+        }
+
+        return url;
+    }
+
+    private HttpHeaders headersForNoAuth() {
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+
+        return headers;
+    }
+
+    // TODO: why is this generically named cookie used?
+    private final static String Cookie = "Cookie";
+
+    private HttpHeaders headersForBasicAuth(HttpServletRequest request, String base64Creds) {
+        HttpHeaders headers = new HttpHeaders();
+        headers.add("Authorization", "Basic " + base64Creds);
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        String rawCookie = request.getHeader(Cookie);
+        if (rawCookie != null) {
+            headers.add(Cookie, rawCookie);
+        }
+        return headers;
+    }
+
+    private HttpHeaders headersForCookieAuth(HttpServletRequest request) {
+        HttpHeaders headers = new HttpHeaders();
+        headers.setContentType(MediaType.APPLICATION_JSON);
+        String rawCookie = request.getHeader(Cookie);
+        if (rawCookie != null) {
+            headers.add(Cookie, rawCookie);
+        }
+        return headers;
+    }
+
+    private List<EpMicroserviceParameter> composeParams(EpMicroservice data, FnUser user) {
+        List<EpMicroserviceParameter> params = new ArrayList<>(data.getEpMicroserviceParameters());
+        EpMicroserviceParameter userIdParam = new EpMicroserviceParameter();
+        userIdParam.setParaKey("userId");
+        userIdParam.setParaValue(user.getOrgUserId());
+        params.add(userIdParam);
+        return params;
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/service/PortalAdminService.java b/portal-BE/src/main/java/org/onap/portal/service/PortalAdminService.java
new file mode 100644 (file)
index 0000000..13be1f3
--- /dev/null
@@ -0,0 +1,222 @@
+package org.onap.portal.service;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.List;
+import javax.annotation.PostConstruct;
+import javax.persistence.EntityExistsException;
+import javax.persistence.EntityManager;
+import javax.servlet.http.HttpServletResponse;
+import org.onap.portal.domain.db.fn.FnApp;
+import org.onap.portal.domain.db.fn.FnRole;
+import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.domain.db.fn.FnUserRole;
+import org.onap.portal.domain.dto.transport.ExternalAccessUser;
+import org.onap.portal.domain.dto.transport.FieldsValidator;
+import org.onap.portal.domain.dto.transport.PortalAdmin;
+import org.onap.portal.restTemplates.AAFTemplate;
+import org.onap.portal.service.app.FnAppService;
+import org.onap.portal.service.role.FnRoleService;
+import org.onap.portal.service.user.FnUserService;
+import org.onap.portal.service.userRole.FnUserRoleService;
+import org.onap.portal.utils.EPCommonSystemProperties;
+import org.onap.portal.utils.EcompPortalUtils;
+import org.onap.portal.utils.PortalConstants;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.stereotype.Service;
+
+@Service
+public class PortalAdminService {
+
+    private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PortalAdminService.class);
+
+    private String SYS_ADMIN_ROLE_ID = "1";
+    private String ECOMP_APP_ID = "1";
+
+    private final ExternalAccessRolesService externalAccessRolesService;
+    private final FnAppService fnAppService;
+    private final FnRoleService fnRoleService;
+    private final FnUserRoleService fnUserRoleService;
+    private final FnUserService fnUserService;
+    private final EntityManager entityManager;
+    private final AAFTemplate aafTemplate;
+
+    @Autowired
+    public PortalAdminService(ExternalAccessRolesService externalAccessRolesService,
+        FnAppService fnAppService, FnRoleService fnRoleService,
+        FnUserRoleService fnUserRoleService, FnUserService fnUserService,
+        EntityManager entityManager, AAFTemplate aafTemplate) {
+        this.externalAccessRolesService = externalAccessRolesService;
+        this.fnAppService = fnAppService;
+        this.fnRoleService = fnRoleService;
+        this.fnUserRoleService = fnUserRoleService;
+        this.fnUserService = fnUserService;
+        this.entityManager = entityManager;
+        this.aafTemplate = aafTemplate;
+    }
+
+    @PostConstruct
+    public void init() {
+        SYS_ADMIN_ROLE_ID = SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID);
+        ECOMP_APP_ID = SystemProperties.getProperty(EPCommonSystemProperties.ECOMP_APP_ID);
+    }
+
+
+    @SuppressWarnings("unchecked")
+    public List<PortalAdmin> getPortalAdmins() {
+        try {
+            List<PortalAdmin> portalAdmins = entityManager.createNamedQuery("PortalAdminDTO")
+                .setParameter("adminRoleId", SYS_ADMIN_ROLE_ID).getResultList();
+            logger.debug(EELFLoggerDelegate.debugLogger, "getPortalAdmins was successful");
+            return portalAdmins;
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "getPortalAdmins failed", e);
+            return null;
+        }
+    }
+
+    public FieldsValidator createPortalAdmin(String orgUserId) {
+        FieldsValidator fieldsValidator = new FieldsValidator();
+        logger.debug(EELFLoggerDelegate.debugLogger, "LR: createPortalAdmin: orgUserId is {}", orgUserId);
+        FnUser user = null;
+        boolean createNewUser = false;
+        List<FnUser> localUserList = fnUserService.getUserWithOrgUserId(orgUserId);
+        if (!localUserList.isEmpty()) {
+            user = localUserList.get(0);
+        } else {
+            createNewUser = true;
+        }
+
+        if (user != null && isLoggedInUserPortalAdmin(user.getId())) {
+            fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_CONFLICT);
+            logger.error(EELFLoggerDelegate.errorLogger,
+                "User '" + user.getOrgUserId() + "' already has PortalAdmin role assigned.");
+        } else if (user != null || createNewUser) {
+            try {
+                if (createNewUser) {
+                    user = fnUserService.getUserWithOrgUserId(orgUserId).get(0);
+                    if (user != null) {
+                        user.setActiveYn(true);
+                        fnUserService.save(user);
+                    }
+                }
+                if (user != null) {
+                    FnUserRole userRole = new FnUserRole();
+                    userRole.setUserId(user);
+                    userRole.setRoleId(fnRoleService.getById(Long.valueOf(SYS_ADMIN_ROLE_ID)));
+                    userRole.setFnAppId(fnAppService.getById(Long.valueOf(ECOMP_APP_ID)));
+                    fnUserRoleService.saveOne(userRole);
+                }
+                if (user != null && EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+                    List<FnRole> roleList = externalAccessRolesService
+                        .getPortalAppRoleInfo(PortalConstants.SYS_ADMIN_ROLE_ID);
+                    FnRole role = new FnRole();
+                    if (roleList.size() > 0) {
+                        role = roleList.get(0);
+                    }
+                    logger.debug(EELFLoggerDelegate.debugLogger, "Requested RoleName is  " + role.getRoleName());
+                    addPortalAdminInExternalCentralAuth(user.getOrgUserId(), role.getRoleName());
+                }
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger, "createPortalAdmin failed", e);
+                fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+            }
+        }
+        return fieldsValidator;
+    }
+
+    private void addPortalAdminInExternalCentralAuth(String loginId, String portalAdminRole) throws Exception {
+        try {
+            String name = "";
+            if (EPCommonSystemProperties.containsProperty(
+                EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+                name = loginId + SystemProperties
+                    .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+            }
+            //TODO HARDCODED ID
+            FnApp app = fnAppService.getById(PortalConstants.PORTAL_APP_ID);
+            String extRole = app.getAuthNamespace() + "." + portalAdminRole.replaceAll(" ", "_");
+            ObjectMapper addUserRoleMapper = new ObjectMapper();
+            ExternalAccessUser extUser = new ExternalAccessUser(name, extRole);
+            String userRole = addUserRoleMapper.writeValueAsString(extUser);
+            HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+            aafTemplate.addPortalAdminInAAF(new HttpEntity<>(userRole, headers));
+        } catch (Exception e) {
+            if (e.getMessage().equalsIgnoreCase("409 Conflict")) {
+                logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already exists", e.getMessage());
+            } else {
+                logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
+                throw e;
+            }
+        }
+    }
+
+    public FieldsValidator deletePortalAdmin(Long userId) {
+        FieldsValidator fieldsValidator = new FieldsValidator();
+        logger.debug(EELFLoggerDelegate.debugLogger, "deletePortalAdmin: test 1");
+        try {
+            //TODO HARDCODED ID
+            fnUserRoleService.deleteByUserIdAndRoleId(userId, SYS_ADMIN_ROLE_ID);
+            if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) {
+
+                List<FnRole> roleList = externalAccessRolesService
+                    .getPortalAppRoleInfo(PortalConstants.SYS_ADMIN_ROLE_ID);
+                FnRole role = new FnRole();
+                if (roleList.size() > 0) {
+                    role = roleList.get(0);
+                }
+                logger.debug(EELFLoggerDelegate.debugLogger, "Requested RoleName is  " + role.getRoleName());
+                deletePortalAdminInExternalCentralAuth(userId, role.getRoleName());
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "deletePortalAdmin failed", e);
+            fieldsValidator.setHttpStatusCode((long) HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+        }
+        return fieldsValidator;
+    }
+
+
+    private void deletePortalAdminInExternalCentralAuth(Long userId, String portalAdminRole) throws Exception {
+        try {
+            String name = "";
+            FnUser localUserList = fnUserService.getUser(userId)
+                .orElseThrow(() -> new EntityExistsException("User with id:" + userId + "do not exists."));
+            if (EPCommonSystemProperties.containsProperty(
+                EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) {
+                name = localUserList.getOrgUserId() + SystemProperties
+                    .getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN);
+            }
+            //TODO HARDCODED ID
+            FnApp app = fnAppService.getById(PortalConstants.PORTAL_APP_ID);
+            String extRole = app.getAuthNamespace() + "." + portalAdminRole.replaceAll(" ", "_");
+            HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth();
+            aafTemplate.deletePortalAdminFromAAF(name, extRole, new HttpEntity<>(headers));
+        } catch (Exception e) {
+            if (e.getMessage().equalsIgnoreCase("404 Not Found")) {
+                logger.debug(EELFLoggerDelegate.debugLogger, "Portal Admin role already deleted or may not be found",
+                    e.getMessage());
+            } else {
+                logger.error(EELFLoggerDelegate.errorLogger, "Failed to add Portal Admin role ", e);
+                throw e;
+            }
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    private boolean isLoggedInUserPortalAdmin(Long userId) {
+        try {
+            List<PortalAdmin> portalAdmins = entityManager.createNamedQuery("ActivePortalAdminDTO")
+                .setParameter("userId", userId)
+                .setParameter("adminRoleId", SYS_ADMIN_ROLE_ID)
+                .getResultList();
+            logger.debug(EELFLoggerDelegate.debugLogger, portalAdmins.toString());
+            return portalAdmins.size() > 0;
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "isLoggedInUserPortalAdmin failed", e);
+            return false;
+        }
+    }
+}
diff --git a/portal-BE/src/main/java/org/onap/portal/service/SearchService.java b/portal-BE/src/main/java/org/onap/portal/service/SearchService.java
new file mode 100644 (file)
index 0000000..0829239
--- /dev/null
@@ -0,0 +1,179 @@
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+
+package org.onap.portal.service;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.domain.dto.transport.UserWithNameSurnameTitle;
+import org.onap.portal.service.user.FnUserService;
+import org.onap.portal.utils.EcompPortalUtils;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+@Service
+@Transactional
+public class SearchService {
+
+    EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(SearchService.class);
+
+    private static final int maxSizeOfSearchResult = 100;
+
+    private final FnUserService userService;
+
+    @Autowired
+    public SearchService(FnUserService userService) {
+        this.userService = userService;
+    }
+
+    public String searchUsersInPhoneBook(final String searchString) {
+        List<String> tokens = EcompPortalUtils.parsingByRegularExpression(searchString, " ");
+        while (tokens.size() > 2) { // we use no more then first 2 tokens (userId is removed, see above)
+            tokens.remove(tokens.size() - 1);
+        }
+        FnUser attrUser = new FnUser();
+        List<UserWithNameSurnameTitle> resultOfSearch = new ArrayList<UserWithNameSurnameTitle>(), resultOfAdditionalSearch = null,
+            resultOfSearchUserId = new ArrayList<UserWithNameSurnameTitle>();
+        if (tokens.size() == 2) {
+            attrUser.setFirstName(tokens.get(0));
+            attrUser.setLastName(tokens.get(1));
+            resultOfSearch = this.searchUsersByName(attrUser);
+            resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0));
+            resultOfSearch = this.removeWrongLastNames(resultOfSearch, tokens.get(1));
+            if (resultOfSearch.size() < maxSizeOfSearchResult) {
+                attrUser.setFirstName(tokens.get(1));
+                attrUser.setLastName(tokens.get(0));
+                resultOfAdditionalSearch = this.searchUsersByName(attrUser);
+                resultOfAdditionalSearch = this.removeWrongFirstNames(resultOfAdditionalSearch, tokens.get(1));
+                resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0));
+            }
+        } else if (tokens.size() == 1) {
+            attrUser.setFirstName(tokens.get(0));
+            attrUser.setOrgUserId(tokens.get(0));
+            resultOfSearch = this.searchUsersByName(attrUser);
+            resultOfSearchUserId = this.searchUsersByUserId(attrUser);
+            resultOfSearch = this.removeWrongFirstNames(resultOfSearch, tokens.get(0));
+            if (resultOfSearch.size() < maxSizeOfSearchResult) {
+                attrUser.setFirstName(null);
+                attrUser.setLastName(tokens.get(0));
+                resultOfAdditionalSearch = this.searchUsersByName(attrUser);
+                resultOfAdditionalSearch = this.removeWrongLastNames(resultOfAdditionalSearch, tokens.get(0));
+            }
+        }
+        if (resultOfAdditionalSearch != null) {
+            resultOfSearch.addAll(resultOfAdditionalSearch);
+        }
+        resultOfSearch.addAll(resultOfSearchUserId);
+        resultOfSearch.stream().distinct().collect(Collectors.toList());
+        resultOfSearch = this.cutSearchResultToMaximumSize(resultOfSearch);
+        ObjectMapper mapper = new ObjectMapper();
+        String result = "[]";
+        try {
+            result = mapper.writeValueAsString(resultOfSearch);
+        } catch (JsonProcessingException e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "searchUsersInFnTable failed", e);
+        }
+        return result;
+    }
+
+    public List<UserWithNameSurnameTitle> searchUsersByUserId(FnUser attrUser) {
+        List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>();
+        try {
+            List<FnUser> searchResult = this.userService.getUserByUserId(attrUser.getOrgUserId());
+            for (FnUser user : searchResult) {
+                UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle());
+                foundUsers.add(foundUser);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "searchUsersByUserId failed", e);
+        }
+        return foundUsers;
+    }
+
+    public List<UserWithNameSurnameTitle> searchUsersByName(FnUser attrUser) {
+        List<UserWithNameSurnameTitle> foundUsers = new ArrayList<UserWithNameSurnameTitle>();
+        try {
+            List<FnUser> searchResult = this.userService.getUserByFirstLastName(attrUser.getFirstName(),attrUser.getLastName());
+            for (Object obj : searchResult) {
+                FnUser user = (FnUser) obj;
+                UserWithNameSurnameTitle foundUser = new UserWithNameSurnameTitle(user.getOrgUserId(), user.getFirstName(), user.getLastName(), user.getJobTitle());
+                foundUsers.add(foundUser);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "searchUsersByName failed", e);
+        }
+        return foundUsers;
+    }
+
+    private List<UserWithNameSurnameTitle> removeWrongFirstNames(List<UserWithNameSurnameTitle> resultOfSearch, String firstName) {
+        firstName = firstName.toUpperCase();
+        for (int i = resultOfSearch.size() - 1; i >= 0; i--) {
+            UserWithNameSurnameTitle user = resultOfSearch.get(i);
+            if ((user.getFirstName() == null) || !user.getFirstName().toUpperCase().startsWith(firstName)) {
+                resultOfSearch.remove(i);
+            }
+        }
+        return resultOfSearch;
+    }
+
+    private List<UserWithNameSurnameTitle> removeWrongLastNames(List<UserWithNameSurnameTitle> resultOfSearch, String lastName) {
+        lastName = lastName.toUpperCase();
+        for (int i = resultOfSearch.size() - 1; i >= 0; i--) {
+            UserWithNameSurnameTitle user = resultOfSearch.get(i);
+            if ((user.getLastName() == null) || !user.getLastName().toUpperCase().startsWith(lastName)) {
+                resultOfSearch.remove(i);
+            }
+        }
+        return resultOfSearch;
+    }
+
+    private List<UserWithNameSurnameTitle> cutSearchResultToMaximumSize(List<UserWithNameSurnameTitle> resultOfSearch) {
+        if (resultOfSearch.size() > maxSizeOfSearchResult) {
+            resultOfSearch.subList(maxSizeOfSearchResult, resultOfSearch.size()).clear();
+        }
+        return resultOfSearch;
+    }
+}
index f57cc24..2313ce1 100644 (file)
@@ -1,6 +1,7 @@
 package org.onap.portal.service.app;
 
 import java.util.List;
+import java.util.Optional;
 import org.onap.portal.domain.db.fn.FnApp;
 import org.springframework.data.jpa.repository.JpaRepository;
 import org.springframework.data.jpa.repository.Query;
@@ -12,10 +13,12 @@ import org.springframework.transaction.annotation.Transactional;
 @Transactional
 interface FnAppDao extends JpaRepository<FnApp, Long> {
 
-  @Query
-  List<FnApp> getByUebKey(final @Param("uebKey") String uebKey);
+    @Query
+    List<FnApp> getByUebKey(final @Param("uebKey") String uebKey);
 
-  @Query
-  List<FnApp> getCentralizedApps();
+    @Query
+    List<FnApp> getCentralizedApps();
 
+    @Query
+    Optional<List<FnApp>> retrieveWhereAppName(final @Param("appName") String appName);
 }
index 13d0911..98cb0fa 100644 (file)
@@ -138,4 +138,17 @@ public class FnAppService {
   public List<FnApp> saveAll(List<FnApp> fnApps) {
     return fnAppDao.saveAll(fnApps);
   }
+
+  public List<FnApp> findAll() {
+    return Optional.of(fnAppDao.findAll()).orElse(new ArrayList<>());
+  }
+
+  public FnApp getAppDetail(final String appName) {
+    List<FnApp> fnApps = fnAppDao.retrieveWhereAppName(appName).orElse(new ArrayList<>());
+    if (!fnApps.isEmpty()) {
+      return fnApps.get(0);
+    } else {
+      throw new EntityExistsException("No FnApp where appName equals " + appName);
+    }
+  }
 }
index 1f8c64b..d2dcb3a 100644 (file)
@@ -41,6 +41,7 @@
 package org.onap.portal.service.appFunction;
 
 import java.util.List;
+import java.util.Optional;
 import org.onap.portal.domain.db.ep.EpAppFunction;
 import org.springframework.data.jpa.repository.JpaRepository;
 import org.springframework.data.jpa.repository.Query;
@@ -55,4 +56,13 @@ interface EpAppFunctionDao extends JpaRepository<EpAppFunction, Long> {
   @Query
   List<EpAppFunction> getAppRoleFunctionList(final @Param("roleId") Long roleId, final @Param("appId") Long appId);
 
+  @Query
+  Optional<List<EpAppFunction>> getAllRoleFunctions(final @Param("appId") Long appId);
+
+  @Query
+  List<EpAppFunction> getAppFunctionOnCodeAndAppId(final @Param("appId") long appId, @Param("functionCd") final String functionCd);
+
+  @Query
+  List<EpAppFunction> getRoleFunction(@Param("functionCd") final String functionCd, final @Param("appId") long appId);
+
 }
index aa5e258..23fd675 100644 (file)
@@ -45,8 +45,8 @@ import java.util.List;
 import java.util.Optional;
 import java.util.function.Function;
 import java.util.function.Predicate;
-import java.util.stream.Collectors;
 
+import javax.persistence.EntityManager;
 import org.onap.portal.domain.db.ep.EpAppFunction;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
@@ -55,21 +55,21 @@ import org.springframework.stereotype.Service;
 public class EpAppFunctionService {
 
   private final EpAppFunctionDao epAppFunctionDao;
+  private final EntityManager entityManager;
 
   @Autowired
-  public EpAppFunctionService(EpAppFunctionDao epAppFunctionDao) {
+  public EpAppFunctionService(final EpAppFunctionDao epAppFunctionDao,final EntityManager entityManager) {
     this.epAppFunctionDao = epAppFunctionDao;
+    this.entityManager = entityManager;
   }
 
   public List<EpAppFunction> getAppRoleFunctionList(final Long roleId, final Long appId) {
-
     return Optional.of(epAppFunctionDao.getAppRoleFunctionList(roleId, appId))
-        .orElse(new ArrayList<>())
-        .stream()
-        .filter(distinctByKey(EpAppFunction::getAppId))
-        .filter(distinctByKey(EpAppFunction::getFunctionCd))
-        .filter(distinctByKey(EpAppFunction::getFunctionName))
-        .collect(Collectors.toList());
+        .orElse(new ArrayList<>());
+  }
+
+  public Optional<EpAppFunction> getForId(Long id){
+    return epAppFunctionDao.findById(id);
   }
 
   private <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
@@ -77,7 +77,34 @@ public class EpAppFunctionService {
     return t -> seen.add(keyExtractor.apply(t));
   }
 
+  public EpAppFunction save(final EpAppFunction epAppFunction){
+    return epAppFunctionDao.save(epAppFunction);
+  }
+
   public List<EpAppFunction> saveAll(List<EpAppFunction> epAppFunctions) {
     return epAppFunctionDao.saveAll(epAppFunctions);
   }
+
+  public List<EpAppFunction> getAllRoleFunctions(final Long appId){
+    return epAppFunctionDao.getAllRoleFunctions(appId).orElse(new ArrayList<>());
+  }
+
+  public List<EpAppFunction> getAppFunctionOnCodeAndAppId(final long appId, final String functionCd) {
+      return epAppFunctionDao.getAppFunctionOnCodeAndAppId(appId, functionCd);
+  }
+
+  public List<EpAppFunction> getRoleFunction(final String functionCd, final long appId) {
+    return epAppFunctionDao.getRoleFunction(functionCd, appId);
+  }
+
+  public void deleteOne(EpAppFunction function){
+    epAppFunctionDao.delete(function);
+  }
+
+  public void deleteByAppIdAndFunctionCd(Long appId, String functionCd) {
+    entityManager.createQuery("DELETE FROM ep_app_function WHERE app_id = :appId and function_cd = :functionCd")
+        .setParameter("appId", appId)
+        .setParameter("functionCd", functionCd)
+        .executeUpdate();
+  }
 }
index 801c938..0fb4320 100644 (file)
 
 package org.onap.portal.service.appRoleFunction;
 
+import java.util.List;
 import org.onap.portal.domain.db.ep.EpAppRoleFunction;
 import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.data.jpa.repository.Query;
+import org.springframework.data.repository.query.Param;
 import org.springframework.stereotype.Repository;
 import org.springframework.transaction.annotation.Transactional;
 
@@ -49,4 +52,7 @@ import org.springframework.transaction.annotation.Transactional;
 @Transactional
 interface EpAppRoleFunctionDao extends JpaRepository<EpAppRoleFunction, Integer> {
 
+    @Query
+    List<EpAppRoleFunction> getAppRoleFunctionOnRoleIdAndAppId(final @Param("appId") long appId, final @Param("roleId") long roleId);
+
 }
index cb5383b..d8d2683 100644 (file)
@@ -40,6 +40,7 @@
 
 package org.onap.portal.service.appRoleFunction;
 
+import javax.persistence.EntityManager;
 import org.onap.portal.domain.db.ep.EpAppRoleFunction;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
@@ -50,13 +51,48 @@ import java.util.List;
 public class EpAppRoleFunctionService {
 
     private final EpAppRoleFunctionDao epAppRoleFunctionDao;
+    private final EntityManager entityManager;
+
 
     @Autowired
-    public EpAppRoleFunctionService(EpAppRoleFunctionDao epAppRoleFunctionDao) {
+    public EpAppRoleFunctionService(final EpAppRoleFunctionDao epAppRoleFunctionDao,
+        final EntityManager entityManager) {
         this.epAppRoleFunctionDao = epAppRoleFunctionDao;
+        this.entityManager = entityManager;
     }
 
     public List<EpAppRoleFunction> saveAll(List<EpAppRoleFunction> epAppRoleFunctions) {
         return epAppRoleFunctionDao.saveAll(epAppRoleFunctions);
     }
+
+    public EpAppRoleFunction save(EpAppRoleFunction apRoleFunction) {
+        return epAppRoleFunctionDao.save(apRoleFunction);
+    }
+
+    public List<EpAppRoleFunction> getAppRoleFunctionOnRoleIdAndAppId(final long appId, final long roleId){
+        return getAppRoleFunctionOnRoleIdAndAppId(appId, roleId);
+    }
+
+    public void deleteByAppIdAndFunctionCd(final Long appId, final String functionCd) {
+        entityManager.createQuery("DELETE FROM ep_app_role_function WHERE app_id = :appId and function_cd = :functionCd")
+            .setParameter("appId", appId)
+            .setParameter("functionCd", functionCd)
+            .executeUpdate();
+    }
+
+    public void deleteByAppIdAndFunctionCdAndRoleId(final Long appId, final String functionCd, final Integer roleId) {
+        entityManager.createQuery("DELETE FROM ep_app_role_function WHERE app_id = :appId and function_cd = :functionCd and role_id = :roleId")
+            .setParameter("appId", appId)
+            .setParameter("functionCd", functionCd)
+            .setParameter("roleId", roleId)
+            .executeUpdate();
+    }
+
+    public void delete(EpAppRoleFunction approleFunction) {
+        epAppRoleFunctionDao.delete(approleFunction);
+    }
+
+    public void deleteInBatch(List<EpAppRoleFunction> appRoleFunctionList) {
+        epAppRoleFunctionDao.deleteInBatch(appRoleFunctionList);
+    }
 }
index 1b999f8..0885b8c 100644 (file)
@@ -1,6 +1,14 @@
 package org.onap.portal.service.microservice;
 
+import java.util.Optional;
+import java.util.Set;
 import org.onap.portal.domain.db.ep.EpMicroservice;
+import org.onap.portal.domain.db.ep.EpMicroserviceParameter;
+import org.onap.portal.service.microserviceParameter.EpMicroserviceParameterService;
+import org.onap.portal.utils.EPCommonSystemProperties;
+import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.onboarding.util.CipherUtil;
+import org.onap.portalsdk.core.util.SystemProperties;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
@@ -9,14 +17,96 @@ import java.util.List;
 @Service
 public class EpMicroserviceService {
 
+    EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(EpMicroserviceService.class);
+
     private final EpMicroserviceDao epMicroserviceDao;
+    private final EpMicroserviceParameterService epMicroserviceParameterService;
 
     @Autowired
-    public EpMicroserviceService(EpMicroserviceDao epMicroserviceDao) {
+    public EpMicroserviceService(EpMicroserviceDao epMicroserviceDao,
+        EpMicroserviceParameterService epMicroserviceParameterService) {
         this.epMicroserviceDao = epMicroserviceDao;
+        this.epMicroserviceParameterService = epMicroserviceParameterService;
     }
 
     public List<EpMicroservice> saveAll(List<EpMicroservice> epMicroservices) {
         return epMicroserviceDao.saveAll(epMicroservices);
     }
+
+    public Optional<EpMicroservice> getById(long serviceId) {
+        return epMicroserviceDao.findById(serviceId);
+    }
+
+    public EpMicroservice saveOne(EpMicroservice newServiceData) {
+        return epMicroserviceDao.save(newServiceData);
+    }
+
+    public List<EpMicroservice> getAll() {
+        return epMicroserviceDao.findAll();
+    }
+
+    public void deleteById(long serviceId) {
+        epMicroserviceDao.deleteById(serviceId);
+    }
+
+    @SuppressWarnings("OptionalGetWithoutIsPresent")
+    public void updateMicroservice(long serviceId, EpMicroservice newServiceData) throws Exception {
+        EpMicroservice newService = getById(serviceId).get();
+        try {
+            newService.setId(serviceId);
+            if (newService.getPassword() != null) {
+                if (newService.getPassword().equals(EPCommonSystemProperties.APP_DISPLAY_PASSWORD)) {
+                    EpMicroservice oldMS = getById(serviceId).get();
+                    newService.setPassword(oldMS.getPassword()); // keep the old password
+                } else {
+                    newService.setPassword(encryptedPassword(newService.getPassword())); //new password
+                }
+            }
+            saveOne(newService);
+            List<EpMicroserviceParameter> oldService = epMicroserviceParameterService.getByServiceId(serviceId);
+            boolean foundParam;
+            for (EpMicroserviceParameter microserviceParameter : oldService) {
+                foundParam = false;
+                for (EpMicroserviceParameter service : newService.getEpMicroserviceParameters()) {
+                    if (service.getId().equals(microserviceParameter.getId())) {
+                        foundParam = true;
+                        break;
+                    }
+                }
+                if (!foundParam) {
+                    epMicroserviceParameterService.deleteOne(microserviceParameter);
+                }
+            }
+            for (EpMicroserviceParameter param : newService.getEpMicroserviceParameters()) {
+                param.setServiceId(newService);
+                epMicroserviceParameterService.save(param);
+            }
+        } catch (Exception e) {
+            logger.error(EELFLoggerDelegate.errorLogger, "updateMicroservice failed", e);
+            throw e;
+        }
+        saveServiceParameters(newService.getId(), newService.getEpMicroserviceParameters());
+    }
+
+    public void saveServiceParameters(Long newServiceId, Set<EpMicroserviceParameter> list) {
+        EpMicroservice newService = getById(newServiceId).get();
+        for (EpMicroserviceParameter para : list) {
+            para.setServiceId(newService);
+            epMicroserviceParameterService.save(para);
+        }
+    }
+
+    private String encryptedPassword(String decryptedPwd) throws Exception {
+        String result = "";
+        if (decryptedPwd != null && !decryptedPwd.isEmpty()) {
+            try {
+                result = CipherUtil.encryptPKC(decryptedPwd,
+                    SystemProperties.getProperty(SystemProperties.Decryption_Key));
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger, "encryptedPassword failed", e);
+                throw e;
+            }
+        }
+        return result;
+    }
 }
index f4359c5..076e183 100644 (file)
@@ -77,6 +77,10 @@ public class EpMicroserviceParameterService {
               return list;
        }
 
+       public List<EpMicroserviceParameter> getByServiceId(long serviceId) {
+              return epMicroserviceParameterDao.getParametersById(serviceId);
+       }
+
        private MicroserviceParameter epWidgetCatalogParameterToMicroserviceParameter(
                final EpMicroserviceParameter microservice) {
               return new MicroserviceParameter(microservice.getId(), microservice.getServiceId().getId(),
@@ -105,4 +109,8 @@ public class EpMicroserviceParameterService {
        public List<EpMicroserviceParameter> saveAll(List<EpMicroserviceParameter> epMicroserviceParameters) {
               return epMicroserviceParameterDao.saveAll(epMicroserviceParameters);
        }
+
+       public void deleteOne(EpMicroserviceParameter microserviceParameter) {
+              epMicroserviceParameterDao.delete(microserviceParameter);
+       }
 }
index e12391d..057f873 100644 (file)
@@ -41,6 +41,8 @@
 package org.onap.portal.service.role;
 
 import java.util.List;
+import java.util.Optional;
+import javax.swing.text.html.Option;
 import org.onap.portal.domain.db.fn.FnRole;
 import org.springframework.data.jpa.repository.JpaRepository;
 import org.springframework.data.jpa.repository.Query;
@@ -52,31 +54,41 @@ import org.springframework.transaction.annotation.Transactional;
 @Transactional
 interface FnRoleDao extends JpaRepository<FnRole, Long> {
 
-  @Query
-  List<FnRole> retrieveAppRoleByAppRoleIdAndByAppId(final @Param("appId") Long appId,
-      final @Param("appRoleId") Long appRoleId);
+    @Query
+    List<FnRole> retrieveAppRoleByAppRoleIdAndByAppId(final @Param("appId") Long appId,
+        final @Param("appRoleId") Long appRoleId);
 
-  @Query
-  List<FnRole> getUserRoleOnUserIdAndAppId(final @Param("userId") Long userId, final @Param("appId") Long appId);
+    @Query
+    List<FnRole> getUserRoleOnUserIdAndAppId(final @Param("userId") Long userId, final @Param("appId") Long appId);
 
-  @Query
-  List<FnRole> retrieveAppRoleByRoleIdWhereAppIdIsNull(final @Param("roleId") Long roleId);
+    @Query
+    List<FnRole> retrieveAppRoleByRoleIdWhereAppIdIsNull(final @Param("roleId") Long roleId);
 
-  @Query
-  List<FnRole> retrieveAppRolesWhereAppIdIsNull();
+    @Query
+    List<FnRole> retrieveAppRolesWhereAppIdIsNull();
 
-  @Query
-  List<FnRole> retrieveAppRolesByAppId(final @Param("appId") Long id);
+    @Query
+    List<FnRole> retrieveAppRolesByAppId(final @Param("appId") Long id);
 
-  @Query
-  List<FnRole> retrieveActiveRolesOfApplication(final @Param("appId") Long appId);
+    @Query
+    List<FnRole> retrieveActiveRolesOfApplication(final @Param("appId") Long appId);
 
-  @Query
-  List<FnRole> retrieveAppRolesByRoleNameAndByAppId(final @Param("roleName") String roleName, final @Param("appId") Long appId);
+    @Query
+    List<FnRole> retrieveAppRolesByRoleNameAndByAppId(final @Param("roleName") String roleName,
+        final @Param("appId") Long appId);
 
-  @Query
-  List<FnRole> getGlobalRolesOfPortal();
+    @Query
+    List<FnRole> getGlobalRolesOfPortal();
 
-  @Query
-  FnRole getSysAdminRoleId();
+    @Query
+    FnRole getSysAdminRoleId();
+
+    @Query
+    Optional<List<FnRole>> retrieveAppRolesByRoleNameAndWhereAppIdIsNull(final @Param("roleName") String roleName);
+
+    @Query
+    Optional<List<FnRole>> userAppGlobalRoles(final @Param("userId") long userId, final @Param("appId") long appId);
+
+    @Query
+    Optional<List<FnRole>> retrieveActiveRolesWhereAppIdIsNull();
 }
index d73ae66..3d489ae 100644 (file)
@@ -126,6 +126,10 @@ public class FnRoleService {
     return Optional.of(fnRoleDao.retrieveActiveRolesOfApplication(appId)).orElse(new ArrayList<>());
   }
 
+  public List<FnRole> retrieveAppRolesByRoleNameAndWhereAppIdIsNull(final String roleName){
+    return fnRoleDao.retrieveAppRolesByRoleNameAndWhereAppIdIsNull(roleName).orElse(new ArrayList<>());
+  }
+
   public List<FnRole> getGlobalRolesOfPortal() {
     List<FnRole> globalRoles = new ArrayList<>();
     try {
@@ -152,4 +156,13 @@ public class FnRoleService {
   public List<FnRole> saveAll(List<FnRole> fnRoles) {
     return fnRoleDao.saveAll(fnRoles);
   }
+
+  public List<FnRole> userAppGlobalRoles(final Long userId, final Long appId) {
+      return fnRoleDao.userAppGlobalRoles(userId, appId).orElse(new ArrayList<>());
+  }
+
+
+  public List<FnRole> retrieveActiveRolesWhereAppIdIsNull() {
+      return fnRoleDao.retrieveActiveRolesWhereAppIdIsNull().orElse(new ArrayList<>());
+  }
 }
index a91dee8..797d29d 100644 (file)
@@ -1,5 +1,6 @@
 package org.onap.portal.service.roleFunction;
 
+import java.util.Optional;
 import org.onap.portal.domain.db.fn.FnRoleFunction;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
@@ -19,4 +20,12 @@ public class FnRoleFunctionService {
     public List<FnRoleFunction> saveAll(List<FnRoleFunction> roleFunctions) {
         return fnRoleFunctionDao.saveAll(roleFunctions);
     }
+
+    public List<FnRoleFunction> findAll(){
+        return fnRoleFunctionDao.findAll();
+    }
+
+    public Optional<FnRoleFunction> findById(final Long id) {
+        return fnRoleFunctionDao.findById(id);
+    }
 }
index f7a150d..197b2b2 100644 (file)
@@ -68,4 +68,7 @@ interface FnUserDao extends JpaRepository<FnUser, Long> {
        @Query
        Optional<List<FnUser>> getActiveUsers();
 
+       @Query
+       Optional<List<FnUser>> findByFirstNameAndLastName(final @Param("firstName") String firstName, final @Param("lastName") String lastName);
+
 }
index 23732d6..7962755 100644 (file)
 
 package org.onap.portal.service.user;
 
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Optional;
+import org.hibernate.criterion.Criterion;
+import org.hibernate.criterion.Restrictions;
+import org.json.JSONArray;
+import org.json.JSONObject;
 import org.onap.portal.domain.db.fn.FnUser;
+import org.onap.portal.utils.EPCommonSystemProperties;
+import org.onap.portal.utils.EPSystemProperties;
+import org.onap.portalsdk.core.domain.FusionObject.Utilities;
 import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
+import org.onap.portalsdk.core.util.SystemProperties;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.repository.query.Param;
 import org.springframework.security.core.userdetails.UserDetailsService;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.stereotype.Service;
@@ -55,66 +70,199 @@ import org.springframework.transaction.annotation.Transactional;
 @Transactional
 public class FnUserService implements UserDetailsService {
 
-       private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserService.class);
+    private final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(FnUserService.class);
 
-       private final FnUserDao fnUserDao;
+    private final FnUserDao fnUserDao;
 
-       @Autowired
-       public FnUserService(FnUserDao fnUserDao) {
-              this.fnUserDao = fnUserDao;
-       }
+    @Autowired
+    public FnUserService(FnUserDao fnUserDao) {
+        this.fnUserDao = fnUserDao;
+    }
 
-       @Override
-       public FnUser loadUserByUsername(final String username) throws UsernameNotFoundException {
-              Optional<FnUser> fnUser = fnUserDao.findByLoginId(username);
-              if (fnUser.isPresent()) {
-                     return fnUser.get();
-              } else {
-                     throw new UsernameNotFoundException("User not found for username: " + username);
-              }
-       }
+    @Override
+    public FnUser loadUserByUsername(final String username) throws UsernameNotFoundException {
+        Optional<FnUser> fnUser = fnUserDao.findByLoginId(username);
+        if (fnUser.isPresent()) {
+            return fnUser.get();
+        } else {
+            throw new UsernameNotFoundException("User not found for username: " + username);
+        }
+    }
 
-       public FnUser saveFnUser(final FnUser fnUser) {
-              return fnUserDao.save(fnUser);
-       }
+    public FnUser saveFnUser(final FnUser fnUser) {
+        return fnUserDao.save(fnUser);
+    }
 
-       public Optional<FnUser> getUser(final Long id) {
-              return Optional.of(fnUserDao.getOne(id));
-       }
+    public Optional<FnUser> getUser(final Long id) {
+        return Optional.of(fnUserDao.getOne(id));
+    }
 
-       public List<FnUser> getUserWithOrgUserId(final String orgUserIdValue) {
-              return fnUserDao.getUserWithOrgUserId(orgUserIdValue).orElse(new ArrayList<>());
-       }
+    public List<FnUser> getUserWithOrgUserId(final String orgUserIdValue) {
+        return fnUserDao.getUserWithOrgUserId(orgUserIdValue).orElse(new ArrayList<>());
+    }
 
-       public List<FnUser> getUsersByOrgIds(final List<String> orgIds) {
-              return fnUserDao.getUsersByOrgIds(orgIds).orElse(new ArrayList<>());
-       }
+    public List<FnUser> getUsersByOrgIds(final List<String> orgIds) {
+        return fnUserDao.getUsersByOrgIds(orgIds).orElse(new ArrayList<>());
+    }
 
-       public List<FnUser> getActiveUsers() {
-              return fnUserDao.getActiveUsers().orElse(new ArrayList<>());
-       }
+    public List<FnUser> getActiveUsers() {
+        return fnUserDao.getActiveUsers().orElse(new ArrayList<>());
+    }
 
-       public void deleteUser(final FnUser fnUser) {
-              fnUserDao.delete(fnUser);
-       }
+    public void deleteUser(final FnUser fnUser) {
+        fnUserDao.delete(fnUser);
+    }
 
-       public boolean existById(final Long userId) {
-              return fnUserDao.existsById(userId);
-       }
+    public boolean existById(final Long userId) {
+        return fnUserDao.existsById(userId);
+    }
 
-       public List<FnUser> findAll() {
-              return fnUserDao.findAll();
-       }
+    public List<FnUser> findAll() {
+        return fnUserDao.findAll();
+    }
 
-       public List<FnUser> saveAll(final List<FnUser> fnUsers) {
-              return fnUserDao.saveAll(fnUsers);
-       }
+    public List<FnUser> saveAll(final List<FnUser> fnUsers) {
+        return fnUserDao.saveAll(fnUsers);
+    }
 
-       public FnUser save(final FnUser user) {
-              return fnUserDao.save(user);
-       }
+    public FnUser save(final FnUser user) {
+        return fnUserDao.save(user);
+    }
 
-       public void delete(final FnUser user) {
-              fnUserDao.delete(user);
-       }
+    public void delete(final FnUser user) {
+        fnUserDao.delete(user);
+    }
+
+    public List<FnUser> findByFirstNameAndLastName(final String firstName, final String lastName) {
+        return fnUserDao.findByFirstNameAndLastName(firstName, lastName).orElse(new ArrayList<>());
+    }
+
+    public List<FnUser> getUserByUserId(String userId) {
+        if (SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) {
+            List<FnUser> users = new ArrayList<>();
+            List<FnUser> filterdUsers = new ArrayList<>();
+            BufferedReader in = null;
+            HttpURLConnection con = null;
+            try {
+                String url = EPSystemProperties.getProperty(EPSystemProperties.AUTH_USER_SERVER);
+                URL obj = new URL(url);
+
+                con = (HttpURLConnection) obj.openConnection();
+
+                // optional default is GET
+                con.setRequestMethod("GET");
+                con.setConnectTimeout(3000);
+                con.setReadTimeout(8000);
+
+                StringBuffer response = new StringBuffer();
+
+                in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
+                String inputLine;
+                while ((inputLine = in.readLine()) != null) {
+                    response.append(inputLine);
+                }
+                JSONObject jObject = new JSONObject(response.toString()); // json
+                JSONArray jsonUsers = jObject.getJSONArray("response"); // get data object
+                for (int i = 0; i < jsonUsers.length(); i++) {
+                    JSONObject eachObject = jsonUsers.getJSONObject(i);
+                    FnUser eachUser = new FnUser();
+                    eachUser.setOrgUserId(eachObject.get("id").toString());// getString("id"));
+                    eachUser.setFirstName(eachObject.get("givenName").toString());
+                    eachUser.setLastName(eachObject.get("familyName").toString());
+                    eachUser.setEmail(eachObject.get("email").toString());
+                    users.add(eachUser);
+                }
+
+                for (FnUser user : users) {
+
+                    if (Utilities.nvl(userId).length() > 0) {
+                        if (!userId.equalsIgnoreCase(user.getOrgUserId())) {
+                            continue;
+                        }
+                    }
+                    filterdUsers.add(user);
+
+                }
+
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger, "getUserByUserId failed", e);
+            } finally {
+                try {
+                    if (in != null) {
+                        in.close();
+                    }
+                    con.disconnect();
+                } catch (IOException e) {
+                    logger.error(EELFLoggerDelegate.errorLogger, "getUserByUserId 2 failed", e);
+                }
+            }
+            return filterdUsers;
+        } else {
+            List<FnUser> list = this.getUserWithOrgUserId(userId);
+            return (list == null || list.size() == 0) ? null : list;
+        }
+
+    }
+
+    public List<FnUser> getUserByFirstLastName(String firstName, String lastName) {
+        if (!SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM).trim().equalsIgnoreCase("OIDC")) {
+            List<FnUser> list = this.findByFirstNameAndLastName(firstName, lastName);
+            return (list == null || list.size() == 0) ? null : list;
+        } else {
+            List<FnUser> users = new ArrayList<>();
+            List<FnUser> filterdUsers = new ArrayList<>();
+            BufferedReader in = null;
+            HttpURLConnection con = null;
+            try {
+                String url = EPCommonSystemProperties.getProperty(EPCommonSystemProperties.AUTH_USER_SERVER);
+                URL obj = new URL(url);
+                con = (HttpURLConnection) obj.openConnection();
+                con.setRequestMethod("GET");
+                con.setConnectTimeout(3000);
+                con.setReadTimeout(8000);
+                StringBuffer response = new StringBuffer();
+                in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
+                String inputLine;
+                while ((inputLine = in.readLine()) != null) {
+                    response.append(inputLine);
+                }
+                JSONObject jObject = new JSONObject(response.toString());
+                JSONArray jsonUsers = jObject.getJSONArray("response");
+                for (int i = 0; i < jsonUsers.length(); i++) {
+                    JSONObject eachObject = jsonUsers.getJSONObject(i);
+                    FnUser eachUser = new FnUser();
+                    eachUser.setOrgUserId(eachObject.get("id").toString());
+                    eachUser.setFirstName(eachObject.get("givenName").toString());
+                    eachUser.setLastName(eachObject.get("familyName").toString());
+                    eachUser.setEmail(eachObject.get("email").toString());
+                    users.add(eachUser);
+                }
+                for (FnUser user : users) {
+                    if (Utilities.nvl(firstName).length() > 0) {
+                        if (!firstName.equalsIgnoreCase(user.getFirstName())) {
+                            continue;
+                        }
+                    }
+                    if (Utilities.nvl(lastName).length() > 0) {
+                        if (!lastName.equalsIgnoreCase(user.getLastName())) {
+                            continue;
+                        }
+                    }
+                    filterdUsers.add(user);
+                }
+            } catch (Exception e) {
+                logger.error(EELFLoggerDelegate.errorLogger, "getUserByFirstLastName failed", e);
+            } finally {
+                try {
+                    if (in != null) {
+                        in.close();
+                        con.disconnect();
+                    }
+                } catch (IOException e) {
+                    logger.error(EELFLoggerDelegate.errorLogger, "getUserByFirstLastName failed to close", e);
+                }
+            }
+            return filterdUsers;
+        }
+    }
 }
index eb7ece2..86ee03f 100644 (file)
@@ -474,6 +474,11 @@ public class FnUserRoleService {
     fnUserRoleDao.deleteById(id);
   }
 
+  public void deleteByUserIdAndRoleId(final Long userId, final String roleId){
+    final String query =  "DELETE FROM FnUserRole id = :userId AND roleId.id = :roleId";
+    entityManager.createQuery(query).setParameter("userId", userId).setParameter("roleId", roleId).executeUpdate();
+  }
+
   public List<RoleInAppForUser> constructRolesInAppForUserGet(List<Role> appRoles, FnRole[] userAppRoles,
       Boolean extRequestValue) {
     List<RoleInAppForUser> rolesInAppForUser = new ArrayList<>();
index f8641f0..57a6c9f 100644 (file)
@@ -51,18 +51,19 @@ import org.springframework.transaction.annotation.Transactional;
 @Service
 @Transactional
 public class EpUserRolesRequestDetService {
-       private final EpUserRolesRequestDetDao epUserRolesRequestDetDao;
 
-       @Autowired
-       public EpUserRolesRequestDetService(EpUserRolesRequestDetDao epUserRolesRequestDetDao) {
-              this.epUserRolesRequestDetDao = epUserRolesRequestDetDao;
-       }
+    private final EpUserRolesRequestDetDao epUserRolesRequestDetDao;
 
-       public EpUserRolesRequestDet saveOne(EpUserRolesRequestDet epUserRolesRequestDet){
-              return epUserRolesRequestDetDao.save(epUserRolesRequestDet);
-       }
+    @Autowired
+    public EpUserRolesRequestDetService(EpUserRolesRequestDetDao epUserRolesRequestDetDao) {
+        this.epUserRolesRequestDetDao = epUserRolesRequestDetDao;
+    }
 
-       public List<EpUserRolesRequestDet> appRolesRequestDetailList(final Long reqId){
-              return Optional.of(epUserRolesRequestDetDao.appRolesRequestDetailList(reqId)).orElse(new ArrayList<>());
-       }
+    public EpUserRolesRequestDet saveOne(EpUserRolesRequestDet epUserRolesRequestDet) {
+        return epUserRolesRequestDetDao.save(epUserRolesRequestDet);
+    }
+
+    public List<EpUserRolesRequestDet> appRolesRequestDetailList(final Long reqId) {
+        return Optional.of(epUserRolesRequestDetDao.appRolesRequestDetailList(reqId)).orElse(new ArrayList<>());
+    }
 }
diff --git a/portal-BE/src/main/java/org/onap/portal/utils/EPSystemProperties.java b/portal-BE/src/main/java/org/onap/portal/utils/EPSystemProperties.java
new file mode 100644 (file)
index 0000000..9db97ce
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * ============LICENSE_START==========================================
+ * ONAP Portal
+ * ===================================================================
+ * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
+ * ===================================================================
+ * Modifications Copyright (c) 2019 Samsung
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *             https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END============================================
+ *
+ *
+ */
+
+package org.onap.portal.utils;
+
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.context.annotation.PropertySources;
+
+@Configuration
+@PropertySources({
+    @PropertySource("classpath:/WEB-INF/conf/system.properties"),
+    @PropertySource("classpath:/WEB-INF/conf/sql.properties"),
+    @PropertySource("classpath:/WEB-INF/fusion/conf/fusion.properties"),
+   //@PropertySource(value = "file:${catalina.home}/conf/system.properties", ignoreResourceNotFound = true),
+   //@PropertySource(value = "file:${catalina.home}/conf/fusion.properties", ignoreResourceNotFound = true)
+})
+
+public class EPSystemProperties extends EPCommonSystemProperties {
+
+    public static final String CONTACT_US_URL = "contact_us_link";
+    public static final String ECOMP_CONTEXT_ROOT = "context_root";
+
+}
diff --git a/portal-BE/src/main/resources/WEB-INF/conf/cache.ccf b/portal-BE/src/main/resources/WEB-INF/conf/cache.ccf
new file mode 100644 (file)
index 0000000..b8a2363
--- /dev/null
@@ -0,0 +1,30 @@
+# DEFAULT CACHE REGION
+jcs.default=DC
+jcs.default.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes
+jcs.default.cacheattributes.MaxObjects=1000
+jcs.default.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache
+jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes
+jcs.default.elementattributes.IsEternal=true
+jcs.default.elementattributes.IsSpool=true
+
+
+# MEMORY SHRINKING CONFIGURATION (Commented)
+#jcs.default.cacheattributes.UseMemoryShrinker=true
+#jcs.default.cacheattributes.MaxMemoryIdleTimeSeconds=3600
+#jcs.default.cacheattributes.ShrinkerIntervalSeconds=60
+#jcs.default.cacheattributes.MaxSpoolPerRun=500
+#jcs.default.elementattributes=org.apache.jcs.engine.ElementAttributes
+#jcs.default.elementattributes.IsEternal=false
+
+
+# AUXILLARY CACHE CONFIGURATION
+jcs.auxiliary.DC=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheFactory
+jcs.auxiliary.DC.attributes=org.apache.jcs.auxiliary.disk.indexed.IndexedDiskCacheAttributes
+jcs.auxiliary.DC.attributes.DiskPath=fusion/cache
+
+
+# PRE-DEFINED REGION FOR LOOKUP DATA
+jcs.region.lookUpObjectCache=DC
+jcs.region.lookUpObjectCache.cacheattributes=org.apache.jcs.engine.CompositeCacheAttributes
+jcs.region.lookUpObjectCache.cacheattributes.MaxObjects=4000
+jcs.region.lookUpObjectCache.cacheattributes.MemoryCacheName=org.apache.jcs.engine.memory.lru.LRUMemoryCache
diff --git a/portal-BE/src/main/resources/WEB-INF/conf/quartz.properties b/portal-BE/src/main/resources/WEB-INF/conf/quartz.properties
new file mode 100644 (file)
index 0000000..12b731a
--- /dev/null
@@ -0,0 +1,73 @@
+###
+# ============LICENSE_START==========================================
+# ONAP Portal
+# ===================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the "License");
+# you may not use this software except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# ============LICENSE_END============================================
+#
+# 
+###
+#################################################################################
+# Quartz configurations for Quantum Work Flow                                                                  #
+#################################################################################
+
+org.quartz.scheduler.instanceId = AUTO
+
+#################################################################################
+# Main configurations
+org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
+org.quartz.threadPool.threadCount = 30
+
+============================================================================
+# Configure JobStore  
+#============================================================================
+
+org.quartz.jobStore.misfireThreshold = 60000
+
+org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
+org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
+org.quartz.jobStore.useProperties = false
+#org.quartz.jobStore.dataSource = myDS
+org.quartz.jobStore.tablePrefix = FN_QZ_
+
+org.quartz.jobStore.isClustered = true
+org.quartz.jobStore.clusterCheckinInterval = 20000
+
+#============================================================================
+# Configure Datasources  
+#============================================================================
+
+#org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
+#org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/portal
+#org.quartz.dataSource.myDS.user = todo
+#org.quartz.dataSource.myDS.password = todo
+#org.quartz.dataSource.myDS.maxConnections = 5
+#org.quartz.dataSource.myDS.validationQuery=select 0 from dual
diff --git a/portal-BE/src/main/resources/WEB-INF/conf/raptor.properties b/portal-BE/src/main/resources/WEB-INF/conf/raptor.properties
new file mode 100644 (file)
index 0000000..34bc8c9
--- /dev/null
@@ -0,0 +1,203 @@
+###
+# ============LICENSE_START==========================================
+# ONAP Portal
+# ===================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the "License");
+# you may not use this software except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# ============LICENSE_END============================================
+#
+# 
+###
+##C## Mention the name of the framework. At present RAPTOR supports FUSION
+system=fusion
+##C## Determines the priority for the debug message.
+debug_level=5
+##C## Determines the number of records can be downloaded in excel when you select "download all" option.
+download_limit=65000
+csv_download_limit=10
+##C## Determines the number of records to be displayed in a single page.
+default_page_size=50
+##C## Determines the list size in the form field.
+form_fields_list_size=99000
+##C## Determines the scheduler interval
+#scheduler_interval=0 => disabled
+scheduler_interval=0
+##C## System Name
+system_name=RAPTOR
+##C## This is used for Bread crumbs.
+base_title=ANALYSIS
+##C## whether to allow SQL-based report definition (security risk); super users are always allowed to create SQL-based reports
+allow_sql_based_reports=no
+##C## Determines whether to include disclaimer page at the bottom of each screen
+show_disclaimer=yes
+disclaimer_positioned_top_in_csvexcel=yes
+##C## Determines whether to display the form page as a separate page before running the report
+display_form_before_run=yes
+##C## Determines whether to include the form page on the report data page
+include_form_with_data=yes
+##C## Determines whether to cache chart data in the session => faster re-display if the data volume does not get too large
+cache_chart_data=yes
+##C## Determines whether to cache report data for the currently displayed page in the session => faster re-display
+       ##C## if the data volume does not get too large
+cache_cur_page_data=yes
+##C## Determines Chart width
+default_chart_width=700
+##C## Determines Chart height
+default_chart_height=420
+##C## Determines whether to permit report deletion only by report owner or by everyone with "write" access
+delete_only_by_owner=yes
+##C## Determines whether to log each report execution and update time and user ID
+enable_report_log=yes
+##C## Determines whether to cache user roles info in memory (saves many DB reads, but does not account for roles
+       ##C## assigned after the cache was loaded)
+cache_user_roles=yes
+##C## Determines whether to convert month formats (e.g. MM/YYYY) to the last day of the month (true) or
+        ##C## first day (false) - like 12/2003 is converted to either 12/31/2003 or 12/01/2003
+month_format_use_last_day=no
+##C## Determines whether to print the report title in the download files
+print_title_in_download=yes
+##C## Determines whether to show report description when the report is run and in the quick links
+show_descr_at_runtime=no
+##C## Determines whether to skip labels on the Line chart axis when they overlap
+#DEPRECATED skip_chart_labels_to_fit=no
+##C## Determines whether to show chart types that are purpose and/or data specific
+show_nonstandard_charts=yes
+##C## Determines whether to allow the user to change the chart type at runtime
+allow_runtime_chart_sel=yes
+##C## Determines whether to display the report title as chart title as well
+display_chart_title=yes
+##C## Determines whether to merge/blank multi-level row headings in cross-tab report
+merge_crosstab_row_headings=yes
+##C## Determines whether to display chart when displaying the report at first or just a "Show Chart" button
+display_chart_by_default=yes
+##C## Determines whether to print the form field values in the download files
+print_params_in_download=yes
+##C## Determines the limitation to the characters in chart label.
+skip_chart_labels_limit=30
+##C## Determines whether to users with read-only rights for a report can copy it
+can_copy_on_read_only=yes
+##C## Determines the no of decimals to be displayed in Totals column
+#max_decimals_on_totals=-1 => don't truncate, display all decimal digits
+max_decimals_on_totals=2
+##C## Determines which JFreeChart to use.
+jfree_version=latest
+#jfree_version=0.9.11
+# Added this restriction so that heavily used system which contain
+# more than 1000 users can enable this feature not to display whole
+# users in the drop down menu
+display_all_users=yes
+##Sheet name
+sheet_name=raptor
+#shell_script_name=/home/sundar/test.sh
+#download_query_folder=/titan/PROJECT3/RAPTOR/raptor/dwnld/query/
+## this directory is mentioned if the flat file is downloaded using shell script
+shell_script_dir=/titan/PROJECT3/RAPTOR/raptor/dwnld/
+flat_file_lower_limit=1
+flat_file_upper_limit=200000
+## whatever request mentioned here would be parsed in sql and request parameter would be filled
+request_get_params=c_master,isEmbedded
+print_footer_in_download=yes
+## footer mentioned here appears in downloaded excel
+footer_first_line=Raptor
+footer_second_line=Use Pursuant to Company Instructions
+## to run report in popup window
+report_in_popup_window=yes
+## to run each report in new popup window if the above is selected
+popup_in_new_window=yes
+## "Yes" allows the request param to be passed to the drill down report
+pass_request_param_in_drilldown=yes
+## Show PDF download icon
+show_pdf_download=yes
+# Show Folder Tree
+show_folder_tree=no
+#Show folder tree only for Admin Users
+show_folder_tree_only_to_admin_users=no
+#folder tree should be minimized
+folder_tree_minimized=yes
+## whatever session mentioned here would be parsed in sql and session parameter would be filled
+session_params=login_id
+display_formfield_info=yes
+customize_formfield_info=yes
+#schedule limit for end users
+schedule_limit=10
+# customized query if you need any restrictions for schedule and security tab for fusion
+#schedule_custom_query_for_users=getAllUsersByCustomer
+#schedule_custom_query_for_roles=getAllRolesByCustomer
+# customized query if you need any restrictions for schedule and security tab for prisms example
+#schedule_custom_query_for_users=SELECT au.user_id, au.first_name||' '||au.last_name user_name FROM app_user au order by 2
+schedule_custom_query_for_users=SELECT au.user_id id, au.first_name||' '||au.last_name name FROM app_user au where user_id = 1 order by 2
+#schedule_custom_query_for_roles=SELECT ar.role_id, ar.descr role_name FROM app_role ar order by 2
+schedule_date_pattern=MM/dd/yyyy hh:mm:ss a
+## This is used to display in right format in chart timestamp axis as we give in the sql
+#chart_yearly_format=yyyy
+#chart_monthly_format=MMM-yyyy
+#chart_daily_format=MM-dd-yyyy
+chart_hourly_format=MM/dd HH
+#chart_minute_format=HH:mm
+chart_minute_format=MM-dd-yyyy-HH:mm
+#chart_second_format=HH:mm:ss
+chart_second_format=MM-dd-yyyy
+#chart_millisecond_format=HH:mm:ss.S
+schedule_help_text=This form is used to schedule a specific Reporting Platform report to be delivered to one or more email addresses associated with your Company's Business Direct user logins.  Note that report output delivered via email does not include the capability to drill down/back up to additional data levels.  So, select the appropriate data level report for the scheduled report.  View the status of scheduled report requests in the My Schedules menu item.
+use_loginid_in_schedYN=Y
+session_params_for_scheduling=login_id
+session_date_formfield_auto_incr=yes
+display_session_param_pdfexcel=login_id;Login Id
+session_params_for_displaying_in_scheduling=login_id;Login Id
+application_server=tomcat
+#gmap properties
+gmap_key=ABQIAAAAToJSSetKBMjBJx8MiRw4ghQiU0SbbKnm8C5eu25cpyLwgkLzyRShrQTbgZtqnKAqZU9JwcSq1bKwiA
+PROJECT-FOLDER=/Users/sundar/git/st_quantum/quantum/target/quantum-1.0
+# 
+MARKET-SHAPEFILE-FOLDER=resources/files
+# output folder for files generated on server side
+OUTPUT-FOLDER=resources/temp
+# tile size in pixel
+TILE-SIZE=256
+#check if map is disabled or not
+map_allowed=Y
+max_drilldown_level=2
+admin_role_equiv_to_super_role=N
+show_loading_during_formfield_chain=Y
+show_print_icon=N
+globally_nowrap=N
+calendar_output_date_format=MM/dd/yyyy
+memory_threshold_percentage=99
+print_params_in_csv_download=yes
+notitle_in_dashboard=yes
+generate_store_sched_reports=yes
+show_excel_2007_download=yes
+print_excel_in_landscape=yes
+show_animated_chart_option=yes
+show_animated_chart_only=no
+adjust_content_based_on_height=yes
+custom_submit_button_text=Run Button
+customize_formfield_layout=yes
+db_type=postgresql
diff --git a/portal-BE/src/main/resources/WEB-INF/conf/raptor_app_fusion.properties b/portal-BE/src/main/resources/WEB-INF/conf/raptor_app_fusion.properties
new file mode 100644 (file)
index 0000000..8c9190c
--- /dev/null
@@ -0,0 +1,54 @@
+###
+# ============LICENSE_START==========================================
+# ONAP Portal
+# ===================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the "License");
+# you may not use this software except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# ============LICENSE_END============================================
+#
+# 
+###
+temp_folder_path=/Users/sundar/git/st_quantum/quantum/target/quantum-1.0/temp/
+upload_folder_path=/Users/sundar/git/st_quantum/quantum/target/quantum-1.0/files/
+excel_template_path=/Users/sundar/git/st_quantum/quantum/target/quantum-1.0/files/raptor_template/
+temp_folder_url=temp/
+upload_folder_url=upload/
+smtp_server=todo_url
+default_email_sender=dev-local@email.com
+error_page=error_page.jsp
+jsp_context_path=raptor/
+img_folder_url=static/fusion/raptor/images/
+base_folder_url=static/fusion/raptor/
+direct_access_url=http://localhost:8080/quantum/raptor_email_attachment.htm?action=raptor&source_page=report_run&display_content=y
+base_action_url=raptor.htm?action=
+base_action_param=c_master=
+super_role_id=1
+admin_role_ids=1
+quick_links_menu_ids=HOME,CUSTOMER,REPORTS
diff --git a/portal-BE/src/main/resources/WEB-INF/conf/raptor_db_fusion.properties b/portal-BE/src/main/resources/WEB-INF/conf/raptor_db_fusion.properties
new file mode 100644 (file)
index 0000000..a0c26f7
--- /dev/null
@@ -0,0 +1,37 @@
+###
+# ============LICENSE_START==========================================
+# ONAP Portal
+# ===================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the "License");
+# you may not use this software except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# ============LICENSE_END============================================
+#
+# 
+###
diff --git a/portal-BE/src/main/resources/WEB-INF/conf/raptor_pdf.properties b/portal-BE/src/main/resources/WEB-INF/conf/raptor_pdf.properties
new file mode 100644 (file)
index 0000000..f511769
--- /dev/null
@@ -0,0 +1,67 @@
+###
+# ============LICENSE_START==========================================
+# ONAP Portal
+# ===================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the "License");
+# you may not use this software except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# ============LICENSE_END============================================
+#
+# 
+###
+## pdf file specific properties
+pdf_data_font_size=9
+pdf_data_font_family=Arial
+#reduce the font size from html config
+pdf_data_font_size_offset=2
+pdf_data_alternate_color=true
+#data row background(white), alternate(light light blue/gray)
+pdf_data_background_alternate_hex_code=#EDEDED
+pdf_data_default_background_hex_code=#FFFFFF
+#header font (white)  background (gray)
+pdf_data_table_header_font_hex_code=#FFFFFF
+pdf_data_table_header_background_hex_code=#8A9BB3
+#footer header
+pdf_footer_font_size=9
+pdf_footer_font_family=Arial
+pdf_proprietary=xxxx
+pdf_proprierary_font_size=7
+pdf_date_timezone=GMT
+pdf_date_pattern=MM/dd/yyyy hh:mm:ss a
+##page number position at 1 - footer middle, 0 -- header right, 2 - both
+pdf_page_number_position=1
+pdf_word_before_page_number=Page
+pdf_word_after_page_number=
+pdf_coverpage_firstcolumn_size=0.3
+pdf_image_auto_rotate=false
+display_create_owner_info=true
+#session_info=customer,customerId
+display_loginid_for_downloaded_by=false
+# please use false if you want landscape to be default.
+is_default_orientation_portrait=true
diff --git a/portal-BE/src/main/resources/WEB-INF/conf/scheduler.properties b/portal-BE/src/main/resources/WEB-INF/conf/scheduler.properties
new file mode 100644 (file)
index 0000000..ce52554
--- /dev/null
@@ -0,0 +1,61 @@
+###
+# ============LICENSE_START==========================================
+# ONAP Portal
+# ===================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the "License");
+# you may not use this software except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# ============LICENSE_END============================================
+#
+# 
+###
+
+
+##scheduler authentication credentials
+scheduler.user.name=test1
+scheduler.password=test2
+#scheduler properties
+scheduler.server.url=http://mtanjv9sdlg10.aic.cip.onap.com:8989/scheduler
+scheduler.create.new.vnf.change.instance=/v1/ChangeManagement/schedules/
+scheduler.get.time.slots=/v1/ChangeManagement/schedules/
+scheduler.submit.new.vnf.change=/v1/ChangeManagement/schedules/{scheduleId}/approvals
+vid.truststore.filename=C:\\Temp\\vid_keystore.jks
+vid.truststore.passwd.x=OBF:1wgg1wfq1uus1uui1x131x0r1x1v1x1j1uvo1uve1wg81wfi
+
+#scheduler-policy properties
+policy.server.url=https://policypdp-conexus-e2e.ecomp.cci.onap.com:8081/pdp
+policy.get.config=/api/getConfig
+policy.ClientAuth=UHlQRFBTZXJ2ZXI6dGVzdA==
+policy.client.mechId=m06814@controller.dcae.ecomp.onap.com
+policy.client.password=OBF:1ffu1qvu1t2z1l161fuk1i801nz91ro41xf71xfv1rqi1nx51i7y1fuq1kxw1t371qxw1fh0
+policy.username=testpdp
+policy.password=OBF:1igd1kft1l1a1sw61svs1kxs1kcl1idt
+policy.Authorization=dGVzdHBkcDphbHBoYTEyMw==
+policy.environment=TEST
+
diff --git a/portal-BE/src/main/resources/WEB-INF/conf/sql.properties b/portal-BE/src/main/resources/WEB-INF/conf/sql.properties
new file mode 100644 (file)
index 0000000..8663cd4
--- /dev/null
@@ -0,0 +1,300 @@
+###
+# ============LICENSE_START==========================================
+# ONAP Portal
+# ===================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the "License");
+# you may not use this software except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# ============LICENSE_END============================================
+#
+# 
+###
+#SQL Statements for PostgreSQL
+
+#ReportLoader.java
+
+load.custom.report.xml = SELECT cr.report_xml FROM cr_report cr WHERE rep_id=?::int
+
+db.update.report.xml = SELECT cr.rep_id, cr.report_xml FROM cr_report cr WHERE rep_id=? FOR UPDATE
+
+update.custom.report.rec = UPDATE cr_report SET title='[Utils.oracleSafe(rw.getReportName())]', descr='[Utils.oracleSafe(rw.getReportDescr())]', public_yn='[(rw.isPublic()]', menu_id='[rw.getMenuID()]', menu_approved_yn='[(rw.isMenuApproved()]', owner_id=[rw.getOwnerID()], maint_id=[rw.getUpdateID()], maint_date=TO_DATE('[rw.getUpdateDate()]', '[Globals.getOracleTimeFormat()]'), dashboard_type_yn='[(rw.isDashboardType()]', dashboard_yn= '[(rw.getReportType().equals(AppConstants.RT_DASHBOARD)]' WHERE rep_id = [rw.getReportID()]
+
+is.report.already.scheduled = select rep_id from cr_report_schedule where rep_id = ?::int
+
+create.custom.report.rec = INSERT INTO cr_report(rep_id, title, descr, public_yn, menu_id, menu_approved_yn, report_xml, owner_id, create_id, create_date, maint_id, maint_date, dashboard_type_yn, dashboard_yn, folder_id) VALUES([rw.getReportID()], '[Utils.oracleSafe(rw.getReportName())]', '[Utils.oracleSafe(rw.getReportDescr())]', '[rw.isPublic()]', '[rw.getMenuID()]', '[rw.isMenuApproved()]', '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>', [rw.getOwnerID()], [rw.getCreateID()], TO_DATE('[rw.getCreateDate()]', '[Globals.getOracleTimeFormat()]'), [rw.getUpdateID()], TO_DATE('[rw.getUpdateDate()]', '[Globals.getOracleTimeFormat()]'), '[rw.isDashboardType()]', '[rw.getReportType().equals(AppConstants.RT_DASHBOARD)]',[rw.getFolderId()]) 
+
+get.user.report.names = SELECT cr.rep_id, cr.title FROM cr_report cr WHERE coalesce(cr.owner_id, cr.create_id) = [userID]                                                      
+                                                               
+get.report.owner.id = SELECT coalesce(cr.owner_id, cr.create_id) AS owner FROM cr_report cr WHERE rep_id = ?::int                                              
+
+delete.report.record.log = DELETE FROM cr_report_log WHERE rep_id = [reportID]
+
+delete.report.record.users = DELETE FROM cr_report_schedule_users WHERE rep_id = [reportID]
+
+delete.report.record.schedule = DELETE FROM cr_report_schedule WHERE rep_id = [reportID]
+
+delete.report.record.access = DELETE FROM cr_report_access WHERE rep_id = [reportID]
+
+delete.report.record.email = DELETE FROM cr_report_email_sent_log WHERE rep_id = [reportID]
+
+delete.report.record.favorite = DELETE FROM cr_favorite_reports WHERE rep_id = [reportID]
+
+delete.report.record.report = DELETE FROM cr_report WHERE rep_id = [reportID]
+                                                                                                                                                                               
+load.quick.links =  SELECT cr.rep_id, cr.title, cr.descr FROM (SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra LEFT JOIN cr_report cr ON cr.rep_id = ra.rep_id WHERE cr.menu_id LIKE '%[nvls(menuId)]%' AND cr.menu_approved_yn = 'Y' AND (coalesce(cr.owner_id, cr.create_id) = [userID] OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL) ORDER BY cr.title
+
+load.folder.reports = SELECT cr.rep_id, cr.rep_id report_id, [rep_title_sql] || CASE WHEN cr.public_yn = 'Y' THEN '' ELSE '[PRIVATE_ICON]' END||cr.title||'</a>' title, cr.descr, au.first_name||' '||au.last_name owner_name, TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'N' ELSE coalesce(ra.read_only_yn, 'Y') END read_only_yn, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'Y' ELSE 'N' END user_is_owner_yn FROM cr_report cr JOIN app_user au ON coalesce(cr.owner_id, cr.create_id) = au.user_id AND cr.folder_id= '[folderId]' LEFT JOIN (SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL(SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON cr.rep_id = ra.rep_id
+#If roleList.toString() is '' PostgreSQL returns an error - needs to be null instead of empty
+
+load.folder.reports.user = AND coalesce(cr.owner_id, cr.create_id) = [userID]  
+
+load.folder.reports.publicsql = AND (coalesce(cr.owner_id, cr.create_id) = [userID] OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL)
+
+load.quick.download.links = SELECT a.file_name, b.title,to_char(a.dwnld_start_time, 'Dy DD-Mon-YYYY HH24:MI:SS') as time, a.dwnld_start_time FROM cr_report_dwnld_log a, cr_report b where a.user_id = [userID] and a.rep_id = b.rep_id and (a.dwnld_start_time) >= to_date(to_char(now()- interval '1 day', 'mm/dd/yyyy'), 'mm/dd/yyyy') and a.record_ready_time is not null order by a.dwnld_start_time
+
+load.reports.to.schedule = SELECT cr.rep_id, Initcap(cr.title), cr.descr FROM cr_report cr LEFT OUTER JOIN (SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON cr.rep_id = ra.rep_id AND (cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL or cr.owner_id = [userID] )ORDER BY Initcap(cr.title)
+               
+load.reports.to.add.in.dashboard = SELECT cr.rep_id, cr.title, cr.descr FROM cr_report cr LEFT OUTER JOIN (SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON cr.rep_id = ra.rep_id AND (coalesce(cr.owner_id, cr.create_id) = [userID] OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL) AND (cr.dashboard_yn = 'N' or cr.dashboard_yn is null) ORDER BY cr.title
+
+load.my.recent.links = select rep_id, title, descr, form_fields from ( select row_number() OVER () AS rnum, rep_id, title, descr, form_fields from  (select cr.rep_id, cr.title, a.form_fields,  cr.descr, a.log_time, a.user_id, a.action, a.action_value from cr_report_log a, cr_report cr where user_id = [userID] AND action = 'Report Execution Time' and a.rep_id = cr.rep_id order by log_time desc) AS x) AS y where rnum <= 6 AND rnum >= 1
+
+create.report.log.entry = INSERT INTO cr_report_log (rep_id, log_time, user_id, action, action_value, form_fields) VALUES([reportID], now(), [userID], '[action]' , '[executionTime]', '[form_fields]')
+
+create.report.log.entry.exec.time = INSERT INTO cr_report_log (rep_id, log_time, user_id, action, action_value, form_fields) VALUES([reportID], now()+'1 second', [userID], '[action]' , '[executionTime]', '[formFields]')
+
+clear.report.log.entries = DELETE FROM cr_report_log WHERE rep_id = ? and user_id = ?
+
+load.report.log.entries = SELECT x.log_time, x.user_id, (CASE WHEN x.action = 'Report Execution Time' THEN  '<a href=\"[AppUtils.getRaptorActionURL()]report.run.container&c_master='||x.rep_id||'&'||x.form_fields||'&fromReportLog=Y&display_content=Y&noFormFields=Y&refresh=Y\">'||x.action||'</a>' ELSE x.action END) action, (CASE WHEN x.action = 'Report Execution Time' THEN  action_value  ELSE 'N/A' END) time_taken, (CASE WHEN x.action = 'Report Execution Time' THEN '<a href=\"[AppUtils.getRaptorActionURL()]report.run.container&c_master='||x.rep_id||'&'||x.form_fields||'&fromReportLog=Y&display_content=Y&noFormFields=Y&refresh=Y\"><img src=\"[AppUtils.getImgFolderURL()]test_run.gif\" width=\"12\" height=\"12\" border=0 alt=\"Run report\"/></a>' ELSE 'N/A' END) run_image, x.name FROM  (SELECT rl.rep_id, TO_CHAR(rl.log_time, 'Month DD, YYYY HH:MI:SS AM') log_time, rl.action_value, fuser.last_name ||', '||fuser.first_name name, rl.user_id, rl.action, rl.form_fields FROM cr_report_log rl, fn_user fuser WHERE rl.rep_id = [nvls(reportId)] and rl.action != 'Report Run' and fuser.user_id = rl.user_id ORDER BY rl.log_time DESC) x WHERE LIMIT 100
+
+does.user.can.schedule.report = select crs.sched_user_id, count(*) from cr_report_schedule crs where sched_user_id = [userId] group by crs.sched_user_id having count(*) >= [Globals.getScheduleLimit()]
+
+does.user.can.schedule = select crs.schedule_id from cr_report_schedule crs where schedule_id = [scheduleId]
+
+get.system.date.time = select to_char(now(),'MM/dd/yyyy HH24:mi:ss')
+
+get.next.day.date.time = select to_char(now()+'1 day','MM/dd/yyyy HH24:mi:ss')
+
+get.next.fifteen.minutes.date.time = select to_char(now()+'15 min','MM/dd/yyyy HH24:mi:ss')
+
+get.next.thirty.minutes.date.time = select to_char(now()+'30 min','MM/dd/yyyy HH24:mi:ss')
+
+get.template.file = select template_file from cr_report_template_map where report_id = [reportId]
+
+load.pdf.img.lookup = select image_id, image_loc from cr_raptor_pdf_img
+
+load.action.img.lookup = select image_id, image_loc from cr_raptor_action_img
+
+
+#ActionHandler.java
+
+report.values.map.def.a = SELECT x FROM (SELECT DISTINCT 
+
+report.values.map.def.b = TO_CHAR([colName], '[nvl(displayFormat, AppConstants.DEFAULT_DATE_FORMAT)]')
+
+report.values.map.def.c = [colName] 
+
+report.values.map.def.d =  x FROM [rdef.getTableById(tableId).getTableName()] WHERE [colName] IS NOT NULL ORDER BY 1) xx LIMIT <= [Globals.getDefaultPageSize()]
+
+test.sched.cond.popup = SELECT 1 WHERE EXISTS ([sql])
+
+download.all.email.sent = Select user_id, rep_id from CR_REPORT_EMAIL_SENT_LOG where gen_key='[pdfAttachmentKey.trim()]' and log_id =[report_email_sent_log_id.trim()] and (now() - sent_date) < '1 day' limit 1
+
+download.all.gen.key = select schedule_id from cr_report_email_sent_log u where U.GEN_KEY = '[pdfAttachmentKey]'
+
+download.all.retrieve = SELECT au.user_id FROM (SELECT rs.schedule_id, rs.rep_id FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.run_date IS NOT NULL  AND rs.schedule_id = [scheduleId]) x, cr_report r, app_user au WHERE x.rep_id = r.rep_id  AND au.user_id IN (SELECT rsu.user_id FROM cr_report_schedule_users rsu WHERE rsu.schedule_id = x.schedule_id and rsu.schedule_id = [scheduleId]  UNION SELECT ur.user_id FROM fn_user_role ur WHERE ur.role_id IN (SELECT rsu2.role_id FROM cr_report_schedule_users rsu2 WHERE rsu2.schedule_id = x.schedule_id and  rsu2.schedule_id = [scheduleId]))
+
+download.all.insert = insert into cr_report_dwnld_log (user_id,rep_id,file_name,dwnld_start_time,filter_params) values (?,?,?,?,?)
+
+#ReportWrapper.java
+
+report.wrapper.format = SELECT coalesce(cr.owner_id, cr.create_id) owner_id, cr.create_id, TO_CHAR(cr.create_date, '[Globals.getOracleTimeFormat()]') create_date, maint_id, TO_CHAR(cr.maint_date, '[Globals.getOracleTimeFormat()]') update_date, cr.menu_id, cr.menu_approved_yn FROM cr_report cr WHERE cr.rep_id= [reportID]
+
+generate.subset.sql = SELECT [colNames.toString()] FROM (SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM ([reportSQL]) AS x ) AS y 
+
+report.sql.only.first.part = SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM (SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM (
+
+report.sql.only.second.part.a = WHERE rnum <= [endRow] 
+
+report.sql.only.second.part.b =  AND rnum >= [startRow] ORDER BY rnum
+
+report.sql.only.second.part.b.noorderby =  AND rnum >= [startRow]
+
+generate.sql.visual.select = SELECT
+
+generate.sql.visual.count = COUNT(*) cnt
+
+generate.sql.visual.dual = 
+#No DUAL table in PostgreSQL so this is blank
+
+#ReportRuntime.java
+
+load.crosstab.report.data = SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM ( [reportSQL] 
+
+#RaptorRunHandler.java
+
+generate.sql.handler = SELECT row_number() OVER () AS rnum, x.* from ([sql]) AS x LIMIT 2
+
+generate.sql.select = SELECT [colNames.toString()] FROM (SELECT row_number() OVER () AS rnum, [colNames.toString()] FROM ([sql]) AS y) AS x 
+                       
+#ReportSchedule.java
+
+load.schedule.data = SELECT rs.enabled_yn, TO_CHAR(rs.start_date, 'MM/DD/YYYY') start_date, TO_CHAR(rs.end_date, 'MM/DD/YYYY') end_date, TO_CHAR(rs.run_date, 'MM/DD/YYYY') run_date, coalesce(TO_CHAR(rs.run_date, 'HH'), '12') run_hour, coalesce(TO_CHAR(rs.run_date, 'MI'), '00') run_min, coalesce(TO_CHAR(rs.run_date, 'AM'), 'AM') run_ampm, rs.recurrence, rs.conditional_yn, rs.notify_type, rs.max_row, rs.initial_formfields, rs.schedule_id, coalesce(TO_CHAR(rs.end_date, 'HH'), '11') end_hour, coalesce(TO_CHAR(rs.end_date, 'MI'), '45') end_min, coalesce(TO_CHAR(rs.end_date, 'AM'), 'PM') end_ampm, encrypt_yn, attachment_yn FROM cr_report_schedule rs WHERE rs.rep_id = [reportID]
+
+load.schedule.getid = SELECT rsu.user_id, fuser.last_name||', '||fuser.first_name, fuser.login_id FROM cr_report_schedule_users rsu, fn_user fuser WHERE rsu.rep_id = [reportID]  AND rsu.schedule_id = [getScheduleID()] and rsu.user_id IS NOT NULL and rsu.user_id = fuser.user_id
+
+load.schedule.users = SELECT rsu.role_id FROM cr_report_schedule_users rsu WHERE rsu.rep_id = [reportID] AND rsu.schedule_id = [getScheduleID()] AND rsu.role_id IS NOT NULL
+
+new.schedule.data = SELECT nextval('SEQ_CR_REPORT_SCHEDULE') AS sequence
+
+execute.update = DELETE FROM cr_report_schedule_users WHERE rep_id = [reportID] and schedule_id = [getScheduleID()]
+
+execute.update.users = INSERT INTO cr_report_schedule_users (schedule_id, rep_id, user_id, role_id, order_no) VALUES([getScheduleID()], [reportID], [emailToUsers.get(i)).getId()], NULL, [(i + 1)])
+
+execute.update.roles = INSERT INTO cr_report_schedule_users (schedule_id, rep_id, user_id, role_id, order_no) VALUES([getScheduleID()], [reportID], NULL, [emailToRoles.get(i)).getId()], [((emailToUsers.size() + i + 1)])
+
+execute.update.activity = INSERT into cr_schedule_activity_log (schedule_id, notes, run_time) values ([getScheduleID()],'Submitted:Schedule',TO_DATE('[getRunDate()] [getRunHour()]:[getRunMin()] [getRunAMPM()]', 'MM/DD/YYYY HH:MI AM'))
+delete.schedule.data = SELECT 1 FROM cr_report_schedule WHERE rep_id = [reportID] and sched_user_id = [getScheduleUserID()] and schedule_id = [getScheduleID()]
+delete.schedule.data.users = DELETE FROM cr_report_schedule_users WHERE rep_id = [reportID]  and schedule_id = [getScheduleID()]
+delete.schedule.data.id = DELETE FROM cr_report_schedule where rep_id = [reportID] and sched_user_id = [getScheduleUserID()] and schedule_id = [getScheduleID()]
+
+load.cond.sql = SELECT condition_large_sql FROM cr_report_schedule WHERE schedule_id=?::int
+
+load.cond.sql.select = SELECT condition_sql FROM cr_report_schedule WHERE schedule_id = [scheduleId]
+
+persist.cond.sql.update = update cr_report_schedule set condition_large_sql = '' where  schedule_id = [scheduleId]
+#EMPTY CLOB() changed to ''
+
+persist.cond.sql.large = SELECT condition_large_sql FROM cr_report_schedule cr WHERE schedule_id=? FOR UPDATE
+
+persist.cond.sql.set = update cr_report_schedule set condition_sql = ? where schedule_id = [scheduleId]
+
+#DataCache.java
+
+get.data.view.actions = SELECT ts.web_view_action FROM cr_table_source ts WHERE ts.web_view_action IS NOT NULL
+
+get.public.report.id.names = SELECT rep_id, title FROM cr_report WHERE public_yn = 'Y' ORDER BY title
+
+get.private.accessible.names.a = SELECT cr.rep_id, cr.title FROM cr_report cr WHERE cr.rep_id not in (select rep_id from cr_report_access cra where user_id =  '[user_id]' 
+
+get.private.accessible.names.if =  OR role_id in (
+
+get.private.accessible.names.b =  ) AND public_yn = 'N' and cr.owner_id = '[user_id]' order by 2 
+
+get.group.accessible.names.a = SELECT cr.rep_id, cr.title FROM cr_report cr  WHERE cr.rep_id  in (select rep_id from cr_report_access cra where user_id =  '[user_id]'
+
+get.group.accessible.names.b =  )  AND public_yn = 'N' order by 2 
+
+get.report.table.sources.a = SELECT table_name, display_name, pk_fields, web_view_action, large_data_source_yn, filter_sql FROM cr_table_source 
+
+get.report.table.sources.where =  where SOURCE_DB= '[dBInfo]'
+
+get.report.table.sources.if =  where SOURCE_DB is null or SOURCE_DB = '[AppConstants.DB_LOCAL]'
+
+get.report.table.sources.else =  ORDER BY table_name
+
+grab.report.table.a = SELECT ts.table_name, ts.display_name, ts.pk_fields, ts.web_view_action, ts.large_data_source_yn, ts.filter_sql FROM cr_table_source ts  WHERE 
+
+grab.report.table.if = ts.SOURCE_DB= '[dBInfo]'
+
+grab.report.table.else = (ts.SOURCE_DB is null or ts.SOURCE_DB = '[AppConstants.DB_LOCAL]')
+
+grab.report.table.b =  except SELECT ts.table_name, ts.display_name, ts.pk_fields,  ts.web_view_action,  ts.large_data_source_yn, ts.filter_sql from cr_table_source ts where table_name in (select table_name from  cr_table_role where role_id not IN [sb.toString()]) and 
+
+grab.report.table.c =  ORDER BY 1 
+
+get.report.table.crjoin = SELECT src_table_name, dest_table_name, join_expr FROM cr_table_join
+
+get.report.table.joins = SELECT tj.src_table_name, tj.dest_table_name, tj.join_expr FROM cr_table_join tj WHERE ((EXISTS (SELECT 1 FROM cr_table_role trs WHERE trs.table_name=tj.src_table_name AND trs.role_id IN [sb.toString()])) OR (NOT EXISTS (SELECT 1 FROM cr_table_role trs WHERE trs.table_name=tj.src_table_name))) AND ((EXISTS (SELECT 1 FROM cr_table_role trd WHERE trd.table_name=tj.dest_table_name AND trd.role_id IN [sb.toString()])) OR (NOT EXISTS (SELECT 1 FROM cr_table_role trd WHERE trd.table_name=tj.dest_table_name)))
+
+generate.report.table.col = SELECT a.table_name, a.column_name, a.data_type, a.label FROM user_column_def a WHERE a.table_name = '[tableName.toUpperCase()]' ORDER BY a.column_id
+
+generate.db.user.sql.a = SELECT utc.table_name, utc.column_name, utc.data_type, 
+
+generate.db.user.sql.if = utc.column_name FROM user_tab_columns utc 
+
+generate.db.user.sql.else = coalesce(x.label, utc.column_name) FROM user_tab_columns utc 
+
+generate.db.user.sql.b = WHERE utc.table_name = '[tableName.toUpperCase()]' 
+
+generate.db.user.sql.c = AND utc.table_name = x.table_name AND utc.column_name = x.column_name 
+
+generate.db.user.sql.d = ORDER BY utc.column_id 
+
+#SearchHandler.java
+
+load.report.search.result = SELECT cr.rep_id, cr.rep_id report_id, [rep_title_sql] || CASE WHEN cr.public_yn = 'Y' THEN '' ELSE '[PRIVATE_ICON]' END || cr.title ||'</a>' title, cr.descr, au.first_name||' '||au.last_name owner_name, TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'N' ELSE coalesce(ra.read_only_yn, 'Y') END read_only_yn, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'Y' ELSE 'N' END user_is_owner_yn, case when report_xml like '%<allowSchedule>N</allowSchedule>%' then 'N' when report_xml like '%<allowSchedule>Y</allowSchedule>%' or 1 = (select distinct 1 from cr_report_schedule where rep_id = cr.rep_id) then 'Y' else 'N' end FROM cr_report cr JOIN fn_user au ON coalesce (cr.owner_id, cr.create_id) = au.user_id AND TO_CHAR(cr.rep_id, 'FM99999999') like coalesce('%[fReportID]%', TO_CHAR(cr.rep_id, 'FM99999999')) AND UPPER(cr.title) LIKE UPPER('%[fReportName]%') LEFT JOIN(SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON ra.rep_id = cr.rep_id
+
+load.report.search.instr = WHERE cr.menu_id LIKE '%[menuId]%'
+
+load.report.search.result.user = WHERE coalesce(cr.owner_id, cr.create_id) = [userID]
+
+load.report.search.result.public = WHERE (coalesce(cr.owner_id, cr.create_id) = [userID] OR cr.public_yn = 'Y' OR ra.read_only_yn IS NOT NULL)
+
+load.report.search.result.fav =  WHERE cr.rep_id in (select rep_id from cr_favorite_reports where user_id = [userID]
+
+load.report.search.result.sort = ORDER BY CASE coalesce(cr.owner_id, cr.create_id) WHEN [userID] THEN ' ' WHEN 'upper(au.first_name||' '||au.last_name)' ELSE 'upper(cr.title)' END
+
+load.folder.report.result = SELECT cr.rep_id, cr.rep_id report_id, [rep_title_sql] || CASE WHEN cr.public_yn = 'Y' THEN '' ELSE '[PRIVATE_ICON]' END || cr.title || '</a>' title, cr.descr, au.first_name||' '||au.last_name owner_name, TO_CHAR(cr.create_date, 'MM/DD/YYYY') create_date, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'N' ELSE coalesce(ra.read_only_yn, 'Y') END read_only_yn, CASE WHEN coalesce(cr.owner_id, cr.create_id) = [userID] THEN 'Y' ELSE 'N' END user_is_owner_yn FROM cr_report cr JOIN fn_user au ON coalesce (cr.owner_id, cr.create_id) = au.user_id AND TO_CHAR(cr.rep_id, 'FM99999999') like coalesce('%[fReportID]%', TO_CHAR(cr.rep_id, 'FM99999999')) AND UPPER(cr.title) LIKE UPPER('%[fReportName]%') LEFT JOIN(SELECT rep_id, MIN(read_only_yn) read_only_yn FROM ((SELECT ua.rep_id, ua.read_only_yn FROM cr_report_access ua WHERE ua.user_id = [userID]) UNION ALL (SELECT ra.rep_id, ra.read_only_yn FROM cr_report_access ra WHERE ra.role_id IN ([roleList.toString()]))) report_access GROUP BY rep_id) ra ON ra.rep_id = cr.rep_id
+
+load.folder.report.result.sort =  ORDER BY CASE coalesce(cr.owner_id, cr.create_id) WHEN [userID] THEN ' ' WHEN '(au.first_name||' '||au.last_name)' ELSE 'cr.title' END
+
+#WizardProcessor.java
+
+process.filter.add.edit = '[argValue]'
+
+#ReportDefinition.java
+
+persist.report.adhoc = SELECT nextval('[Globals.getAdhocReportSequence()]') AS sequence
+
+#Globals.java
+
+initialize.roles = SELECT 1 WHERE EXISTS (SELECT 1 FROM cr_table_role)
+
+initialize.version = SELECT cr_raptor.get_version
+
+# scheduler
+
+
+scheduler.available.schedules = SELECT x.rep_id, x.schedule_id, x.conditional_yn, x.condition_large_sql, x.notify_type, x.max_row, x.initial_formfields, x.processed_formfields, r.title, x.user_id FROM ( SELECT rs.rep_id, rs.schedule_id, rs.sched_user_id user_id, rs.conditional_yn, rs.condition_large_sql, rs.notify_type, rs.max_row, rs.initial_formfields, rs.processed_formfields  FROM cr_report_schedule rs  WHERE rs.enabled_yn='Y'  AND rs.start_date <= [currentDate]  AND  (rs.end_date >= [currentDate] or rs.end_date is null )  AND rs.run_date IS NOT NULL  ) x, cr_report r  WHERE x.rep_id = r.rep_id
+
+random.string = select ( 'Z' || round(random() * 1000000000000))
+
+
+scheduler.user.emails = SELECT au.user_id FROM (SELECT rs.schedule_id, rs.rep_id FROM cr_report_schedule rs WHERE rs.enabled_yn='Y' AND rs.start_date <= now() AND rs.end_date  >= now() AND rs.run_date IS NOT NULL AND rs.schedule_id = [p_schedule_id] ) x, cr_report r, fn_user au WHERE x.rep_id = r.rep_id AND au.user_id IN (SELECT rsu.user_id FROM cr_report_schedule_users rsu WHERE rsu.schedule_id = x.schedule_id and rsu.schedule_id = [p_schedule_id] UNION SELECT ur.user_id FROM fn_user_role ur WHERE ur.role_id IN (SELECT rsu2.role_id FROM cr_report_schedule_users rsu2 WHERE rsu2.schedule_id = x.schedule_id and rsu2.schedule_id = [p_schedule_id]))  
+
+# basic sql
+
+seq.next.val = SELECT nextval('[sequenceName]') AS id
+
+current.date = now()
+
+nvl = IFNULL
diff --git a/portal-BE/src/main/resources/WEB-INF/conf/system.properties b/portal-BE/src/main/resources/WEB-INF/conf/system.properties
new file mode 100644 (file)
index 0000000..041458d
--- /dev/null
@@ -0,0 +1,157 @@
+###
+# ============LICENSE_START==========================================
+# ONAP Portal
+# ===================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the "License");
+# you may not use this software except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# ============LICENSE_END============================================
+#
+# 
+###
+
+db.driver = org.mariadb.jdbc.Driver
+#db.connectionURL = jdbc:mariadb:failover://localhost:3306/ecomp_portal
+#db.userName = XXXX
+#db.password = XXXX
+db.connectionURL = jdbc:mariadb:failover://localhost:3306/portal_2_6_os
+db.userName = root
+db.password = root
+# is the db.password property encrypted?
+db.encrypt_flag = false
+
+
+db.hib.dialect = org.hibernate.dialect.MySQLDialect
+db.min_pool_size = 5
+db.max_pool_size = 10
+hb.dialect = org.hibernate.dialect.MySQLDialect
+hb.show_sql = false
+hb.db_reconnect = true
+hb.idle_connection_test_period = 3600
+
+# Ecomp portal title
+app_display_name                                         = Portal
+files_path = /tmp
+context_root = ECOMPPORTAL
+# menu settings
+menu_query_name                      = menuData
+menu_properties_file_location        = /WEB-INF/fusion/menu/
+application_menu_set_name            = APP
+application_menu_attribute_name      = applicationMenuData
+application_menu_properties_name     = menu.properties
+business_direct_menu_set_name        = BD
+business_direct_menu_properties_name = bd.menu.properties
+business_direct_menu_attribute_name  = businessDirectMenuData
+
+application_user_id           = 30000
+post_default_role_id          = 1
+
+#Enable Fusion Mobile capabilities for the application
+mobile_enable                            = false
+
+cache_config_file_path        = /WEB-INF/conf/cache.ccf
+cache_switch                  = 1
+cache_load_on_startup         = false
+
+user_name                                        = fullName
+decryption_key                           = AGLDdG4D04BKm2IxIWEr8o==
+
+
+#Cron Schedules
+cron_site_name                = one
+log_cron                      = 0 * * * * ? *
+sessiontimeout_feed_cron         = 0 0/5 * * * ? *
+
+#Front end URL 
+frontend_url                  = http://localhost:9000/ecompportal/applicationsHome
+
+#cookie domain          PLEASE DO NOT REMOVE THIS VALUE FOR OPEN SOUCE REFACTOR
+cookie_domain = openecomp.org
+
+# An Unique 128-bit value defined to identify a specific version of
+# ECOMP Portal deployed on a specific virtual machine.
+# This value must be generated and updated at the time of 
+# the deployment.
+# Online Unique UUID generator - https://www.uuidgenerator.net/
+instance_uuid                          = 90bc9497-10e6-49fe-916b-dcdfaa972383
+
+ecomp_shared_context_rest_url= http://todo_enter_be_hostname:9000/ecompportal/context
+
+ecomp_shared_context_rest_url= http://todo_enter_share_context_rest_hostname:9000/ecompportal/context
+elastic_search_url                     = http://todo_enter_elastic_search_hostname:9200
+contact_us_link                                = http://todo_enter_contact_us_hostname 
+user_guide_link             = http://todo_enter_user_guide_link
+
+# Contact Us page properties
+ush_ticket_url                         = http://todo_enter_ush_ticket_url
+feedback_email_address         = portal@lists.openecomp.org
+portal_info_url                                = https://todo_enter_portal_info_url    
+
+#Online user bar refresh interval, in seconds
+online_user_update_rate                  = 5
+
+#Online user bar refresh total duration, in seconds
+online_user_update_duration                    = 900
+
+# User notification refresh interval and duration, in seconds
+notification_update_rate                       = 90
+notification_update_duration           = 900
+#Widgets upload flag
+microservices.widget.upload.flag=true
+
+#Microservices Related Properties for Portal
+microservices.widget.username = widget_user
+microservices.widget.password = KpuqIB08YHg+btG+pjX+sA==
+#This property won't be needed after consul is functional on VMs -
+microservices.widget.local.port = 8082
+
+#delete auditlog from number of days ago
+auditlog_del_day_from = 365
+
+#authenticate user server
+authenticate_user_server=http://todo_enter_auth_server_hostname:8383/openid-connect-server-webapp/allUsers
+
+#window width threshold to collapse left/right menu when page onload
+window_width_threshold_left_menu = 1400
+window_width_threshold_right_menu = 1350
+
+#External system notification URL
+external_system_notification_url= https://jira.onap.org/browse/
+
+# External Access System Basic Auth Credentials & Rest endpoint(These credentials doesn't work as these are place holders for now)
+ext_central_access_user_name = m00468@portal.onap.org
+ext_central_access_password = dR2NABMkxPaFbIbym87ZwQ==
+ext_central_access_url = https://aaftest.test.onap.org:8095/proxy/authz/
+ext_central_access_user_domain = @csp.onap.org
+
+# External Central Auth system access
+remote_centralized_system_access = false
+
+#left menu with root value or non-root
+portal_left_menu = non-root
\ No newline at end of file
diff --git a/portal-BE/src/main/resources/WEB-INF/fusion/conf/fusion.properties b/portal-BE/src/main/resources/WEB-INF/fusion/conf/fusion.properties
new file mode 100644 (file)
index 0000000..3d90d62
--- /dev/null
@@ -0,0 +1,101 @@
+#os
+###
+# ============LICENSE_START==========================================
+# ONAP Portal
+# ===================================================================
+# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
+# ===================================================================
+#
+# Unless otherwise specified, all software contained herein is licensed
+# under the Apache License, Version 2.0 (the "License");
+# you may not use this software except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# Unless otherwise specified, all documentation contained herein is licensed
+# under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+# you may not use this documentation except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#             https://creativecommons.org/licenses/by/4.0/
+#
+# Unless required by applicable law or agreed to in writing, documentation
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# ============LICENSE_END============================================
+#
+# 
+###
+# domain settings
+#domain_class_location = 
+
+# validator settings
+#default_error_message = Default error message
+
+login_url_no_ret_val = http://localhost:9000/ecompportal/login.htm
+
+user_attribute_name      = user
+
+# User Session settings
+#user_attribute_name           = user
+roles_attribute_name          = roles
+role_functions_attribute_name = role_functions
+#client_device_attribute_name  = client_device
+#client_device_emulation       = false
+#client_device_type_to_emulate = 
+
+# menu settings
+menu_query_name                      = menuData
+#menu_properties_file_location        = /WEB-INF/fusion/menu/
+application_menu_set_name            = APP
+application_menu_attribute_name      = applicationMenuData
+#application_menu_properties_name     = menu.properties
+business_direct_menu_set_name        = BD
+#business_direct_menu_properties_name = bd.menu.properties
+business_direct_menu_attribute_name  = businessDirectMenuData
+
+# RAPTOR config settings
+#raptor_config_file_path = /WEB-INF/conf/
+
+# ECOMP settings
+ecomp_app_id = 1
+# Role settings
+sys_admin_role_id = 1
+account_admin_role_id = 999
+restricted_app_role_id = 900
+#sys_admin_role_function_delete_from_ui = true
+
+# Profile Search settings
+#profile_search_report_id=181
+#callable_profile_search_report_id=386
+
+
+# Home Page index html
+
+home_page                                              = /index.html
+
+authentication_mechanism = DBAUTH
+
+login.error.hrid.empty = Login failed, please contact system administrator. 
+login.error.hrid.not-found = User not found, please contact system administrator.
+login.error.user.inactive = Account is disabled, please contact system administrator.
+
+#
+# Number of seconds to poll health (database operational, etc.)
+#
+health_poll_interval_seconds = 5
+#
+# If a component is down a log entry will be written that triggers an alert.  This parameter specifies how often this alert should be triggered  
+# if the component remains down.   For example a value of 30, would translate to 30 * 60 seconds = 1800 seconds, or every 30 minutes
+#
+health_fail_alert_every_x_intervals =  30
index eff7141..b99840d 100644 (file)
@@ -1,7 +1,7 @@
 server.port=8080
 
 spring.datasource.url=jdbc:mysql://portal-db:3306/testdb?createDatabaseIfNotExist=true&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
-+spring.datasource.driverClassName=org.mariadb.jdbc.Driver
+spring.datasource.driverClassName=org.mariadb.jdbc.Driver
 spring.datasource.initialization-mode=always
 spring.session.jdbc.initialize-schema=always
 spring.datasource.continueOnError=true
@@ -32,4 +32,6 @@ log4j.logger.org.hibernate.SQL=debug
 log4j.logger.org.hibernate.type.descriptor.sql=trace
 
 #PROPERTIES
-external_access_enable = false
\ No newline at end of file
+external_access_enable = false
+
+container.classpath = classpath:
index 64639b4..6f45b22 100644 (file)
@@ -1,7 +1,6 @@
 server.port=8080
 
 spring.jpa.database=mysql
-spring.jpa.show-sql=true
 spring.jpa.hibernate.ddl-auto=update
 spring.h2.console.enabled=true
 spring.datasource.url=jdbc:h2:mem:testdb
@@ -12,4 +11,4 @@ spring.datasource.initialization-mode=always
 spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
 
 #PROPERTIES
-external_access_enable = false
\ No newline at end of file
+external_access_enable = false
index 7c654ad..8e5b1aa 100644 (file)
@@ -67,7 +67,7 @@ class UserControllerTest {
        private final UserController userController;
 
        @Autowired
-       UserControllerTest(final FnUserService userService, final UserController userController) {
+       UserControllerTest(FnUserService userService, UserController userController) {
               this.userService = userService;
               this.userController = userController;
        }
@@ -140,4 +140,4 @@ class UserControllerTest {
               assertEquals(expected, actual);
               assertNotEquals(oldPassword, newPassword);
        }
-}
\ No newline at end of file
+}
index 9a1a96a..5a30ac0 100644 (file)
 
 package org.onap.portal.controller;
 
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.Assert.assertEquals;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.junit.jupiter.api.Test;
 import org.junit.runner.RunWith;
-import org.onap.portal.domain.dto.ecomp.PortalRestResponse;
-import org.onap.portal.domain.dto.ecomp.PortalRestStatusEnum;
+import org.onap.portal.domain.dto.PortalRestResponse;
+import org.onap.portal.domain.dto.PortalRestStatusEnum;
 import org.onap.portal.framework.MockitoTestSuite;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.boot.test.context.SpringBootTest;
@@ -70,12 +70,12 @@ class WidgetMSControllerTest {
        @Test
        void getServiceLocation() {
               PortalRestResponse<String> expected = new PortalRestResponse<>();
-              expected.setMessage("Error!");
-              expected.setResponse("Couldn't get the service location");
-              expected.setStatus(PortalRestStatusEnum.ERROR);
+              expected.setMessage("Success!");
+              expected.setResponse("localhost:null");
+              expected.setStatus(PortalRestStatusEnum.OK);
               PortalRestResponse<String> actual = widgetMSController.getServiceLocation(request, response, "portal");
               assertEquals(expected.getMessage(), actual.getMessage());
               assertEquals(expected.getResponse(), actual.getResponse());
               assertEquals(expected.getStatus(), actual.getStatus());
        }
-}
\ No newline at end of file
+}
index 65525db..3c13737 100644 (file)
@@ -254,7 +254,7 @@ public class WidgetsCatalogControllerTest {
 
        @Test
        public void getUploadFlag() {
-              String expected = "";
+              String expected = "true";
               String actual = widgetsCatalogController.getUploadFlag();
 
               assertEquals(expected, actual);
@@ -271,4 +271,4 @@ public class WidgetsCatalogControllerTest {
                       .guest(false)
                       .build();
        }
-}
\ No newline at end of file
+}
index ef0a3e0..a40d194 100644 (file)
@@ -139,7 +139,7 @@ class FnUserServiceTest {
               assertEquals(expected.getAlertMethodCd(), actual.getAlertMethodCd());
               assertEquals(expected.getHrid(), actual.getHrid());
               assertEquals(expected.getOrgUserId(), actual.getOrgUserId());
-              assertEquals(expected.getOrg_code(), actual.getOrg_code());
+              assertEquals(expected.getOrgCode(), actual.getOrgCode());
               assertEquals(expected.getLoginId(), actual.getLoginId());
               //   assertEquals(expected.getLoginPwd(), actual.getLoginPwd());
               assertEquals(expected.getActiveYn(), actual.getActiveYn());
@@ -157,7 +157,7 @@ class FnUserServiceTest {
               assertEquals(expected.getJobTitle(), actual.getJobTitle());
               assertEquals(expected.getDepartment(), actual.getDepartment());
               assertEquals(expected.getBusinessUnit(), actual.getBusinessUnit());
-              assertEquals(expected.getCost_center(), actual.getCost_center());
+              assertEquals(expected.getCostCenter(), actual.getCostCenter());
               assertEquals(expected.getFinLocCode(), actual.getFinLocCode());
               assertEquals(expected.getSiloStatus(), actual.getSiloStatus());
        }