diff options
Diffstat (limited to 'ecomp-portal-BE-common/src')
71 files changed, 8822 insertions, 627 deletions
diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/SecurityInitializer.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/SecurityInitializer.java new file mode 100644 index 00000000..2a0a4b15 --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/config/SecurityInitializer.java @@ -0,0 +1,44 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.config; + +import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; + +public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardController.java index d8e8aeb0..4b364995 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/DashboardController.java @@ -171,8 +171,7 @@ public class DashboardController extends EPRestrictedBaseController { * @return Rest response wrapped around a String; e.g., "success" or "ERROR" */ @RequestMapping(value = "/widgetData", method = RequestMethod.POST, produces = "application/json") - public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget, HttpServletRequest request, - HttpServletResponse response) { + public PortalRestResponse<String> saveWidgetData(@RequestBody CommonWidget commonWidget, HttpServletRequest request, HttpServletResponse response) { logger.debug(EELFLoggerDelegate.debugLogger, "saveWidgetData: argument is {}", commonWidget); EPUser user = EPUserUtils.getUserSession(request); if (adminRolesService.isSuperAdmin(user)) { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java index 0be015ee..1e955c8b 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/ExternalAccessRolesController.java @@ -39,6 +39,7 @@ package org.onap.portalapp.portal.controller; import java.io.IOException; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -69,10 +70,15 @@ import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalsdk.core.domain.AuditLog; import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.domain.RoleFunction; +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.UserService; +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; @@ -87,6 +93,7 @@ import org.springframework.web.client.RestTemplate; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.TypeFactory; import io.swagger.annotations.ApiOperation; @@ -117,6 +124,9 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @Autowired private ExternalAccessRolesService externalAccessRolesService; + @Autowired + private UserService userservice = new UserServiceCentalizedImpl(); + @ApiOperation(value = "Gets user role for an application.", response = CentralUser.class, responseContainer="List") @RequestMapping(value = { "/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json") @@ -136,7 +146,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @ApiOperation(value = "Gets user roles for an application which is upgraded to newer version.", response = String.class, responseContainer="List") @RequestMapping(value = { - "/v2/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json") + "/v1/user/{loginId}" }, method = RequestMethod.GET, produces = "application/json") public String getV2UserList(HttpServletRequest request, HttpServletResponse response, @PathVariable("loginId") String loginId) throws Exception { String answer = null; @@ -176,7 +186,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @ApiOperation(value = "Gets roles for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer="Json") @RequestMapping(value = { - "/v2/roles" }, method = RequestMethod.GET, produces = "application/json") + "/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; @@ -223,7 +233,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @ApiOperation(value = "Gets all role functions for an application which is upgraded to newer version.", response = CentralV2RoleFunction.class, responseContainer="Json") @RequestMapping(value = { - "/v2/functions" }, method = RequestMethod.GET, produces = "application/json") + "/v1/functions" }, method = RequestMethod.GET, produces = "application/json") public List<CentralV2RoleFunction> getV2RoleFunctionsList(HttpServletRequest request, HttpServletResponse response) throws Exception { List<CentralV2RoleFunction> cenRoleFuncList = null; @@ -266,7 +276,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl @ApiOperation(value = "Gets v2 role information for an application which is upgraded to newer version.", response = CentralV2Role.class, responseContainer="Json") @RequestMapping(value = { - "/v2/role/{role_id}" }, method = RequestMethod.GET, produces = "application/json") + "/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; @@ -302,7 +312,7 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl } @ApiOperation(value = "Gets role information for an application provided by function code.", response = CentralV2RoleFunction.class, responseContainer = "Json") - @RequestMapping(value = { "/v2/function/{code}" }, method = RequestMethod.GET, produces = "application/json") + @RequestMapping(value = { "/v1/function/{code}" }, method = RequestMethod.GET, produces = "application/json") public CentralV2RoleFunction getV2RoleFunction(HttpServletRequest request, HttpServletResponse response, @PathVariable("code") String code) throws Exception { CentralV2RoleFunction centralV2RoleFunction = null; @@ -331,10 +341,20 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl EPApp requestedApp = applicationList.get(0); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class); - CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(availableRoleFunction.getCode(), - requestedApp.getUebKey()); + CentralV2RoleFunction domainRoleFunction = null; + if(availableRoleFunction.getType()!=null && availableRoleFunction.getAction()!= null) { + String code = availableRoleFunction.getType()+"|"+availableRoleFunction.getCode()+"|"+availableRoleFunction.getAction(); + domainRoleFunction = externalAccessRolesService.getRoleFunction(code, + requestedApp.getUebKey()); + } else { + domainRoleFunction = externalAccessRolesService.getRoleFunction(availableRoleFunction.getCode(), + requestedApp.getUebKey()); + } + boolean saveOrUpdateResponse = false; - if (domainRoleFunction != null) { + if (domainRoleFunction != null && domainRoleFunction.getCode().equals(availableRoleFunction.getCode()) + && domainRoleFunction.getType().equals(availableRoleFunction.getType()) + && domainRoleFunction.getAction().equals(availableRoleFunction.getAction())) { domainRoleFunction.setName(availableRoleFunction.getName()); saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction, requestedApp); @@ -750,11 +770,11 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl 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) { - response.setStatus(HttpServletResponse.SC_BAD_REQUEST); + sendErrorResponse(response, e); logger.error(EELFLoggerDelegate.errorLogger, "getUsersOfApplication failed", e); - throw new Exception(e.getMessage()); } return users; } @@ -804,4 +824,61 @@ public class ExternalAccessRolesController implements BasicAuthenticationControl response.setStatus(HttpServletResponse.SC_BAD_REQUEST); } } + + @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 { + EcompUser user = null; + ObjectMapper mapper = new ObjectMapper(); + CentralUser answer = null; + try { + fieldsValidation(request); + answer = externalAccessRolesService.getUserRoles(loginId, request.getHeader(UEBKEY)); + if (answer != null) { + String res = mapper.writeValueAsString(answer); + User ecompUser = userservice.userMapper(res); + user = UserUtils.convertToEcompUser(ecompUser); + } + } catch (Exception e) { + sendErrorResponse(response, e); + logger.error(EELFLoggerDelegate.errorLogger, "getEcompUser failed", e); + } + if (user != null) { + return mapper.writeValueAsString(user); + } + return null; + } + + @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); + EPApp app = externalAccessRolesService.getApp(request.getHeader(UEBKEY)).get(0); + // Sync all roles from external system into Ecomp 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; + } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java index 1433fb21..8f0558aa 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/RoleManageController.java @@ -108,6 +108,8 @@ import com.fasterxml.jackson.databind.type.TypeFactory; @EnableAspectJAutoProxy @EPAuditLog public class RoleManageController extends EPRestrictedBaseController { + private static final String PIPE = "|"; + private static final String ROLE_INVALID_CHARS = "%=():,\"\""; private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RoleManageController.class); @@ -321,7 +323,7 @@ public class RoleManageController extends EPRestrictedBaseController { 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()); + throw new DuplicateRecordException("Role already exists: " + existRole.getName()); domainRole = new CentralV2Role(); domainRole.setName(role.getName()); @@ -340,7 +342,7 @@ public class RoleManageController extends EPRestrictedBaseController { + " and action: " + roleFunction.getAction() + " found while saving!"); } roleFunction.setCode(externalAccessRolesService.encodeFunctionCode(roleFunction.getCode())); - roleFunction.setCode(roleFunction.getType() + "|" + roleFunction.getCode() + "|" + roleFunction.setCode(roleFunction.getType() + PIPE + roleFunction.getCode() + PIPE + roleFunction.getAction()); domainRole.addRoleFunction((CentralV2RoleFunction) roleFunction); } @@ -500,20 +502,36 @@ public class RoleManageController extends EPRestrictedBaseController { if (isAuthorizedUser(user, requestedApp)) { fieldsValidation(requestedApp); if (requestedApp.getCentralAuth()) { - saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc, requestedApp); + String code = roleFunc.getType()+PIPE+roleFunc.getCode()+PIPE+roleFunc.getAction(); + CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code, + requestedApp.getUebKey()); + if(domainRoleFunction != null && (domainRoleFunction.getType() == null || domainRoleFunction.getAction() == null)) { + addIfTypeActionDoesNotExits(domainRoleFunction); + } + boolean isSave = true; + if (domainRoleFunction != null && domainRoleFunction.getCode().equals(roleFunc.getCode()) + && domainRoleFunction.getType().equals(roleFunc.getType()) + && domainRoleFunction.getAction().equals(roleFunc.getAction())) { + domainRoleFunction.setName(roleFunc.getName()); + saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(domainRoleFunction, + requestedApp); + isSave = false; + } else { + roleFunc.setAppId(requestedApp.getId()); + saveOrUpdateResponse = externalAccessRolesService.saveCentralRoleFunction(roleFunc, + requestedApp); + } if (saveOrUpdateResponse) { EPUser requestedUser = externalAccessRolesService.getUser(user.getOrgUserId()).get(0); EPApp app = externalAccessRolesService.getApp(requestedApp.getUebKey()).get(0); - CentralV2RoleFunction function = externalAccessRolesService.getRoleFunction(roleFunc.getCode(), - requestedApp.getUebKey()); - String activityCode = (function.getCode() == null) + String activityCode = (isSave) ? 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(), roleFunc.getCode()); + "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:'" + roleFunc.getCode() + "'", + + app.getId() + " and function:'" + code + "'", PortalConstants.AUDIT_LOG_COMMENT_SIZE)); auditService.logActivity(auditLog, null); MDC.put(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP, @@ -526,7 +544,7 @@ public class RoleManageController extends EPRestrictedBaseController { logger.info(EELFLoggerDelegate.auditLogger, EPLogUtil.formatAuditLogMessage("RoleManageController.saveRoleFunction", activityCode, String.valueOf(requestedUser.getId()), requestedUser.getOrgUserId(), - roleFunc.getCode())); + code)); MDC.remove(EPCommonSystemProperties.AUDITLOG_BEGIN_TIMESTAMP); MDC.remove(EPCommonSystemProperties.AUDITLOG_END_TIMESTAMP); MDC.remove(SystemProperties.MDC_TIMER); @@ -546,6 +564,24 @@ public class RoleManageController extends EPRestrictedBaseController { return new PortalRestResponse<>(PortalRestStatusEnum.OK, "Saved Successfully!", "Success"); } + + + private void addIfTypeActionDoesNotExits(CentralV2RoleFunction domainRoleFunction) { + if(domainRoleFunction.getCode().contains(PIPE)) { + String newfunctionCodeFormat = EcompPortalUtils.getFunctionCode(domainRoleFunction.getCode()); + String newfunctionTypeFormat = EcompPortalUtils.getFunctionType(domainRoleFunction.getCode()); + String newfunctionActionFormat = EcompPortalUtils.getFunctionAction(domainRoleFunction.getCode()); + domainRoleFunction.setType(newfunctionTypeFormat); + domainRoleFunction.setAction(newfunctionActionFormat); + domainRoleFunction.setCode(newfunctionCodeFormat); + } else { + String type = externalAccessRolesService.getFunctionCodeType(domainRoleFunction.getCode()); + String action = externalAccessRolesService.getFunctionCodeAction(domainRoleFunction.getCode()); + domainRoleFunction.setType(type); + domainRoleFunction.setAction(action); + } + } + @RequestMapping(value = { "/portalApi/role_function_list/removeRoleFunction/{appId}" }, method = RequestMethod.POST) public PortalRestResponse<String> removeRoleFunction(HttpServletRequest request, HttpServletResponse response, @RequestBody String roleFunc, @PathVariable("appId") Long appId) throws Exception { @@ -557,10 +593,13 @@ public class RoleManageController extends EPRestrictedBaseController { if (requestedApp.getCentralAuth()) { ObjectMapper mapper = new ObjectMapper(); String data = roleFunc; + boolean getDelFuncResponse = false; CentralV2RoleFunction availableRoleFunction = mapper.readValue(data, CentralV2RoleFunction.class); - CentralV2RoleFunction domainRoleFunction = externalAccessRolesService - .getRoleFunction(availableRoleFunction.getCode(), requestedApp.getUebKey()); - boolean getDelFuncResponse = externalAccessRolesService + String code = availableRoleFunction.getType() + PIPE + availableRoleFunction.getCode() + PIPE + + availableRoleFunction.getAction(); + CentralV2RoleFunction domainRoleFunction = externalAccessRolesService.getRoleFunction(code, + requestedApp.getUebKey()); + getDelFuncResponse = externalAccessRolesService .deleteCentralRoleFunction(domainRoleFunction.getCode(), requestedApp); if (getDelFuncResponse) { logger.info(EELFLoggerDelegate.applicationLogger, diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerAuxController.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerAuxController.java index c676fa98..fce1f387 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerAuxController.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/controller/SchedulerAuxController.java @@ -58,11 +58,6 @@ import org.onap.portalapp.portal.utils.PortalConstants; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; -/*import org.openecomp.vid.policy.PolicyProperties; -import org.openecomp.vid.policy.PolicyResponseWrapper; -import org.openecomp.vid.policy.PolicyRestInterfaceFactory; -import org.openecomp.vid.policy.PolicyRestInterfaceIfc; -import org.openecomp.vid.policy.PolicyUtil;*/ import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreference.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreference.java index 4d943f62..b597b9d2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreference.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreference.java @@ -42,14 +42,14 @@ import org.onap.portalsdk.core.domain.support.DomainVo; public class EPUserAppsManualSortPreference extends DomainVo { private static final long serialVersionUID = -6270136291139278216L; - private int userId; + private Long userId; private Long appId; private int appManualSortOrder; - public int getUserId() { + public Long getUserId() { return userId; } - public void setUserId(int userId) { + public void setUserId(Long userId) { this.userId = userId; } public Long getAppId() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreference.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreference.java index 552e2e0f..9c324047 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreference.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreference.java @@ -42,17 +42,17 @@ import org.onap.portalsdk.core.domain.support.DomainVo; public class EPWidgetsManualSortPreference extends DomainVo{ private static final long serialVersionUID = 4607102334801223570L; - private int userId; + private Long userId; private Long widgetId; private int widgetRow; private int widgetCol; private int widgetWidth; private int widgetHeight; - public int getUserId() { + public Long getUserId() { return userId; } - public void setUserId(int userId) { + public void setUserId(Long userId) { this.userId = userId; } public Long getWidgetId() { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/ExternalSystemAccess.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/ExternalSystemAccess.java index 29b4fe35..c7d5d207 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/ExternalSystemAccess.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/ExternalSystemAccess.java @@ -61,6 +61,37 @@ public class ExternalSystemAccess { public void setAccessValue(Boolean accessValue) { this.accessValue = accessValue; } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((accessValue == null) ? 0 : accessValue.hashCode()); + result = prime * result + ((key == null) ? 0 : key.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ExternalSystemAccess other = (ExternalSystemAccess) obj; + if (accessValue == null) { + if (other.accessValue != null) + return false; + } else if (!accessValue.equals(other.accessValue)) + return false; + if (key == null) { + if (other.key != null) + return false; + } else if (!key.equals(other.key)) + return false; + return true; + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/FunctionalMenuItemWithAppID.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/FunctionalMenuItemWithAppID.java index a9455d61..ecb17875 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/FunctionalMenuItemWithAppID.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/domain/FunctionalMenuItemWithAppID.java @@ -47,7 +47,7 @@ import javax.persistence.Id; import javax.persistence.Transient; /*** * - * This class is almost identical to org.openecomp.portalapp.portal.transport.FunctionalMenuItem + * This class is almost identical to org.onap.portalapp.portal.transport.FunctionalMenuItem * The only difference is the appId field. In FunctionMenuItem, we used @Transient as an attribute, and we are using @Column in this class. * In some sql queries, we need to have appId, but it's not a field in fn_menu_functional table. * diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/SyncUserRolesException.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/SyncUserRolesException.java new file mode 100644 index 00000000..f7f19a5f --- /dev/null +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/exceptions/SyncUserRolesException.java @@ -0,0 +1,48 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ + +package org.onap.portalapp.portal.exceptions; + +@SuppressWarnings("serial") +public class SyncUserRolesException extends Exception{ + + public SyncUserRolesException(String msg) { + super(msg); + } + +} diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java index 5d2f399b..8cf20ba8 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/interceptor/PortalResourceInterceptor.java @@ -245,7 +245,7 @@ public class PortalResourceInterceptor extends ResourceInterceptor { BasicAuthCredentials creds; try { creds = basicAuthService.getBasicAuthCredentialByUsernameAndPassword(accountNamePassword[0], - encrypted(accountNamePassword[1])); + accountNamePassword[1]); } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "checkBasicAuth failed to get credentials", e); final String msg = "Failed while getting basic authentication credential: "; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java index 11fb2fb5..c1127758 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdvice.java @@ -112,7 +112,7 @@ public class EPEELFLoggerAdvice { MDC.put(className + methodName + EPCommonSystemProperties.METRICSLOG_BEGIN_TIMESTAMP, getCurrentDateTimeUTC()); MDC.put(EPCommonSystemProperties.TARGET_ENTITY, EPCommonSystemProperties.ECOMP_PORTAL_BE); MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, methodName); - if (MDC.get(Configuration.MDC_KEY_REQUEST_ID) == null){ + if (MDC.get(Configuration.MDC_KEY_REQUEST_ID) == null || MDC.get(Configuration.MDC_KEY_REQUEST_ID).isEmpty()){ String requestId = UUID.randomUUID().toString(); MDC.put(Configuration.MDC_KEY_REQUEST_ID, requestId); } @@ -173,7 +173,7 @@ public class EPEELFLoggerAdvice { if (securityEventType != null && args.length > 0 && args[0] != null && args[0] instanceof HttpServletRequest && securityEventType == SecurityEventTypeEnum.INCOMING_REST_MESSAGE && (MDC.get(EPCommonSystemProperties.FULL_URL) == null - || MDC.get(EPCommonSystemProperties.FULL_URL) == "")) { + || MDC.get(EPCommonSystemProperties.FULL_URL).isEmpty())) { HttpServletRequest req = (HttpServletRequest) args[0]; this.setHttpRequestBasedDefaultsIntoGlobalLoggingContext(req, securityEventType, methodName); } @@ -313,7 +313,8 @@ public class EPEELFLoggerAdvice { if (accessingClient != null && accessingClient.trim().length()==0 && (accessingClient.contains("Mozilla") || accessingClient.contains("Chrome") || accessingClient.contains("Safari"))) { accessingClient = EPCommonSystemProperties.ECOMP_PORTAL_FE; - } + }else if(accessingClient==null || accessingClient.isEmpty()) + accessingClient = "Unknown"; MDC.put(EPCommonSystemProperties.PARTNER_NAME, accessingClient); // Load loginId into MDC context. @@ -340,9 +341,9 @@ public class EPEELFLoggerAdvice { } // Rest Path - MDC.put(Configuration.MDC_SERVICE_NAME, restMethod); + MDC.put(Configuration.MDC_SERVICE_NAME, (restMethod==null || restMethod.isEmpty()) ? "Unknown" : restMethod); String restPath = req.getServletPath(); - if (restPath != null && restPath != "") { + if (restPath != null && !restPath.isEmpty()) { MDC.put(Configuration.MDC_SERVICE_NAME, restPath); } @@ -359,7 +360,7 @@ public class EPEELFLoggerAdvice { MDC.put(EPCommonSystemProperties.TARGET_SERVICE_NAME, "search"); } } else { - MDC.put(Configuration.MDC_SERVICE_NAME, restMethod); + MDC.put(Configuration.MDC_SERVICE_NAME, (restMethod==null || restMethod.isEmpty()) ? "Unknown" : restMethod); MDC.put(EPCommonSystemProperties.PARTNER_NAME, EPCommonSystemProperties.ECOMP_PORTAL_FE); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPAppMessagesEnum.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPAppMessagesEnum.java index d7536bf7..a93be650 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPAppMessagesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPAppMessagesEnum.java @@ -224,7 +224,7 @@ public enum EPAppMessagesEnum { "ERR540E", "Unexpected Scheduler error", "Details: {0}.", "Please check logs for more information."), SchedulerInvalidAttributeError(EPErrorCodesEnum.SCHEDULER_INVALID_ATTRIBUTEERROR, ErrorTypeEnum.SYSTEM_ERROR, AlarmSeverityEnum.MAJOR, ErrorSeverityEnum.ERROR, - "ERR505E", "Unable to create Scheduler", "Details: {0}.", "Please check logs for more information."), + "ERR515E", "Unable to create Scheduler", "Details: {0}.", "Please check logs for more information."), ; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPErrorCodesEnum.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPErrorCodesEnum.java index e4cd38e7..b505eedd 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPErrorCodesEnum.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/logging/format/EPErrorCodesEnum.java @@ -116,6 +116,6 @@ public enum EPErrorCodesEnum implements EELFResolvableErrorEnum { * Here this application loads messages from three bundles */ static { - EELFResourceManager.loadMessageBundle("org/openecomp/portalapp/portal/logging/format/ApplicationCodes"); + EELFResourceManager.loadMessageBundle("org/onap/portalapp/portal/logging/format/ApplicationCodes"); } } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java index 53848e02..3caede7e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduler/client/HttpsBasicClient.java @@ -80,7 +80,7 @@ public class HttpsBasicClient{ String methodName = "getClient"; ClientConfig config = new ClientConfig(); //config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE); - //config.getClasses().add(org.openecomp.aai.util.CustomJacksonJaxBJsonProvider.class); + //config.getClasses().add(org.onap.aai.util.CustomJacksonJaxBJsonProvider.class); SSLContext ctx = null; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java index 678073c8..0a935ae4 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/scheduleraux/SchedulerAuxUtil.java @@ -43,9 +43,6 @@ import java.util.Date; import org.glassfish.jersey.client.ClientResponse; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; -/*import org.openecomp.vid.policy.PolicyResponseWrapper; -import org.openecomp.vid.policy.PolicyUtil; -import org.openecomp.vid.policy.RestObject;*/ import com.fasterxml.jackson.databind.ObjectMapper; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java index 653e974b..e0ce086e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AdminRolesServiceImpl.java @@ -251,6 +251,7 @@ public class AdminRolesServiceImpl implements AdminRolesService { if (EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { // Add user admin role for list of centralized applications in external system addAdminRoleInExternalSystem(user, localSession, newAppsWhereUserIsAdmin); + result = true; } } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); @@ -409,7 +410,7 @@ public class AdminRolesServiceImpl implements AdminRolesService { @SuppressWarnings("unchecked") @Override public boolean isSuperAdmin(EPUser user) { - if ((user != null) /* && (user.getId() == null) */ && (user.getOrgUserId() != null)) { + if ((user != null) && (user.getOrgUserId() != null)) { String sql = "SELECT user.USER_ID, user.org_user_id, userrole.ROLE_ID, userrole.APP_ID FROM fn_user_role userrole " + "INNER JOIN fn_user user ON user.USER_ID = userrole.USER_ID " + "WHERE user.org_user_id = '" + user.getOrgUserId() + "' " + "AND userrole.ROLE_ID = '" + SYS_ADMIN_ROLE_ID + "' " @@ -425,21 +426,6 @@ public class AdminRolesServiceImpl implements AdminRolesService { "Exception occurred while executing isSuperAdmin operation", e); } } - // else - // { - // User currentUser = user != null ? (User) - // dataAccessService.getDomainObject(User.class, user.getId(), null) : - // null; - // if (currentUser != null && currentUser.getId() != null) { - // for (UserApp userApp : currentUser.getUserApps()) { - // if (userApp.getApp().getId().equals(ECOMP_APP_ID) && - // userApp.getRole().getId().equals(SYS_ADMIN_ROLE_ID)) { - // // Super Administrator role is global, no need to keep iterating - // return true; - // } - // } - // } - // } return false; } @@ -450,9 +436,7 @@ public class AdminRolesServiceImpl implements AdminRolesService { : null; if (currentUser != null && currentUser.getId() != null) { for (EPUserApp userApp : currentUser.getEPUserApps()) { - if (// !userApp.getApp().getId().equals(ECOMP_APP_ID) - // && - userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) { + if (userApp.getRole().getId().equals(ACCOUNT_ADMIN_ROLE_ID)) { // Account Administrator sees only the applications // he/she is Administrator return true; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AppContactUsServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AppContactUsServiceImpl.java index edffafc3..67e2ae32 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AppContactUsServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/AppContactUsServiceImpl.java @@ -74,7 +74,7 @@ public class AppContactUsServiceImpl implements AppContactUsService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.AppContactUsService# + * @see org.onap.portalapp.portal.service.AppContactUsService# * getAppContactUs() */ @SuppressWarnings("unchecked") @@ -89,7 +89,7 @@ public class AppContactUsServiceImpl implements AppContactUsService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.AppContactUsService# + * @see org.onap.portalapp.portal.service.AppContactUsService# * getAllAppsAndContacts() */ @SuppressWarnings("unchecked") diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java index 18717204..1460a61c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ApplicationsRestClientServiceImpl.java @@ -53,7 +53,6 @@ import javax.ws.rs.core.Response; import org.apache.commons.lang.StringUtils; import org.apache.cxf.jaxrs.client.WebClient; import org.apache.cxf.transport.http.HTTPException; -import org.onap.portalapp.portal.service.AppsCacheService; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.logging.aop.EPAuditLog; import org.onap.portalapp.portal.logging.aop.EPMetricsLog; @@ -252,7 +251,7 @@ public class ApplicationsRestClientServiceImpl implements ApplicationsRestClient * (non-Javadoc) * * @see - * org.openecomp.portalapp.portal.service.ApplicationsRestClientService#get( + * org.onap.portalapp.portal.service.ApplicationsRestClientService#get( * java.lang.Class, long, java.lang.String, boolean) */ @Override @@ -354,13 +353,15 @@ public class ApplicationsRestClientServiceImpl implements ApplicationsRestClient WebClient client = null; Response response = null; T t = null; - + logger.debug(EELFLoggerDelegate.debugLogger, "Entering to createClientForApp method for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId); client = createClientForApp(appId, restPath); EcompPortalUtils.logAndSerializeObject(logger, restPath, "POST request =", payload); - + logger.debug(EELFLoggerDelegate.debugLogger, "Finished createClientForApp method for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId); try { if (client != null) { + logger.debug(EELFLoggerDelegate.debugLogger, "Entering to POST for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId); response = client.post(payload); + logger.debug(EELFLoggerDelegate.debugLogger, "Finished to POST for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId); } else { logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); @@ -396,12 +397,21 @@ public class ApplicationsRestClientServiceImpl implements ApplicationsRestClient Response response = null; T t = null; + logger.debug(EELFLoggerDelegate.debugLogger, "Entering to createClientForApp method for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId); + client = createClientForApp(appId, restPath); EcompPortalUtils.logAndSerializeObject(logger, restPath, "PUT request =", payload); + + logger.debug(EELFLoggerDelegate.debugLogger, "Finished createClientForApp method for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId); try { if (client != null) { + logger.debug(EELFLoggerDelegate.debugLogger, "Entering to PUT for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId); + response = client.put(payload); + + logger.debug(EELFLoggerDelegate.debugLogger, "Finished to PUT for payload: {} and restPath: {} and appId: {}", payload.toString(), restPath, appId); + } else { logger.error(EELFLoggerDelegate.errorLogger, "Unable to create the Webclient to make the '" + restPath + "' API call."); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthenticationCredentialServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthenticationCredentialServiceImpl.java index b50eb391..7241059e 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthenticationCredentialServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/BasicAuthenticationCredentialServiceImpl.java @@ -47,7 +47,10 @@ import org.onap.portalapp.portal.domain.EPEndpoint; import org.onap.portalapp.portal.domain.EPEndpointAccount; import org.onap.portalapp.portal.logging.aop.EPMetricsLog; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.util.SystemProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.stereotype.Service; @@ -68,20 +71,31 @@ public class BasicAuthenticationCredentialServiceImpl implements BasicAuthentica List<Criterion> restrictionsList = new ArrayList<Criterion>(); Criterion contextUserNameCrit = Restrictions.eq("username", username); restrictionsList.add(contextUserNameCrit); - Criterion contextPasswordCrit = Restrictions.eq("password", password); - restrictionsList.add(contextPasswordCrit); @SuppressWarnings("unchecked") List<BasicAuthCredentials> credList = (List<BasicAuthCredentials>) dataAccessService .getList(BasicAuthCredentials.class, null, restrictionsList, null); - if (credList == null || credList.size() == 0) { + if (credList ==null || credList.isEmpty()) { logger.error(EELFLoggerDelegate.errorLogger, "getBasicAuthCredentialByAppName: no credential(s) for " + username); return null; } logger.debug(EELFLoggerDelegate.debugLogger, "getBasicAuthCredentialByAppName: cred list size: " + credList.size()); - BasicAuthCredentials cred = (BasicAuthCredentials) credList.get(0); + BasicAuthCredentials cred = null; + for (BasicAuthCredentials basicAuthCredentials : credList) { + try { + final String dbDecryptedPwd = CipherUtil.decryptPKC(basicAuthCredentials.getPassword()); + if (dbDecryptedPwd.equals(password)) { + cred= (BasicAuthCredentials) basicAuthCredentials; + break; + } + } catch (CipherUtilException e) { + logger.error(EELFLoggerDelegate.errorLogger, "getBasicAuthCredentialByUsernameAndPassword() failed", e); + } + + } + if (cred!=null && cred.getId()!=null) cred.setEndpoints(getEndpointsByAccountId(cred.getId())); return cred; } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java index 8c055b2d..b2e9ebc5 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAppCommonServiceImpl.java @@ -100,7 +100,6 @@ import com.att.nsa.cambria.client.CambriaClient.CambriaApiException; import com.att.nsa.cambria.client.CambriaClientBuilders; import com.att.nsa.cambria.client.CambriaIdentityManager; import com.att.nsa.cambria.client.CambriaTopicManager; -import com.google.common.primitives.Ints; public class EPAppCommonServiceImpl implements EPAppService { @@ -515,8 +514,8 @@ public class EPAppCommonServiceImpl implements EPAppService { * (non-Javadoc) * * @see - * org.openecomp.portalapp.portal.service.EPAppService#getAppCatalog( - * org.openecomp.portalapp.portal.domain.EPUser) + * org.onap.portalapp.portal.service.EPAppService#getAppCatalog( + * org.onap.portalapp.portal.domain.EPUser) */ @Override public List<AppCatalogItem> getUserAppCatalog(EPUser user) { @@ -532,8 +531,8 @@ public class EPAppCommonServiceImpl implements EPAppService { * (non-Javadoc) * * @see - * org.openecomp.portalapp.portal.service.EPAppService#getAdminAppCatalog( - * org.openecomp.portalapp.portal.domain.EPUser) + * org.onap.portalapp.portal.service.EPAppService#getAdminAppCatalog( + * org.onap.portalapp.portal.domain.EPUser) */ @Override public List<AppCatalogItem> getAdminAppCatalog(EPUser user) { @@ -1404,7 +1403,7 @@ public class EPAppCommonServiceImpl implements EPAppService { epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol()); epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX()); epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY()); - HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>(); + HashMap<String, Long> additionalUpdateParam = new HashMap<>(); additionalUpdateParam.put("userId", epWidgetsManualSort.getUserId()); dataAccessService.saveDomainObject(epWidgetsManualSort, additionalUpdateParam); } else { @@ -1414,7 +1413,7 @@ public class EPAppCommonServiceImpl implements EPAppService { epWidgetsManualSort.setWidgetCol(epWidgetsManPref.getCol()); epWidgetsManualSort.setWidgetWidth(epWidgetsManPref.getSizeX()); epWidgetsManualSort.setWidgetHeight(epWidgetsManPref.getSizeY()); - epWidgetsManualSort.setUserId(Ints.checkedCast(user.getId())); + epWidgetsManualSort.setUserId(user.getId()); dataAccessService.saveDomainObject(epWidgetsManualSort, null); } fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); @@ -1485,7 +1484,7 @@ public class EPAppCommonServiceImpl implements EPAppService { EPUserAppsManualSortPreference epAppsManualSort = existingAppIds.get(appid); epAppsManualSort .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1); - HashMap<String, Integer> additionalUpdateParam = new HashMap<String, Integer>(); + HashMap<String, Long> additionalUpdateParam = new HashMap<>(); additionalUpdateParam.put("userId", epAppsManualSort.getUserId()); dataAccessService.saveDomainObject(epAppsManualSort, additionalUpdateParam); } else { @@ -1493,7 +1492,7 @@ public class EPAppCommonServiceImpl implements EPAppService { epAppsManualSort.setAppId(epAppsManPref.getAppid()); epAppsManualSort .setAppManualSortOrder((epAppsManPref.getCol() + (6 * epAppsManPref.getRow())) + 1); - epAppsManualSort.setUserId(Ints.checkedCast(user.getId())); + epAppsManualSort.setUserId(user.getId()); dataAccessService.saveDomainObject(epAppsManualSort, null); } fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); @@ -1509,9 +1508,9 @@ public class EPAppCommonServiceImpl implements EPAppService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.EPAppService# + * @see org.onap.portalapp.portal.service.EPAppService# * deleteUserAppSortManual(java.lang.String, - * org.openecomp.portalapp.portal.domain.EPUser) + * org.onap.portalapp.portal.domain.EPUser) */ @SuppressWarnings("unchecked") @Override @@ -1550,7 +1549,7 @@ public class EPAppCommonServiceImpl implements EPAppService { epSortTypes = dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null); if (epSortTypes.size() == 0) { usrSortPr = new EPUserAppsSortPreference(); - usrSortPr.setUserId(Ints.checkedCast(user.getId())); + usrSortPr.setUserId((int)(long)(user.getId())); usrSortPr.setSortPref(appsSortPreference.getValue()); dataAccessService.saveDomainObject(usrSortPr, null); fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAuditServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAuditServiceImpl.java index 1b3dfade..cb94147c 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAuditServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPAuditServiceImpl.java @@ -73,7 +73,7 @@ public class EPAuditServiceImpl implements EPAuditService { * (non-Javadoc) * * @see - * org.openecomp.portalapp.portal.service.EPUserService#getGuestLastLogin( + * org.onap.portalapp.portal.service.EPUserService#getGuestLastLogin( * java.lang.String) */ public Date getGuestLastLogin(String userId) { @@ -102,7 +102,7 @@ public class EPAuditServiceImpl implements EPAuditService { * (non-Javadoc) * * @see - * org.openecomp.portalapp.portal.service.EPAuditService#delAuditLogFromDay( + * org.onap.portalapp.portal.service.EPAuditService#delAuditLogFromDay( * ) */ @Override diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImpl.java index 98d31b16..243b7261 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImpl.java @@ -75,7 +75,7 @@ public class EPLeftMenuServiceImpl implements EPLeftMenuService { * (non-Javadoc) * * @see - * org.openecomp.portalapp.portal.service.EPLeftMenuService#getLeftMenuItems + * org.onap.portalapp.portal.service.EPLeftMenuService#getLeftMenuItems * (java.util.Set) */ @Override diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLoginServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLoginServiceImpl.java index eff297f5..1ec71d78 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLoginServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/EPLoginServiceImpl.java @@ -44,6 +44,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.commons.lang.StringUtils; import org.onap.portalapp.command.EPLoginBean; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.logging.aop.EPMetricsLog; @@ -52,6 +53,8 @@ import org.onap.portalapp.portal.logging.logic.EPLogUtil; import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.menu.MenuBuilder; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.service.support.FusionService; import org.onap.portalsdk.core.util.SystemProperties; @@ -74,7 +77,7 @@ public class EPLoginServiceImpl extends FusionService implements EPLoginService /* * (non-Javadoc) - * @see org.openecomp.portalapp.portal.service.EPLoginService#findUser(org.openecomp.portalapp.command.EPLoginBean, java.lang.String, java.util.HashMap) + * @see org.onap.portalapp.portal.service.EPLoginService#findUser(org.openecomp.portalapp.command.EPLoginBean, java.lang.String, java.util.HashMap) */ @SuppressWarnings("rawtypes") public EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename, HashMap additionalParams) @@ -84,7 +87,7 @@ public class EPLoginServiceImpl extends FusionService implements EPLoginService /* * (non-Javadoc) - * @see org.openecomp.portalapp.portal.service.EPLoginService#findUser(org.openecomp.portalapp.command.EPLoginBean, java.lang.String, java.util.HashMap, boolean) + * @see org.onap.portalapp.portal.service.EPLoginService#findUser(org.onap.portalapp.command.EPLoginBean, java.lang.String, java.util.HashMap, boolean) */ @SuppressWarnings("rawtypes") public EPLoginBean findUser(EPLoginBean bean, String menuPropertiesFilename_ignored, HashMap additionalParams, @@ -179,19 +182,31 @@ public class EPLoginServiceImpl extends FusionService implements EPLoginService * @param password * @return EPUser object; null on error or if no match. */ - @SuppressWarnings("rawtypes") + @SuppressWarnings({ "rawtypes", "unchecked" }) private EPUser findUser(String loginId, String password) { Map<String, String> params = new HashMap<>(); params.put("login_id", loginId); - params.put("login_pwd", password); - List list = null; + List<EPUser> list = null; try { - list = dataAccessService.executeNamedQuery("getEPUserByLoginIdLoginPwd", params, new HashMap()); + list = dataAccessService.executeNamedQuery("getEPUserByLoginId", params, new HashMap()); + for (EPUser user : list) { + try { + if (StringUtils.isNotBlank(user.getLoginPwd())) { + final String dbDecryptedPwd = CipherUtil.decryptPKC(user.getLoginPwd()); + if (dbDecryptedPwd.equals(password)) { + return user; + } + } + } catch (CipherUtilException e) { + logger.error(EELFLoggerDelegate.errorLogger, "findUser() failed", e); + } + } + } catch (Exception e) { EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); logger.error(EELFLoggerDelegate.errorLogger, "findUser failed on " + loginId, e); } - return (list == null || list.isEmpty()) ? null : (EPUser) list.get(0); + return null; } @SuppressWarnings("rawtypes") diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java index d65f1152..bcf806b2 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesService.java @@ -49,6 +49,7 @@ import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.ExternalRoleDetails; +import org.onap.portalapp.portal.exceptions.InvalidUserException; import org.onap.portalapp.portal.transport.CentralRole; import org.onap.portalapp.portal.transport.CentralUser; import org.onap.portalapp.portal.transport.CentralV2Role; @@ -100,7 +101,7 @@ public interface ExternalAccessRolesService { * @return EPUser object * @throws Exception */ - List<EPUser> getUser(String loginId) throws Exception; + List<EPUser> getUser(String loginId) throws InvalidUserException; /** * It returns complete user information including application roles permissions @@ -432,5 +433,23 @@ public interface ExternalAccessRolesService { ObjectMapper mapper, JSONArray extRole) throws IOException, JsonParseException, JsonMappingException; public JSONArray getAllUsersByRole(String roleName) throws Exception; + + /** + * + * It check function code has any pipes, if found return function type + * + * @param roleFuncItem + * @param type + * @return function type + */ + String getFunctionCodeType(String roleFuncItem); + + /** + * It return function action + * + * @param roleFuncItem + * @return String action + */ + String getFunctionCodeAction(String roleFuncItem); } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java index e867c3d6..39bd92d6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImpl.java @@ -122,10 +122,8 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; -import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; @@ -515,8 +513,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic String action = ""; if (roleFunc.getCode().contains(FUNCTION_PIPE)) { code = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); - type = getFunctionType(roleFunc.getCode()); - action = getFunctionAction(roleFunc.getCode()); + type = getFunctionCodeType(roleFunc.getCode()); + action = getFunctionCodeAction(roleFunc.getCode()); } else { code = roleFunc.getCode(); type = roleFunc.getCode().contains("menu") ? "menu" : "url"; @@ -665,8 +663,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic String action = ""; if (addFunction.getCode().contains(FUNCTION_PIPE)) { code = EcompPortalUtils.getFunctionCode(addFunction.getCode()); - type = getFunctionType(addFunction.getCode()); - action = getFunctionAction(addFunction.getCode()); + type = getFunctionCodeType(addFunction.getCode()); + action = getFunctionCodeAction(addFunction.getCode()); } else { code = addFunction.getCode(); type = addFunction.getCode().contains("menu") ? "menu" : "url"; @@ -722,8 +720,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic String action = ""; if (roleFunc.getCode().contains(FUNCTION_PIPE)) { code = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); - type = getFunctionType(roleFunc.getCode()); - action = getFunctionAction(roleFunc.getCode()); + type = getFunctionCodeType(roleFunc.getCode()); + action = getFunctionCodeAction(roleFunc.getCode()); } else { code = roleFunc.getCode(); type = roleFunc.getCode().contains("menu") ? "menu" : "url"; @@ -1105,10 +1103,14 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic @Override @SuppressWarnings("unchecked") - public List<EPUser> getUser(String loginId){ + public List<EPUser> getUser(String loginId) throws InvalidUserException{ final Map<String, String> userParams = new HashMap<>(); userParams.put("org_user_id", loginId); - return (List<EPUser>) dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null); + List<EPUser> userList = dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null); + if (userList.isEmpty()) { + throw new InvalidUserException("User not found"); + } + return userList; } @Override @@ -1189,8 +1191,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic List<CentralV2RoleFunction> getRoleFuncList = dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null); for (CentralV2RoleFunction roleFuncItem : getRoleFuncList) { String code = EcompPortalUtils.getFunctionCode(roleFuncItem.getCode()); - String type = getFunctionType(roleFuncItem.getCode()); - String action = getFunctionAction(roleFuncItem.getCode()); + String type = getFunctionCodeType(roleFuncItem.getCode()); + String action = getFunctionCodeAction(roleFuncItem.getCode()); roleFuncItem.setCode(EPUserUtils.decodeFunctionCode(code)); roleFuncItem.setType(type); roleFuncItem.setAction(action); @@ -1200,26 +1202,14 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic } - /** - * It return function action - * - * @param roleFuncItem - * @return String action - */ - private String getFunctionAction(String roleFuncItem) { + @Override + public String getFunctionCodeAction(String roleFuncItem) { return (!roleFuncItem.contains(FUNCTION_PIPE)) ? "*" : EcompPortalUtils.getFunctionAction(roleFuncItem); } - /** - * - * It check function code has any pipes, if found return function type - * - * @param roleFuncItem - * @param type - * @return function type - */ - private String getFunctionType(String roleFuncItem) { + @Override + public String getFunctionCodeType(String roleFuncItem) { String type = null; if ((roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu")) || (!roleFuncItem.contains(FUNCTION_PIPE) && roleFuncItem.contains("menu"))) { @@ -1283,7 +1273,15 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic final Map<String, Long> params = new HashMap<>(); CentralV2User userAppList = new CentralV2User(); CentralV2User user1 = null; + final Map<String, Long> params1 = new HashMap<>(); + List<EPRole> globalRoleList = new ArrayList<>(); + try { + if (app.getId() != PortalConstants.PORTAL_APP_ID) { + params1.put("userId", userInfo.getId()); + params1.put("appId", app.getId()); + globalRoleList = dataAccessService.executeNamedQuery("userAppGlobalRoles", params1, null); + } userAppList.setUserApps(new TreeSet<CentralV2UserApp>()); for (EPUserApp userApp : userAppSet) { if (userApp.getRole().getActive()) { @@ -1304,41 +1302,46 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic epApp.getThumbnail(), epApp.getUsername(), epApp.getUebKey(), epApp.getUebSecret(), epApp.getUebTopicName()); 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(); + EPRole result = null; + if (globalRoleList.size() > 0) + result = globalRoleList.stream() + .filter(x -> userApp.getRole().getId().equals(x.getId())).findAny() + .orElse(null); + if (result == null) + continue; + } else { + appId = userApp.getApp().getId(); + } params.put("roleId", userApp.getRole().getId()); - params.put(APP_ID, userApp.getApp().getId()); - CentralV2Role centralRole; - List<EPRole> globalRoleList; - globalRoleList = getGlobalRolesOfPortal(); - EPRole result = globalRoleList.stream().filter(x -> userApp.getRole().getId().equals(x.getId())) - .findAny().orElse(null); - if (result != null && userApp.getApp().getId() != app.getId()) { - userApp.getRole().setId(result.getId()); - centralRole = getGlobalRoleForRequestedApp(app.getId(), userApp.getRole().getId()); - cua.setRole(centralRole); + params.put(APP_ID, appId); + List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService + .executeNamedQuery("getAppRoleFunctionList", params, null); + SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>(); + for (CentralV2RoleFunction roleFunc : appRoleFunctionList) { + String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); + CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(), + functionCode, roleFunc.getName(), null, null); + roleFunctionSet.add(cenRoleFunc); + } + Long userRoleId = null; + if (globalRole.toLowerCase().startsWith("global_") + || epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) { + userRoleId = userApp.getRole().getId(); } else { - List<CentralV2RoleFunction> appRoleFunctionList = dataAccessService - .executeNamedQuery("getAppRoleFunctionList", params, null); - SortedSet<CentralV2RoleFunction> roleFunctionSet = new TreeSet<>(); - for (CentralV2RoleFunction roleFunc : appRoleFunctionList) { - String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); - CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(roleFunc.getId(), - functionCode, roleFunc.getName(), null, null); - roleFunctionSet.add(cenRoleFunc); - } - Long userRoleId = null; - if (globalRole.toLowerCase().startsWith("global_") - && epApp.getId().equals(PortalConstants.PORTAL_APP_ID)) { - userRoleId = userApp.getRole().getId(); - } else { - userRoleId = userApp.getRole().getAppRoleId(); - } - CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(), - userApp.getRole().getModified(), userApp.getRole().getCreatedId(), - userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(), - userApp.getRole().getName(), userApp.getRole().getActive(), - userApp.getRole().getPriority(), roleFunctionSet, null, null); - cua.setRole(cenRole); + userRoleId = userApp.getRole().getAppRoleId(); } + CentralV2Role cenRole = new CentralV2Role(userRoleId, userApp.getRole().getCreated(), + userApp.getRole().getModified(), userApp.getRole().getCreatedId(), + userApp.getRole().getModifiedId(), userApp.getRole().getRowNum(), + userApp.getRole().getName(), userApp.getRole().getActive(), + userApp.getRole().getPriority(), roleFunctionSet, null, null); + cua.setRole(cenRole); + userAppList.getUserApps().add(cua); } } @@ -1452,8 +1455,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic for (CentralV2RoleFunction roleFunc : cenRoleFuncList) { String functionCode = EcompPortalUtils.getFunctionCode(roleFunc.getCode()); functionCode = EPUserUtils.decodeFunctionCode(functionCode); - String type = getFunctionType(roleFunc.getCode()); - String action = getFunctionAction(roleFunc.getCode()); + String type = getFunctionCodeType(roleFunc.getCode()); + String action = getFunctionCodeAction(roleFunc.getCode()); CentralV2RoleFunction cenRoleFunc = new CentralV2RoleFunction(role.getId(), functionCode, roleFunc.getName(), null, type, action, null); roleFunctionSet.add(cenRoleFunc); @@ -1478,9 +1481,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic @SuppressWarnings("unchecked") @Override public CentralV2RoleFunction getRoleFunction(String functionCode, String uebkey) throws Exception { - if (functionCode.contains("|")) - functionCode = EcompPortalUtils.getFunctionCode(functionCode); - functionCode = encodeFunctionCode(functionCode); + String code = EcompPortalUtils.getFunctionCode(functionCode); + String encodedCode = encodeFunctionCode(code); CentralV2RoleFunction roleFunc = null; EPApp app = getApp(uebkey).get(0); List<CentralV2RoleFunction> getRoleFuncList = null; @@ -1490,17 +1492,20 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic params.put(APP_ID, String.valueOf(app.getId())); getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null); if (getRoleFuncList.isEmpty()) { - return roleFunc; - } else { - if (getRoleFuncList.size() > 1) { - CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(functionCode, getRoleFuncList); - if(cenV2RoleFunction == null) - return roleFunc; - roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction); - } else { - roleFunc = checkIfPipesExitsInFunctionCode(getRoleFuncList.get(0)); + params.put(FUNCTION_CODE_PARAMS, encodedCode); + getRoleFuncList = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null); + if (getRoleFuncList.isEmpty()) { + return roleFunc; } } + if (getRoleFuncList.size() > 1) { + CentralV2RoleFunction cenV2RoleFunction = appFunctionListFilter(encodedCode, getRoleFuncList); + if (cenV2RoleFunction == null) + return roleFunc; + roleFunc = checkIfPipesExitsInFunctionCode(cenV2RoleFunction); + } else { + roleFunc = getRoleFuncList.get(0); + } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "getRoleFunction: failed", e); throw e; @@ -1526,7 +1531,6 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic return roleFunc; } - @SuppressWarnings("unchecked") @Override public boolean saveCentralRoleFunction(CentralV2RoleFunction domainCentralRoleFunction, EPApp app) throws Exception { boolean saveOrUpdateFunction = false; @@ -1534,41 +1538,15 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic domainCentralRoleFunction.setCode(encodeFunctionCode(domainCentralRoleFunction.getCode())); final Map<String, String> functionParams = new HashMap<>(); functionParams.put("appId", String.valueOf(app.getId())); - List<CentralV2RoleFunction> appRoleFuncWithPipe = new ArrayList<>(); - // If request coming from portal application we use type, instance/code and action to fetch record - if(domainCentralRoleFunction.getType()!=null && domainCentralRoleFunction.getAction()!=null){ - functionParams.put(FUNCTION_CODE_PARAMS, domainCentralRoleFunction.getType()+FUNCTION_PIPE - +domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction()); - appRoleFuncWithPipe = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, functionParams, null); - if(appRoleFuncWithPipe.isEmpty()){ - functionParams.put(FUNCTION_CODE_PARAMS, domainCentralRoleFunction.getCode()); - appRoleFuncWithPipe = dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, functionParams, null); - } - } - // If request coming from SDK applications we use just function code to fetch record - else{ - functionParams.put(FUNCTION_CODE_PARAMS, domainCentralRoleFunction.getCode()); - } - CentralV2RoleFunction appFunctionCode = null; - if(!appRoleFuncWithPipe.isEmpty()){ - // Make sure we extract correct record if similar records are found as query uses like condition - appFunctionCode = appFunctionListFilter(domainCentralRoleFunction.getCode(), appRoleFuncWithPipe); - if(appFunctionCode == null){ - appFunctionCode = domainCentralRoleFunction; - } - } else{ - appFunctionCode = domainCentralRoleFunction; - } - appFunctionCode.setName(domainCentralRoleFunction.getName()); if(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()) { - addRoleFunctionInExternalSystem(appFunctionCode, app); + addRoleFunctionInExternalSystem(domainCentralRoleFunction, app); } if(domainCentralRoleFunction.getType() != null && domainCentralRoleFunction.getAction() != null){ - appFunctionCode.setCode(domainCentralRoleFunction.getType()+ + domainCentralRoleFunction.setCode(domainCentralRoleFunction.getType()+ FUNCTION_PIPE+domainCentralRoleFunction.getCode()+FUNCTION_PIPE+domainCentralRoleFunction.getAction()); } - appFunctionCode.setAppId(app.getId()); - dataAccessService.saveDomainObject(appFunctionCode, null); + domainCentralRoleFunction.setAppId(app.getId()); + dataAccessService.saveDomainObject(domainCentralRoleFunction, null); saveOrUpdateFunction = true; } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "saveCentralRoleFunction: failed", e); @@ -1702,8 +1680,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic ObjectMapper mapper = new ObjectMapper(); ExternalAccessPerms extPerms = new ExternalAccessPerms(); String instanceValue = EcompPortalUtils.getFunctionCode(domainCentralRoleFunction.getCode()); - String checkType = getFunctionType(domainCentralRoleFunction.getCode()); - String actionValue = getFunctionAction(domainCentralRoleFunction.getCode()); + String checkType = getFunctionCodeType(domainCentralRoleFunction.getCode()); + String actionValue = getFunctionCodeAction(domainCentralRoleFunction.getCode()); HttpHeaders headers = EcompPortalUtils.base64encodeKeyForAAFBasicAuth(); extPerms.setAction(actionValue); extPerms.setInstance(instanceValue); @@ -2777,9 +2755,11 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic extRoleParams.put(APP_ID, app.getId().toString()); roleList = dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null); } - EPRole updateRoleInactive = roleList.get(0); - updateRoleInactive.setActive(false); - dataAccessService.saveDomainObject(updateRoleInactive, null); + if(!roleList.isEmpty()) { + EPRole updateRoleInactive = roleList.get(0); + updateRoleInactive.setActive(false); + dataAccessService.saveDomainObject(updateRoleInactive, null); + } } } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, @@ -2875,8 +2855,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic EPAppRoleFunction checkRoleFunctionExits = roleFunctionsMap.get(externalpermission.getInstance()); if (checkRoleFunctionExits == null) { String funcCode = externalpermission.getType().substring(app.getNameSpace().length() + 1) - + FUNCTION_PIPE + externalAccessPerms.getInstance() + FUNCTION_PIPE - + externalAccessPerms.getAction(); + + FUNCTION_PIPE + externalpermission.getInstance() + FUNCTION_PIPE + + externalpermission.getAction(); EPAppRoleFunction checkRoleFunctionPipeExits = roleFunctionsMap.get(funcCode); if (checkRoleFunctionPipeExits == null) { try { @@ -3297,8 +3277,8 @@ public class ExternalAccessRolesServiceImpl implements ExternalAccessRolesServic action = EcompPortalUtils.getFunctionAction(role.getFunctionCd()); cenRoleFun = new CentralV2RoleFunction(null, instance, role.getFunctionName(), null, type, action, null); } else{ - type = getFunctionType(role.getFunctionCd()); - action = getFunctionAction(role.getFunctionCd()); + type = getFunctionCodeType(role.getFunctionCd()); + action = getFunctionCodeAction(role.getFunctionCd()); cenRoleFun = new CentralV2RoleFunction(null, role.getFunctionCd(), role.getFunctionName(), null, type, action, null); } return cenRoleFun; diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/GetAccessServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/GetAccessServiceImpl.java index fb0bf7f7..59385554 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/GetAccessServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/GetAccessServiceImpl.java @@ -62,7 +62,7 @@ public class GetAccessServiceImpl implements GetAccessService{ /* * (non-Javadoc) - * @see org.openecomp.portalapp.portal.service.GetAccessService#getAppAccessList() + * @see org.onap.portalapp.portal.service.GetAccessService#getAppAccessList() */ @SuppressWarnings("unchecked") @Override diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ManifestServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ManifestServiceImpl.java index 6ea66fe1..368c1cf6 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ManifestServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/ManifestServiceImpl.java @@ -59,7 +59,7 @@ public class ManifestServiceImpl implements ManifestService { /* * (non-Javadoc) - * @see org.openecomp.portalapp.portal.service.ManifestService#getWebappManifest() + * @see org.onap.portalapp.portal.service.ManifestService#getWebappManifest() */ public Attributes getWebappManifest() throws IOException { EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ManifestServiceImpl.class); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/PersUserAppServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/PersUserAppServiceImpl.java index 39b88f63..a0b32644 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/PersUserAppServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/PersUserAppServiceImpl.java @@ -38,25 +38,21 @@ package org.onap.portalapp.portal.service; import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; import java.util.List; -import java.util.Map; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.EnableAspectJAutoProxy; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.Restrictions; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.domain.EPUserApp; import org.onap.portalapp.portal.domain.PersUserAppSelection; -import org.onap.portalapp.portal.domain.PersUserWidgetSelection; import org.onap.portalapp.portal.logging.aop.EPMetricsLog; import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate; import org.onap.portalsdk.core.service.DataAccessService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.EnableAspectJAutoProxy; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; @Service("persUserAppService") @Transactional @@ -81,9 +77,9 @@ public class PersUserAppServiceImpl implements PersUserAppService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserAppSelectService# - * setAppCatalogSelection(org.openecomp.portalapp.portal.domain.EPUser, - * org.openecomp.portalapp.portal.transport.AppCatalogSelection) + * @see org.onap.portalapp.portal.service.UserAppSelectService# + * setAppCatalogSelection(org.onap.portalapp.portal.domain.EPUser, + * org.onap.portalapp.portal.transport.AppCatalogSelection) */ @Override public void setPersUserAppValue(EPUser user, EPApp app, boolean select, boolean pending) { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/SharedContextServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/SharedContextServiceImpl.java index a950c5ff..49513525 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/SharedContextServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/SharedContextServiceImpl.java @@ -71,7 +71,7 @@ public class SharedContextServiceImpl implements SharedContextService { /* * (non-Javadoc) * - * @see org.openecomp.portalsdk.core.service.SharedContextService# + * @see org.onap.portalsdk.core.service.SharedContextService# * getSharedContexts() */ @Override @@ -89,7 +89,7 @@ public class SharedContextServiceImpl implements SharedContextService { /* * (non-Javadoc) * - * @see org.openecomp.portalsdk.core.service.SharedContextService# + * @see org.onap.portalsdk.core.service.SharedContextService# * getSharedContext(java. lang.String, java.lang.String) */ @Override @@ -112,7 +112,7 @@ public class SharedContextServiceImpl implements SharedContextService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.SharedContextService# + * @see org.onap.portalapp.portal.service.SharedContextService# * addSharedContext(java.lang.String, java.lang.String, java.lang.String) */ @Override @@ -124,8 +124,8 @@ public class SharedContextServiceImpl implements SharedContextService { /* * (non-Javadoc) * - * @see org.openecomp.portalsdk.core.service.SharedContextService# - * saveSharedContext(org.openecomp.portalapp.portal.domain.SharedContext) + * @see org.onap.portalsdk.core.service.SharedContextService# + * saveSharedContext(org.onap.portalapp.portal.domain.SharedContext) */ @Override public void saveSharedContext(SharedContext context) { @@ -135,8 +135,8 @@ public class SharedContextServiceImpl implements SharedContextService { /* * (non-Javadoc) * - * @see org.openecomp.portalsdk.core.service.SharedContextService# - * deleteSharedContext(org.openecomp.portalapp.portal.domain.SharedContext) + * @see org.onap.portalsdk.core.service.SharedContextService# + * deleteSharedContext(org.onap.portalapp.portal.domain.SharedContext) */ @Override public void deleteSharedContext(SharedContext context) { @@ -146,7 +146,7 @@ public class SharedContextServiceImpl implements SharedContextService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.SharedContextService# + * @see org.onap.portalapp.portal.service.SharedContextService# * deleteSharedContexts(java.lang.String) */ @Override @@ -167,7 +167,7 @@ public class SharedContextServiceImpl implements SharedContextService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.SharedContextService# + * @see org.onap.portalapp.portal.service.SharedContextService# * expireSharedContexts(int) */ @Override diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserNotificationServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserNotificationServiceImpl.java index 130c99e7..aa3a4b12 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserNotificationServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserNotificationServiceImpl.java @@ -73,7 +73,7 @@ public class UserNotificationServiceImpl implements UserNotificationService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * @see org.onap.portalapp.portal.service.UserNotificationService# * getNotifications(java.lang.Long) */ @Override @@ -93,7 +93,7 @@ public class UserNotificationServiceImpl implements UserNotificationService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * @see org.onap.portalapp.portal.service.UserNotificationService# * getNotificationHistoryVO(java.lang.Long) */ @Override @@ -109,7 +109,7 @@ public class UserNotificationServiceImpl implements UserNotificationService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * @see org.onap.portalapp.portal.service.UserNotificationService# * getAdminNotificationVOS() */ @Override @@ -125,7 +125,7 @@ public class UserNotificationServiceImpl implements UserNotificationService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * @see org.onap.portalapp.portal.service.UserNotificationService# * getNotificationRoles(java.lang.Long) */ @Override @@ -141,7 +141,7 @@ public class UserNotificationServiceImpl implements UserNotificationService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * @see org.onap.portalapp.portal.service.UserNotificationService# * getAppRoleList() */ @SuppressWarnings("unchecked") @@ -155,7 +155,7 @@ public class UserNotificationServiceImpl implements UserNotificationService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserNotificationService# + * @see org.onap.portalapp.portal.service.UserNotificationService# * setNotificationsRead(java.lang.Long, int) */ @Override @@ -171,8 +171,8 @@ public class UserNotificationServiceImpl implements UserNotificationService { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserNotificationService# - * saveNotification(org.openecomp.portalapp.portal.transport. + * @see org.onap.portalapp.portal.service.UserNotificationService# + * saveNotification(org.onap.portalapp.portal.transport. * EpNotificationItem) */ @Override @@ -196,7 +196,9 @@ public class UserNotificationServiceImpl implements UserNotificationService { if (notificationItem.getNotificationId() != null) { EpNotificationItem updateNotificationItem = (EpNotificationItem) getDataAccessService() .getDomainObject(EpNotificationItem.class, notificationItem.getNotificationId(), null); - notificationItem.setRoles(updateNotificationItem.getRoles()); + if(updateNotificationItem != null) { + notificationItem.setRoles(updateNotificationItem.getRoles()); + } } if (notificationItem.msgSource == null) { notificationItem.setMsgSource("EP"); diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java index c65b4af9..ab4044d1 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImpl.java @@ -63,7 +63,6 @@ import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.json.JSONArray; import org.json.JSONObject; -import org.onap.portalapp.portal.service.SearchService; import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval; import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser; import org.onap.portalapp.portal.domain.EPApp; @@ -75,6 +74,7 @@ import org.onap.portalapp.portal.domain.EPUserAppRoles; import org.onap.portalapp.portal.domain.EPUserAppRolesRequest; import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail; import org.onap.portalapp.portal.domain.ExternalSystemAccess; +import org.onap.portalapp.portal.exceptions.SyncUserRolesException; import org.onap.portalapp.portal.logging.aop.EPMetricsLog; import org.onap.portalapp.portal.logging.format.EPAppMessagesEnum; import org.onap.portalapp.portal.logging.logic.EPLogUtil; @@ -246,7 +246,6 @@ public class UserRolesCommonServiceImpl { */ protected void syncUserRoles(SessionFactory sessionFactory, String userId, Long appId, EcompRole[] userAppRoles, Boolean extRequestValue, String reqType) throws Exception { - boolean result = false; Session localSession = null; Transaction transaction = null; String roleActive = null; @@ -361,23 +360,17 @@ public class UserRolesCommonServiceImpl { } } transaction.commit(); - result = true; } catch (Exception e) { logger.error(EELFLoggerDelegate.errorLogger, "syncUserRoles failed", e); EPLogUtil.logEcompError(logger, EPAppMessagesEnum.BeDaoSystemError, e); EcompPortalUtils.rollbackTransaction(transaction, "Exception occurred in syncUserRoles, Details: " + e.toString()); if("DELETE".equals(reqType)){ - throw new Exception(e.getMessage()); + throw new SyncUserRolesException(e.getMessage()); } } finally { - if (localSession != null) { - localSession.close(); - } - if (!result && !"DELETE".equals(reqType)) { - throw new Exception( - "Exception occurred in syncUserRoles while closing database session for app: '" + appId + "'."); - } + if(localSession != null) + localSession.close(); } } @@ -759,7 +752,7 @@ public class UserRolesCommonServiceImpl { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserRolesService# + * @see org.onap.portalapp.portal.service.UserRolesService# * importRolesFromRemoteApplication(java.lang.Long) */ public List<EPRole> importRolesFromRemoteApplication(Long appId) throws HTTPException { @@ -851,9 +844,9 @@ public class UserRolesCommonServiceImpl { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserRolesService# - * setAppWithUserRoleStateForUser(org.openecomp.portalapp.portal.domain. - * EPUser, org.openecomp.portalapp.portal.transport.AppWithRolesForUser) + * @see org.onap.portalapp.portal.service.UserRolesService# + * setAppWithUserRoleStateForUser(org.onap.portalapp.portal.domain. + * EPUser, org.onap.portalapp.portal.transport.AppWithRolesForUser) */ public boolean setAppWithUserRoleStateForUser(EPUser user, AppWithRolesForUser newAppRolesForUser) { boolean result = false; @@ -1572,7 +1565,7 @@ public class UserRolesCommonServiceImpl { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserRolesService# + * @see org.onap.portalapp.portal.service.UserRolesService# * getAppRolesForUser(java.lang.Long, java.lang.String) */ @SuppressWarnings("unchecked") @@ -1606,7 +1599,7 @@ public class UserRolesCommonServiceImpl { activeRoleList.add(role); } } - + } EPUser localUser = getUserFromApp(userId, app, applicationsRestClientService); // If localUser does not exists return roles @@ -1623,7 +1616,9 @@ public class UserRolesCommonServiceImpl { EcompRole[] appRoles = null; List<EcompRole> roles = new ArrayList<>(); if(app.getCentralAuth()){ - List<EPRole> applicationRoles = dataAccessService.getList(EPRole.class, " where app_id = "+app.getId()+ " and active_yn = 'Y'", null, null);; + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + List<EPRole> applicationRoles = dataAccessService.executeNamedQuery("getActiveRolesOfApplication", appParams, null); for(EPRole role : applicationRoles){ EcompRole ecompRole = new EcompRole(); ecompRole.setId(role.getId()); @@ -1739,10 +1734,11 @@ public class UserRolesCommonServiceImpl { return result; } + @SuppressWarnings("unchecked") public FieldsValidator putUserAppRolesRequest(AppWithRolesForUser userAppRolesData, EPUser user) { FieldsValidator fieldsValidator = new FieldsValidator(); final Map<String, Long> params = new HashMap<>(); - EPUserAppRoles appRole= new EPUserAppRoles(); + List<EPUserAppRoles> appRole= null; try { logger.error(EELFLoggerDelegate.errorLogger,"Should not be reached here, still the endpoint is yet to be defined"); boolean result = postUserRolesToMylogins(userAppRolesData, applicationsRestClientService, userAppRolesData.appId, user.getId()); @@ -1762,13 +1758,15 @@ public class UserRolesCommonServiceImpl { Boolean isAppliedVal = userAppRoles.isApplied; params.put("appRoleId", userAppRoles.roleId); if (isAppliedVal) { - appRole = (EPUserAppRoles) dataAccessService.executeNamedQuery("appRoles", params, null).get(0); - EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail(); - epAppRoleDetail.setReqRoleId(appRole.getRoleId()); - epAppRoleDetail.setReqType("P"); - epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData); - dataAccessService.saveDomainObject(epAppRoleDetail, null); - } + appRole = (List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null); + if (!appRole.isEmpty()) { + EPUserAppRolesRequestDetail epAppRoleDetail = new EPUserAppRolesRequestDetail(); + epAppRoleDetail.setReqRoleId(appRole.get(0).getRoleId()); + epAppRoleDetail.setReqType("P"); + epAppRoleDetail.setEpRequestIdData(epAppRolesRequestData); + dataAccessService.saveDomainObject(epAppRoleDetail, null); + } + } } epAppRolesRequestData.setEpRequestIdDetail(appRoleDetails); fieldsValidator.httpStatusCode = new Long(HttpServletResponse.SC_OK); @@ -1831,7 +1829,7 @@ public class UserRolesCommonServiceImpl { /* * (non-Javadoc) * - * @see org.openecomp.portalapp.portal.service.UserRolesService# + * @see org.onap.portalapp.portal.service.UserRolesService# * getCachedAppRolesForUser(java.lang.Long, java.lang.Long) */ public List<EPUserApp> getCachedAppRolesForUser(Long appId, Long userId) { diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EventWidget.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EventWidget.java index 96562399..d96f1821 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EventWidget.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/EventWidget.java @@ -36,7 +36,7 @@ package org.onap.portalapp.portal.transport; * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -/*package org.openecomp.portalapp.portal.transport; +/*package org.onap.portalapp.portal.transport; import javax.persistence.Column; import javax.persistence.Entity; @@ -45,7 +45,7 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import org.openecomp.portalsdk.core.domain.support.DomainVo; +import org.onap.portalsdk.core.domain.support.DomainVo; import com.fasterxml.jackson.annotation.JsonInclude; *//** diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/ExternalRequestFieldsValidator.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/ExternalRequestFieldsValidator.java index 75418df5..67dba090 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/ExternalRequestFieldsValidator.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/transport/ExternalRequestFieldsValidator.java @@ -60,6 +60,37 @@ public class ExternalRequestFieldsValidator { this.detailMessage = detailMessage; } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((detailMessage == null) ? 0 : detailMessage.hashCode()); + result = prime * result + (this.result ? 1231 : 1237); + return result; + } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ExternalRequestFieldsValidator other = (ExternalRequestFieldsValidator) obj; + if (detailMessage == null) { + if (other.detailMessage != null) + return false; + } else if (!detailMessage.equals(other.detailMessage)) + return false; + if (result != other.result) + return false; + return true; + } + + + + + } diff --git a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/CustomLoggingFilter.java b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/CustomLoggingFilter.java index 0b564eec..4b580e0a 100644 --- a/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/CustomLoggingFilter.java +++ b/ecomp-portal-BE-common/src/main/java/org/onap/portalapp/portal/utils/CustomLoggingFilter.java @@ -59,7 +59,7 @@ public class CustomLoggingFilter extends Filter<ILoggingEvent> { try { if ((event.getLevel() != Level.ERROR || event.getLevel() != Level.WARN) && (event.getThreadName().equalsIgnoreCase("UEBConsumerThread")) && - (event.getLoggerName().contains("org.openecomp.nsa") || event.getLoggerName().contains("org.apache.http")) + (event.getLoggerName().contains("org.onap.nsa") || event.getLoggerName().contains("org.apache.http")) ) { return FilterReply.DENY; } else { diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml index f82d2cb7..5968b3ce 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/EP.hbm.xml @@ -1985,6 +1985,15 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y ; ]]> </sql-query> + + <!-- Gets all active records from fn_role that is associated with this app--> + <sql-query name="getActiveRolesOfApplication"> + <return alias="activeRolesOfApplication" class="org.onap.portalapp.portal.domain.EPRole" /> + <![CDATA[ + select * from fn_role where active_yn = 'Y' and app_id=:appId + ; + ]]> + </sql-query> <sql-query name="getBulkUserRoles"> <return alias="bulkUserRoles" class="org.onap.portalapp.portal.transport.BulkUploadUserRoles" /> @@ -2097,10 +2106,12 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y from fn_user fu, fn_role fr, fn_user_role fur 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' union - 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, fu.active_yn , fr.role_id, fr.role_name - from fn_user fu, fn_role fr, fn_user_role fur - where fu.user_id = fur.user_id and fu.active_yn='Y' and fur.app_id=:appId and fr.role_name like 'global%' and fr.active_yn='Y' - ; + 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, fu.active_yn , fr.role_id, fr.role_name + from fn_user_role a, fn_role fr, fn_user fu + 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' + ; ]]> </sql-query> @@ -2318,6 +2329,15 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y ; ]]> </sql-query> + + + <query name="getBasicauthAccount"> + select id,password from BasicAuthCredentials + </query> + + <query name="getMicroserviceInfo"> + select id,password from MicroserviceData + </query> <sql-query name="getUserRoleOnUserIdAndRoleIdAndAppId"> <return alias="getUserRoleOnUserIdAndRoleIdAndAppId" class="org.onap.portalapp.portal.domain.EPUserApp" /> @@ -2329,14 +2349,16 @@ where fn_role.app_id = fn_app.app_id and fn_app.enabled='Y' and fn_role.active_y ; ]]> - </sql-query> - - <query name="getBasicauthAccount"> - select id,password from BasicAuthCredentials - </query> + </sql-query> + + <sql-query name="userAppGlobalRoles"> + <return alias="userAppGlobalRoles" class="org.onap.portalapp.portal.domain.EPRole" /> + <![CDATA[ + select fr.role_id , fr.role_name ,fr.active_yn, fr.priority, fr.app_id, fr.app_role_id + from fn_user_role a, fn_role fr, fn_user fu + 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 + ; + ]]> + </sql-query> - <query name="getMicroserviceInfo"> - select id,password from MicroserviceData - </query> - </hibernate-mapping> diff --git a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Fusion.hbm.xml b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Fusion.hbm.xml index 819a5212..0487006d 100644 --- a/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Fusion.hbm.xml +++ b/ecomp-portal-BE-common/src/main/webapp/WEB-INF/fusion/orm/Fusion.hbm.xml @@ -353,5 +353,5 @@ Portal app mappings and features are in EP.hbm.xml. select sum(total_lines) TOTAL_LINES from demo_kpi_sourcecode_stats group by category1 ]]> </sql-query> - + </hibernate-mapping> diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java index 522ef7ca..e35d3266 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/AppContactUsControllerTest.java @@ -306,13 +306,13 @@ public class AppContactUsControllerTest extends MockitoTestSuite{ PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); expectedResponse.setStatus(PortalRestStatusEnum.OK); expectedResponse.setMessage("success"); - expectedResponse.setResponse("\"ush_ticket_url\":\"http://todo_enter_ush_ticket_url\",\"portal_info_url\":\"https://todo_enter_portal_info_url\",\"feedback_email_address\":\"portal@lists.openecomp.org\""); + expectedResponse.setResponse("\"ush_ticket_url\":\"http://todo_enter_ush_ticket_url\",\"portal_info_url\":\"https://todo_enter_portal_info_url\",\"feedback_email_address\":\"portal@lists.onap.org\""); PowerMockito.mockStatic(SystemProperties.class); PowerMockito.mockStatic(EPCommonSystemProperties.class); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.USH_TICKET_URL)).thenReturn("http://todo_enter_ush_ticket_url"); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.PORTAL_INFO_URL)).thenReturn("https://todo_enter_portal_info_url"); - Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS)).thenReturn("portal@lists.openecomp.org"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS)).thenReturn("portal@lists.onap.org"); actualResponse = appContactUsController.getPortalDetails(mockedRequest); assertTrue(actualResponse.getStatus().compareTo(PortalRestStatusEnum.OK) == 0); @@ -330,7 +330,7 @@ public class AppContactUsControllerTest extends MockitoTestSuite{ Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.USH_TICKET_URL)).thenThrow(nullPointerException); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.PORTAL_INFO_URL)).thenReturn("https://todo_enter_portal_info_url"); - Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS)).thenReturn("portal@lists.openecomp.org"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.FEEDBACK_EMAIL_ADDRESS)).thenReturn("portal@lists.onap.org"); actualResponse = appContactUsController.getPortalDetails(mockedRequest); assertEquals(actualResponse, expectedResponse); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java index 37f7f687..54671ad3 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/DashboardControllerTest.java @@ -242,7 +242,7 @@ public class DashboardControllerTest { expectedData.setStatus(PortalRestStatusEnum.ERROR); expectedData.setMessage("ERROR"); expectedData.setResponse("Category cannot be null or empty"); - + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget, mockedRequest, mockedResponse); assertEquals(expectedData,actualResponse); @@ -258,7 +258,7 @@ public class DashboardControllerTest { expectedData.setMessage("Invalid category: test"); expectedData.setResponse(null); Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); - PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget, mockedRequest, mockedResponse); + PortalRestResponse<String> actualResponse = dashboardController.saveWidgetData(commonWidget,mockedRequest, mockedResponse); assertEquals(expectedData,actualResponse); } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java index 859cc4c2..47a1394e 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/ExternalAccessRolesControllerTest.java @@ -76,6 +76,7 @@ import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.restful.domain.EcompUser; import org.springframework.beans.BeanUtils; import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import com.fasterxml.jackson.core.JsonProcessingException; @@ -624,7 +625,17 @@ public class ExternalAccessRolesControllerTest { EcompUser user = new EcompUser(); user.setOrgUserId("guestT"); users.add(user); + StringWriter sw = new StringWriter(); + PrintWriter writer = new PrintWriter(sw); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + List<EPApp> applicationList = new ArrayList<EPApp>(); + EPApp app = mockApp(); + app.setCentralAuth(true); + applicationList.add(app); + Mockito.when(externalAccessRolesService.getApp(mockedRequest.getHeader(uebKey))).thenReturn(applicationList); Mockito.when(externalAccessRolesService.getAllAppUsers(mockedRequest.getHeader(uebKey))).thenReturn(users); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(app)).thenReturn(response); List<EcompUser> expectedUsers = externalAccessRolesController.getUsersOfApplication(mockedRequest, mockedResponse); assertEquals(expectedUsers, users); } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/HealthCheckControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/HealthCheckControllerTest.java new file mode 100644 index 00000000..92c0b21e --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/HealthCheckControllerTest.java @@ -0,0 +1,76 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.controller; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.framework.MockitoTestSuite; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest(EcompPortalUtils.class) +public class HealthCheckControllerTest { + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + HealthCheckController healthCheckController = new HealthCheckController(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + + @Test + public void healthCheckFailTest() { + PowerMockito.mockStatic(EcompPortalUtils.class); + healthCheckController.healthCheck(mockedRequest, mockedResponse); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceProxyControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceProxyControllerTest.java index 446c11c4..6f9ce496 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceProxyControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/MicroserviceProxyControllerTest.java @@ -37,6 +37,7 @@ */ package org.onap.portalapp.portal.controller; +import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import javax.servlet.http.HttpServletRequest; @@ -106,7 +107,7 @@ public class MicroserviceProxyControllerTest extends MockitoTestSuite { Mockito.when(microserviceProxyService.proxyToDestination(1, user, mockedRequest)) .thenThrow(httpClientErrorException); String acutualString = microserviceProxyController.getMicroserviceProxy(mockedRequest, getMockedResponse(), 1); - assertTrue(acutualString.equals("{\"error\":\"\"}")); + assertEquals("", acutualString); } @Test @@ -138,6 +139,6 @@ public class MicroserviceProxyControllerTest extends MockitoTestSuite { .thenThrow(httpClientErrorException); String acutualString = microserviceProxyController.getMicroserviceProxyByWidgetId(mockedRequest, getMockedResponse(), 1); - assertTrue(acutualString.equals("{\"error\":\"\"}")); - } + assertEquals("", acutualString); + } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java index e63ea438..d7f64c1d 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/RoleManageControllerTest.java @@ -38,9 +38,15 @@ package org.onap.portalapp.portal.controller; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; import java.io.PrintWriter; +import java.io.StringReader; import java.io.StringWriter; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -51,8 +57,10 @@ import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.json.simple.JSONObject; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Matchers; import org.mockito.Mock; @@ -63,6 +71,7 @@ import org.onap.portalapp.controller.core.RoleFunctionListController; import org.onap.portalapp.controller.core.RoleListController; import org.onap.portalapp.portal.core.MockEPUser; import org.onap.portalapp.portal.domain.CentralV2RoleFunction; +import org.onap.portalapp.portal.domain.CentralizedApp; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPUser; import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; @@ -73,44 +82,54 @@ import org.onap.portalapp.portal.service.EPAppService; import org.onap.portalapp.portal.service.ExternalAccessRolesService; import org.onap.portalapp.portal.transport.CentralV2Role; import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalsdk.core.domain.Role; import org.onap.portalsdk.core.service.AuditService; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.DelegatingServletInputStream; import org.springframework.web.servlet.ModelAndView; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EPUserUtils.class, EcompPortalUtils.class }) public class RoleManageControllerTest { @Mock - RoleController roleController; + RoleController roleController; @Mock - RoleListController roleListController; + RoleListController roleListController; @Mock - RoleFunctionListController roleFunctionListController; - + RoleFunctionListController roleFunctionListController; @Mock ExternalAccessRolesService externalAccessRolesService; @Mock EPUserUtils ePUserUtils = new EPUserUtils(); - + @Mock ExternalAccessRolesService externalAccessRolesService1 = null; - + @InjectMocks - RoleManageController roleManageController = new RoleManageController(); - + RoleManageController roleManageController = new RoleManageController(); + @Mock EPAppService appService; @Mock AuditService auditService; - + @Mock AdminRolesService adminRolesService; - + @Before public void setup() { MockitoAnnotations.initMocks(this); @@ -122,41 +141,46 @@ public class RoleManageControllerTest { HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); NullPointerException nullPointerException = new NullPointerException(); MockEPUser mockUser = new MockEPUser(); - - + @Test - public void removeRoleRoleFunctionTest() throws Exception - { - + public void removeRoleRoleFunctionTest() throws Exception { + ModelAndView modelandView = new ModelAndView("login.htm"); Mockito.when(roleController.removeRoleFunction(mockedRequest, mockedResponse)).thenReturn(modelandView); - ModelAndView expectedModelandView = roleManageController.removeRoleRoleFunction(mockedRequest, mockedResponse); + ModelAndView expectedModelandView = roleManageController.removeRoleRoleFunction(mockedRequest, mockedResponse); assertEquals(expectedModelandView, modelandView); } - + @Test - public void addRoleRoRoleFunctionTest() throws Exception - { + public void addRoleRoRoleFunctionTest() throws Exception { ModelAndView modelandView = new ModelAndView("login.htm"); Mockito.when(roleController.addRoleFunction(mockedRequest, mockedResponse)).thenReturn(modelandView); - ModelAndView expectedModelandView = roleManageController.addRoleRoRoleFunction(mockedRequest, mockedResponse); + ModelAndView expectedModelandView = roleManageController.addRoleRoRoleFunction(mockedRequest, mockedResponse); assertEquals(expectedModelandView, modelandView); } - + @Test - public void removeChildRoleTest() throws Exception - { + public void removeChildRoleTest() throws Exception { ModelAndView modelandView = new ModelAndView("login.htm"); Mockito.when(roleController.removeChildRole(mockedRequest, mockedResponse)).thenReturn(modelandView); - ModelAndView expectedModelandView = roleManageController.removeChildRole(mockedRequest, mockedResponse); + ModelAndView expectedModelandView = roleManageController.removeChildRole(mockedRequest, mockedResponse); assertEquals(expectedModelandView, modelandView); } - - + @Test - public void getRoleIfRoleIdNullTest() throws Exception - { + public void getRoleIfRoleIdNullTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + List<EPApp> apps = new ArrayList<>(); + apps.add(CentralApp()); + Mockito.when(externalAccessRolesService.getApp(CentralApp().getUebKey())).thenReturn(apps); + ResponseEntity<String> result = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(apps.get(0))).thenReturn(result); CentralV2Role answer = new CentralV2Role(); Mockito.when(externalAccessRolesService.getRoleInfo((long) 1, "test")).thenReturn(answer); List<CentralV2RoleFunction> finalRoleFunctionList = new ArrayList<>(); @@ -164,29 +188,27 @@ public class RoleManageControllerTest { Mockito.when(externalAccessRolesService.getRolesForApp("test")).thenReturn(null); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); - Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); - roleManageController.getRole(mockedRequest, mockedResponse, (long)1,null); - -} - + roleManageController.getRole(mockedRequest, mockedResponse, (long) 1, null); + } + @Test(expected = Exception.class) - public void getRoleExceptionTest() throws Exception - { + public void getRoleExceptionTest() throws Exception { Mockito.when(appService.getApp((long) 1)).thenReturn(mockApp()); CentralV2Role answer = new CentralV2Role(); Mockito.when(externalAccessRolesService.getRoleInfo((long) 1, "test")).thenReturn(answer); Mockito.when(externalAccessRolesService.getRoleFuncList("test")).thenThrow(nullPointerException); - roleManageController.getRole(mockedRequest, mockedResponse, (long)1,null); - -} + roleManageController.getRole(mockedRequest, mockedResponse, (long) 1, null); + + } + @Test - public void getRoleIfRoleIdNotNullTest() throws Exception - { + public void getRoleIfRoleIdNotNullTest() throws Exception { Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); CentralV2Role answer = new CentralV2Role(); Mockito.when(externalAccessRolesService.getRoleInfo((long) 1, "test")).thenReturn(answer); @@ -194,11 +216,11 @@ public class RoleManageControllerTest { Mockito.when(externalAccessRolesService.getRoleFuncList("test")).thenReturn(finalRoleFunctionList); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); - Mockito.when(mockedResponse.getWriter()).thenReturn(writer); + Mockito.when(mockedResponse.getWriter()).thenReturn(writer); CentralV2Role currentRole = new CentralV2Role(); - SortedSet<CentralV2Role> parentRoles = new TreeSet<>(); + SortedSet<CentralV2Role> parentRoles = new TreeSet<>(); CentralV2Role centralV2Role = new CentralV2Role(); - centralV2Role.setName("test"); + centralV2Role.setName("test"); parentRoles.add(centralV2Role); currentRole.setParentRoles(parentRoles); Mockito.when(externalAccessRolesService.getRoleInfo((long) 1, "test")).thenReturn(currentRole); @@ -208,13 +230,12 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); - roleManageController.getRole(mockedRequest, mockedResponse, (long)1,(long)1); -} - - public EPApp mockApp() - { + roleManageController.getRole(mockedRequest, mockedResponse, (long) 1, (long) 1); + } + + public EPApp mockApp() { EPApp app = new EPApp(); app.setName("Test"); @@ -237,12 +258,20 @@ public class RoleManageControllerTest { app.setUebTopicName("test"); app.setAppType(1); return app; - + } + @Test public void getRolesTest() throws Exception { EPApp app = mockApp(); app.setCentralAuth(true); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(appService.getApp((long) 1)).thenReturn(app); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, app)).thenReturn(true); List<CentralV2Role> answer = new ArrayList<>(); Mockito.when(appService.getApp((long) 1)).thenReturn(app); Mockito.when(externalAccessRolesService.getRolesForApp("test")).thenReturn(answer); @@ -252,7 +281,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); roleManageController.getRoles(mockedRequest, mockedResponse, (long) 1); } @@ -268,6 +297,12 @@ public class RoleManageControllerTest { @Test public void getRoleFunctionListTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); List<CentralV2RoleFunction> answer = new ArrayList<>(); Mockito.when(externalAccessRolesService.getRoleFuncList("test")).thenReturn(answer); @@ -277,7 +312,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); roleManageController.getRoleFunctionList(mockedRequest, mockedResponse, (long) 1); } @@ -290,16 +325,27 @@ public class RoleManageControllerTest { @Test public void saveRoleFunctionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); Mockito.doNothing().when(roleFunctionListController).saveRoleFunction(mockedRequest, mockedResponse, "test"); CentralV2RoleFunction addNewFunc = new CentralV2RoleFunction(); addNewFunc.setCode("Test"); + addNewFunc.setType("Test"); + addNewFunc.setAction("Test"); addNewFunc.setName("Test"); CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); - Mockito.when(externalAccessRolesService.getRoleFunction("Test", "test")).thenReturn(roleFunction); + roleFunction.setCode("Test|Test|Test"); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); Mockito.when(externalAccessRolesService.saveCentralRoleFunction(Matchers.anyObject(), Matchers.anyObject())) .thenReturn(true); - EPUser user = mockUser.mockEPUser(); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionType(roleFunction.getCode())).thenReturn("Test"); + Mockito.when(EcompPortalUtils.getFunctionAction(roleFunction.getCode())).thenReturn("Test"); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); List<EPUser> userList = new ArrayList<>(); userList.add(user); @@ -310,9 +356,13 @@ public class RoleManageControllerTest { PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); - roleManageController.saveRoleFunction(mockedRequest, mockedResponse, addNewFunc, (long) 1); + PortalRestResponse<String> actual = roleManageController.saveRoleFunction(mockedRequest, mockedResponse, + addNewFunc, (long) 1); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.OK, + "Saved Successfully!", "Success"); + assertEquals(expected, actual); } @Test @@ -332,18 +382,22 @@ public class RoleManageControllerTest { addNewFunc.setCode("Test"); addNewFunc.setName("Test"); Mockito.when(appService.getApp((long) 1)).thenReturn(NonCentralApp()); - String roleFun = "{\"name\":\"Test\",\"code\":\"Test\"}"; roleManageController.saveRoleFunction(mockedRequest, mockedResponse, addNewFunc, (long) 1); } @Test public void removeRoleFunctionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); EPUser user = mockUser.mockEPUser(); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdminOfApplication(user, CentralApp())).thenReturn(true); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); - String roleFun = "{\"name\":\"Test\",\"code\":\"Test\"}"; + String roleFun = "{\"name\":\"Test\",\"type\":\"Test\",\"action\":\"Test\", \"code\":\"Test\"}"; CentralV2RoleFunction roleFunction = mockCentralRoleFunction(); - Mockito.when(externalAccessRolesService.getRoleFunction("Test", "test")).thenReturn(roleFunction); + Mockito.when(externalAccessRolesService.getRoleFunction("Test|Test|Test", "test")).thenReturn(roleFunction); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); @@ -352,9 +406,13 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); - roleManageController.removeRoleFunction(mockedRequest, mockedResponse, roleFun, (long) 1); + PortalRestResponse<String> actual = roleManageController.removeRoleFunction(mockedRequest, mockedResponse, + roleFun, (long) 1); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.OK, + "Deleted Successfully!", "Success"); + assertEquals(expected, actual); } @Test @@ -373,7 +431,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); roleManageController.removeRoleFunction(mockedRequest, mockedResponse, roleFun, (long) 1); } @@ -389,9 +447,12 @@ public class RoleManageControllerTest { @Test public void syncRolesTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + EPUser user = mockUser.mockEPUser(); EPApp app = mockApp(); app.setId((long) 1); - EPUser user = mockUser.mockEPUser(); Mockito.when(appService.getApp(1l)).thenReturn(app); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); @@ -399,7 +460,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); PortalRestResponse<String> actual = roleManageController.syncRoles(mockedRequest, mockedResponse, 1l); PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); @@ -419,9 +480,12 @@ public class RoleManageControllerTest { portalRestResponse.setStatus(PortalRestStatusEnum.ERROR); assertEquals(portalRestResponse, actual); } - + @Test public void syncRolesFunctionsTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); EPApp app = mockApp(); app.setId((long) 1); EPUser user = mockUser.mockEPUser(); @@ -432,7 +496,7 @@ public class RoleManageControllerTest { List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); PortalRestResponse<String> actual = roleManageController.syncFunctions(mockedRequest, mockedResponse, 1l); PortalRestResponse<String> portalRestResponse = new PortalRestResponse<>(); @@ -452,18 +516,20 @@ public class RoleManageControllerTest { portalRestResponse.setStatus(PortalRestStatusEnum.ERROR); assertEquals(portalRestResponse, actual); } - + @Test - public void addeChildRoleTest() throws Exception - { + public void addChildRoleTest() throws Exception { ModelAndView modelandView = new ModelAndView("login.htm"); Mockito.when(roleController.addChildRole(mockedRequest, mockedResponse)).thenReturn(modelandView); - ModelAndView expectedModelandView = roleManageController.addChildRole(mockedRequest, mockedResponse); + ModelAndView expectedModelandView = roleManageController.addChildRole(mockedRequest, mockedResponse); assertEquals(expectedModelandView, modelandView); } - + @Test public void removeRoleTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); List<EPUser> epuserList = new ArrayList<>(); List<EPApp> appList = new ArrayList<>(); appList.add(CentralApp()); @@ -471,6 +537,7 @@ public class RoleManageControllerTest { epuserList.add(user); Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); StringWriter sw = new StringWriter(); PrintWriter writer = new PrintWriter(sw); Mockito.when(mockedResponse.getWriter()).thenReturn(writer); @@ -480,14 +547,16 @@ public class RoleManageControllerTest { Mockito.when(externalAccessRolesService.getUser(Matchers.anyString())).thenReturn(epuserList); Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); - Mockito.when( externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); Map<String, Object> expedtedResponse = new HashMap<String, Object>(); expedtedResponse.put("restCallStatus", " Unauthorized user"); - Map<String, Object> actualResponse = roleManageController.removeRole(mockedRequest, mockedResponse, (long) 1, (long) 1); + expedtedResponse.put("availableRoles", new ArrayList<>()); + Map<String, Object> actualResponse = roleManageController.removeRole(mockedRequest, mockedResponse, (long) 1, + (long) 1); assertEquals(actualResponse.size(), expedtedResponse.size()); } - + @Test(expected = Exception.class) public void removeRoleExceptionTest() throws Exception { EPUser user = mockUser.mockEPUser(); @@ -498,28 +567,344 @@ public class RoleManageControllerTest { Mockito.when(mockedResponse.getWriter()).thenReturn(writer); roleManageController.removeRole(mockedRequest, mockedResponse, (long) 1, (long) 1); } + + @SuppressWarnings("unchecked") + @Test + public void saveRoleNewTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + JSONObject roleJson = new JSONObject(); + roleJson.put("name", "test"); + JSONObject roleJson2 = new JSONObject(); + List<JSONObject> childRolesJson = new ArrayList<>(); + List<JSONObject> roleFunctions = new ArrayList<>(); + roleJson2.put("role", roleJson); + roleJson2.put("childRoles", childRolesJson); + roleJson2.put("roleFunctions", roleFunctions); + ObjectMapper mapper = new ObjectMapper(); + JsonNode actualObj = mapper.readTree(roleJson2.toString()); + Mockito.when(mockedRequest.getInputStream()).thenReturn(new DelegatingServletInputStream( + new ByteArrayInputStream(actualObj.toString().getBytes(StandardCharsets.UTF_8)))); + Mockito.when(mockedRequest.getReader()).thenReturn(new BufferedReader(new StringReader(actualObj.toString()))); + Mockito.when(mockedRequest.getContentType()).thenReturn("application/json"); + Mockito.when(mockedRequest.getCharacterEncoding()).thenReturn("UTF-8"); + Mockito.when(externalAccessRolesService.ConvertCentralRoleToRole(Matchers.anyString())).thenReturn(new Role()); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, ""); + Mockito.when(externalAccessRolesService.saveRoleForApplication(Matchers.any(), Matchers.any())) + .thenReturn(externalRequestFieldsValidator); + Map<String, Object> actual = roleManageController.saveRole(mockedRequest, mockedResponse, CentralApp().getId()); + final Map<String, Object> expected = new HashMap<>(); + expected.put("role", new CentralV2Role(null, "test")); + expected.put("status", "Success"); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void saveRoleUpdateTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + JSONObject roleJson = new JSONObject(); + roleJson.put("id", 1); + roleJson.put("name", "test"); + roleJson.put("active", true); + JSONObject roleJson2 = new JSONObject(); + List<JSONObject> childRolesJson = new ArrayList<>(); + List<JSONObject> roleFunctions = new ArrayList<>(); + JSONObject roleFunction = new JSONObject(); + roleFunction.put("code", "test"); + roleFunction.put("name", "test"); + roleFunction.put("type", "test"); + roleFunction.put("action", "test"); + roleFunctions.add(roleFunction); + roleJson.put("roleFunctions", roleFunctions); + roleJson2.put("role", roleJson); + roleJson2.put("childRoles", childRolesJson); + roleJson2.put("roleFunctions", roleFunctions); + ObjectMapper mapper = new ObjectMapper(); + JsonNode actualObj = mapper.readTree(roleJson2.toString()); + Mockito.when(mockedRequest.getInputStream()).thenReturn(new DelegatingServletInputStream( + new ByteArrayInputStream(actualObj.toString().getBytes(StandardCharsets.UTF_8)))); + Mockito.when(mockedRequest.getReader()).thenReturn(new BufferedReader(new StringReader(actualObj.toString()))); + Mockito.when(mockedRequest.getContentType()).thenReturn("application/json"); + Mockito.when(mockedRequest.getCharacterEncoding()).thenReturn("UTF-8"); + Mockito.when(externalAccessRolesService.ConvertCentralRoleToRole(Matchers.anyString())).thenReturn(new Role()); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, ""); + Mockito.when(externalAccessRolesService.saveRoleForApplication(Matchers.any(), Matchers.any())) + .thenReturn(externalRequestFieldsValidator); + CentralV2Role cenV2Role = new CentralV2Role(1l, "test1"); + cenV2Role.setActive(true); + Mockito.when(externalAccessRolesService.getRoleInfo(Matchers.anyLong(), Matchers.any())).thenReturn(cenV2Role); + Map<String, Object> actual = roleManageController.saveRole(mockedRequest, mockedResponse, CentralApp().getId()); + final Map<String, Object> expected = new HashMap<>(); + expected.put("status", "Success"); + assertEquals(expected.get("status"), actual.get("status")); + } - public CentralV2RoleFunction mockCentralRoleFunction() - { + @SuppressWarnings("unchecked") + @Test + public void saveRoleInvalidRoleExceptionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + JSONObject roleJson = new JSONObject(); + roleJson.put("id", 1); + roleJson.put("name", "test%%"); + roleJson.put("active", true); + JSONObject roleJson2 = new JSONObject(); + List<JSONObject> childRolesJson = new ArrayList<>(); + List<JSONObject> roleFunctions = new ArrayList<>(); + JSONObject roleFunction = new JSONObject(); + roleFunction.put("code", "test"); + roleFunction.put("name", "test"); + roleFunction.put("type", "test"); + roleFunction.put("action", "test"); + roleFunctions.add(roleFunction); + roleJson.put("roleFunctions", roleFunctions); + roleJson2.put("role", roleJson); + roleJson2.put("childRoles", childRolesJson); + roleJson2.put("roleFunctions", roleFunctions); + ObjectMapper mapper = new ObjectMapper(); + JsonNode actualObj = mapper.readTree(roleJson2.toString()); + Mockito.when(mockedRequest.getInputStream()).thenReturn(new DelegatingServletInputStream( + new ByteArrayInputStream(actualObj.toString().getBytes(StandardCharsets.UTF_8)))); + Mockito.when(mockedRequest.getReader()).thenReturn(new BufferedReader(new StringReader(actualObj.toString()))); + Mockito.when(mockedRequest.getContentType()).thenReturn("application/json"); + Mockito.when(mockedRequest.getCharacterEncoding()).thenReturn("UTF-8"); + Map<String, Object> actual = roleManageController.saveRole(mockedRequest, mockedResponse, CentralApp().getId()); + final Map<String, Object> expected = new HashMap<>(); + expected.put("error", "Invalid role name found for 'test%%'. Any one of the following characters '%,(),=,:,comma, and double quotes' are not allowed"); + assertEquals(expected.get("error"), actual.get("error")); + } + + @Test + public void saveRoleUnauthorizedUserExceptionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(false); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Map<String, Object> actual = roleManageController.saveRole(mockedRequest, mockedResponse, CentralApp().getId()); + final Map<String, Object> expected = new HashMap<>(); + expected.put("error", " Unauthorized user"); + assertEquals(expected.get("error"), actual.get("error")); + } + + @Test + public void toggleRoleTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + CentralV2Role role = new CentralV2Role(1l, "test"); + role.setActive(true); + Role currentRole = new Role(); + currentRole.setName("test"); + Mockito.when(externalAccessRolesService.getRoleInfo(Matchers.anyLong(), Matchers.any())).thenReturn(role); + Mockito.when(externalAccessRolesService.ConvertCentralRoleToRole(Matchers.anyString())).thenReturn(currentRole); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, ""); + Mockito.when(externalAccessRolesService.saveRoleForApplication(Matchers.any(),Matchers.any())).thenReturn(externalRequestFieldsValidator); + Map<String, Object> actual = roleManageController.toggleRole(mockedRequest, mockedResponse, CentralApp().getId(), 1l); + final Map<String, Object> expected = new HashMap<>(); + expected.put("restcallStatus", "Success"); + assertEquals(expected.get("restcallStatus"), actual.get("restcallStatus")); + } + + @Test + public void toggleRoleUnauthorizedUserExceptionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(false); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + Map<String, Object> actual = roleManageController.toggleRole(mockedRequest, mockedResponse, CentralApp().getId(), 1l); + final Map<String, Object> expected = new HashMap<>(); + expected.put("restcallStatus", " Unauthorized user"); + assertEquals(expected.get("restcallStatus"), actual.get("restcallStatus")); + } + + @Test(expected = NullPointerException.class) + public void toggleRoleExceptionTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.doThrow(new NullPointerException()).when(appService).getApp((long) 1); + roleManageController.toggleRole(mockedRequest, mockedResponse, CentralApp().getId(), 1l); + } + + @Test + public void toggleRoleFailedTest() throws Exception { + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + List<EPUser> epuserList = new ArrayList<>(); + List<EPApp> appList = new ArrayList<>(); + appList.add(CentralApp()); + EPUser user = mockUser.mockEPUser(); + epuserList.add(user); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + Mockito.when(appService.getApp((long) 1)).thenReturn(CentralApp()); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getApp(Matchers.anyString())).thenReturn(appList); + ResponseEntity<String> response = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(externalAccessRolesService.getNameSpaceIfExists(Matchers.anyObject())).thenReturn(response); + CentralV2Role role = new CentralV2Role(1l, "test"); + role.setActive(true); + Role currentRole = new Role(); + currentRole.setName("test"); + Mockito.when(externalAccessRolesService.getRoleInfo(Matchers.anyLong(), Matchers.any())).thenReturn(role); + Mockito.when(externalAccessRolesService.ConvertCentralRoleToRole(Matchers.anyString())).thenReturn(currentRole); + ExternalRequestFieldsValidator externalRequestFieldsValidator = new ExternalRequestFieldsValidator(false, ""); + Mockito.when(externalAccessRolesService.saveRoleForApplication(Matchers.any(),Matchers.any())).thenReturn(externalRequestFieldsValidator); + Map<String, Object> actual = roleManageController.toggleRole(mockedRequest, mockedResponse, CentralApp().getId(), 1l); + final Map<String, Object> expected = new HashMap<>(); + expected.put("restcallStatus", "Toggle Role Failed"); + assertEquals(expected.get("restcallStatus"), actual.get("restcallStatus")); + } + + @Test + public void getAvailableChildRolesTest() throws Exception { + List<CentralV2Role> centralV2Roles = new ArrayList<>(); + CentralV2Role centralV2Role = new CentralV2Role(); + centralV2Role.setName("test"); + centralV2Role.setId(1l); + CentralV2Role centralV2Role2 = new CentralV2Role(); + centralV2Role2.setName("test"); + centralV2Role2.setId(1l); + centralV2Roles.add(centralV2Role); + centralV2Roles.add(centralV2Role2); + SortedSet<CentralV2RoleFunction> roleFuns = new TreeSet<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction("test", "test"); + roleFuns.add(centralV2RoleFunction); + CentralV2Role currentRole = new CentralV2Role(); + currentRole.setName("test"); + currentRole.setId(1l); + currentRole.setRoleFunctions(roleFuns); + Mockito.when(externalAccessRolesService.getRolesForApp(CentralApp().getUebKey())).thenReturn(centralV2Roles); + Mockito.when(externalAccessRolesService.getRoleInfo(1l, CentralApp().getUebKey())).thenReturn(currentRole); + List<CentralV2Role> actual = roleManageController.getAvailableChildRoles(CentralApp().getUebKey(), 1l); + assertEquals(new ArrayList<>().size(), actual.size()); + } + + @Test + public void getCentralizedAppRolesTest() throws IOException { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<CentralizedApp> cenApps = new ArrayList<>(); + CentralizedApp centralizedApp = new CentralizedApp(); + centralizedApp.setAppId(1); + centralizedApp.setAppName("Test"); + cenApps.add(centralizedApp); + Mockito.when(adminRolesService.isSuperAdmin(Matchers.anyObject())).thenReturn(true); + Mockito.when(externalAccessRolesService.getCentralizedAppsOfUser(Matchers.anyString())).thenReturn(cenApps); + List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, user.getOrgUserId()); + assertEquals(cenApps.size(), actual.size()); + } + + @Test + public void getCentralizedAppRolesExceptionTest() throws IOException { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(EPUserUtils.getUserSession(mockedRequest)).thenReturn(user); + List<CentralizedApp> cenApps = new ArrayList<>(); + CentralizedApp centralizedApp = new CentralizedApp(); + centralizedApp.setAppId(1); + centralizedApp.setAppName("Test"); + cenApps.add(centralizedApp); + Mockito.when(adminRolesService.isAccountAdmin(Matchers.anyObject())).thenReturn(false); + List<CentralizedApp> actual = roleManageController.getCentralizedAppRoles(mockedRequest, mockedResponse, user.getOrgUserId()); + assertNull(actual); + } + + public CentralV2RoleFunction mockCentralRoleFunction() { CentralV2RoleFunction roleFunction = new CentralV2RoleFunction(); roleFunction.setCode("Test"); roleFunction.setName("Test"); roleFunction.setAppId((long) 1); return roleFunction; } - - public EPApp CentralApp() - { - EPApp app = mockApp(); + + public EPApp CentralApp() { + EPApp app = mockApp(); app.setCentralAuth(true); app.setNameSpace("com.test"); return app; } - - public EPApp NonCentralApp() - { - EPApp app = mockApp(); + + public EPApp NonCentralApp() { + EPApp app = mockApp(); app.setCentralAuth(false); return app; } + } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/UserControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/UserControllerTest.java index 205b2355..84db1496 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/UserControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/UserControllerTest.java @@ -135,7 +135,7 @@ public class UserControllerTest extends MockitoTestSuite { @Test public void modifyLoggedinUserExceptionTest() { - EPUser epUser = null; + EPUser epUser =null; PortalRestResponse<String> expectedResponse = new PortalRestResponse<String>(); expectedResponse.setMessage("java.lang.NullPointerException"); expectedResponse.setResponse(null); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsCatalogControllerTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsCatalogControllerTest.java index 50291f07..d8aba5fc 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsCatalogControllerTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/controller/WidgetsCatalogControllerTest.java @@ -37,6 +37,9 @@ */ package org.onap.portalapp.portal.controller; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + import java.util.ArrayList; import java.util.List; @@ -44,17 +47,23 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; +import org.mockito.Matchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.portalapp.portal.controller.WidgetsCatalogController; import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.MicroserviceParameter; import org.onap.portalapp.portal.domain.WidgetCatalog; +import org.onap.portalapp.portal.domain.WidgetCatalogParameter; +import org.onap.portalapp.portal.domain.WidgetParameterResult; import org.onap.portalapp.portal.domain.WidgetServiceHeaders; +import org.onap.portalapp.portal.ecomp.model.PortalRestResponse; +import org.onap.portalapp.portal.ecomp.model.PortalRestStatusEnum; import org.onap.portalapp.portal.framework.MockitoTestSuite; import org.onap.portalapp.portal.service.ConsulHealthService; import org.onap.portalapp.portal.service.ConsulHealthServiceImpl; @@ -65,29 +74,38 @@ import org.onap.portalapp.portal.service.WidgetParameterServiceImpl; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalsdk.core.onboarding.exception.CipherUtilException; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; import org.onap.portalsdk.core.util.SystemProperties; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.mock.web.MockMultipartHttpServletRequest; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; - -@Ignore +@SuppressWarnings("rawtypes") @RunWith(PowerMockRunner.class) -@PrepareForTest({EPUserUtils.class, EcompPortalUtils.class, SystemProperties.class, EPCommonSystemProperties.class}) +@PrepareForTest({ EPUserUtils.class, CipherUtil.class, EcompPortalUtils.class, SystemProperties.class, + EPCommonSystemProperties.class, EPUserUtils.class }) public class WidgetsCatalogControllerTest { @Mock ConsulHealthService consulHealthService = new ConsulHealthServiceImpl(); - + @Mock MicroserviceService microserviceService = new MicroserviceServiceImpl(); - + @Mock WidgetParameterService widgetParameterService = new WidgetParameterServiceImpl(); - + @InjectMocks WidgetsCatalogController widgetsCatalogController = new WidgetsCatalogController(); @@ -95,10 +113,10 @@ public class WidgetsCatalogControllerTest { public void setup() { MockitoAnnotations.initMocks(this); } + @Mock - WidgetServiceHeaders widgetServiceHeaders ; - - + WidgetServiceHeaders widgetServiceHeaders; + @Mock RestTemplate template = new RestTemplate(); @@ -108,32 +126,380 @@ public class WidgetsCatalogControllerTest { HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); NullPointerException nullPointerException = new NullPointerException(); - + MockEPUser mockUser = new MockEPUser(); - - @Mock - HttpEntity mockHttpEntity; - + + @Test + public void getUserWidgetCatalogTest() throws RestClientException, Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + List<WidgetCatalog> widgetsList = new ArrayList<>(); + WidgetCatalog widgetCatalog = new WidgetCatalog(); + widgetCatalog.setId(1l); + widgetCatalog.setName("test"); + widgetsList.add(widgetCatalog); + ResponseEntity<List> ans = new ResponseEntity<>(widgetsList, HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.eq(List.class))).thenReturn(ans); + List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getUserWidgetCatalog("guestT"); + assertEquals(expectedWidgets, widgetsList); + } + + @Test + public void getUserWidgetCatalogExceptionTest() throws RestClientException, Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.doThrow(new NullPointerException()).when(template).exchange(Matchers.anyString(), + Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), Matchers.eq(List.class)); + List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getUserWidgetCatalog("guestT"); + assertNull(expectedWidgets); + } + + @Test + public void getWidgetCatalogTest() throws CipherUtilException { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + List<WidgetCatalog> widgetsList = new ArrayList<>(); + WidgetCatalog widgetCatalog = new WidgetCatalog(); + widgetCatalog.setId(1l); + widgetCatalog.setName("test"); + widgetsList.add(widgetCatalog); + ResponseEntity<List> ans = new ResponseEntity<>(widgetsList, HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.eq(List.class))).thenReturn(ans); + List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getWidgetCatalog(); + assertEquals(expectedWidgets, widgetsList); + } + + @Test + public void getWidgetCatalogExceptionTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.doThrow(new NullPointerException()).when(template).exchange(Matchers.anyString(), + Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), Matchers.eq(List.class)); + List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getUserWidgetCatalog("guestT"); + assertNull(expectedWidgets); + } + + @Test + public void updateWidgetCatalogTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + ResponseEntity<List> ans = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), Matchers.<HttpEntity<?>>any(), + Matchers.eq(List.class))).thenReturn(ans); + WidgetCatalog widget = new WidgetCatalog(); + widget.setId(1l); + widgetsCatalogController.updateWidgetCatalog(widget, 1); + } + + @Test + public void deleteOnboardingWidgetTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + ResponseEntity<List> ans = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<?>>any(), Matchers.eq(List.class))).thenReturn(ans); + widgetsCatalogController.deleteOnboardingWidget(1l); + } + + @SuppressWarnings("unchecked") + @Test + public void updateWidgetCatalogWithFilesTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + String ans = "success"; + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.postForObject(Mockito.any(String.class), Mockito.any(HttpEntity.class), + Mockito.any(Class.class))).thenReturn(ans); + MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); + byte[] mockData = "test".getBytes(); + String originalFilename = "Test_File.zip"; + MockMultipartFile mockMultipartFile = new MockMultipartFile("file", originalFilename, "application/zip", + mockData); + request.addFile(mockMultipartFile); + String actual = widgetsCatalogController.updateWidgetCatalogWithFiles(request, 1l); + assertEquals(ans, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void createWidgetCatalogTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + String ans = "success"; + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.postForObject(Mockito.any(String.class), Mockito.any(HttpEntity.class), + Mockito.any(Class.class))).thenReturn(ans); + MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest(); + byte[] mockData = "test".getBytes(); + String originalFilename = "Test_File.zip"; + MockMultipartFile mockMultipartFile = new MockMultipartFile("file", originalFilename, "application/zip", + mockData); + request.addFile(mockMultipartFile); + String actual = widgetsCatalogController.createWidgetCatalog(request); + assertEquals(ans, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void getWidgetFrameworkTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.getForObject(Mockito.anyString(), Mockito.any(Class.class), Mockito.any(String.class))) + .thenReturn("test123"); + String result = widgetsCatalogController.getWidgetFramework(1l); + assertNull(result); + } + + @SuppressWarnings("unchecked") + @Test + public void getWidgetControllerTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.getForObject(Mockito.anyString(), Mockito.any(Class.class), Mockito.any(String.class))) + .thenReturn("test123"); + String result = widgetsCatalogController.getWidgetController(1); + assertNull(result); + } + + @SuppressWarnings("unchecked") + @Test + public void getWidgetCSSTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.getForObject(Mockito.anyString(), Mockito.any(Class.class), Mockito.any(String.class))) + .thenReturn("test123"); + String result = widgetsCatalogController.getWidgetCSS(1); + assertNull(result); + } + + @Test + public void getWidgetParameterResultTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + MockHttpServletRequest request = new MockHttpServletRequest(); + Mockito.when(EPUserUtils.getUserSession(request)).thenReturn(user); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + ResponseEntity<Long> ans = new ResponseEntity<>(1l, HttpStatus.OK); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.eq(Long.class))).thenReturn(ans); + List<MicroserviceParameter> defaultParam = new ArrayList<>(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + MicroserviceParameter microserviceParameter2 = new MicroserviceParameter(); + microserviceParameter2.setId(2l); + microserviceParameter2.setPara_key("test2"); + defaultParam.add(microserviceParameter); + defaultParam.add(microserviceParameter2); + Mockito.when(microserviceService.getParametersById(1)).thenReturn(defaultParam); + Mockito.when(widgetParameterService.getUserParamById(1l, user.getId(), 1l)).thenReturn(null); + WidgetCatalogParameter userValue = new WidgetCatalogParameter(); + userValue.setUser_value("test123"); + Mockito.when(widgetParameterService.getUserParamById(1l, user.getId(), 2l)).thenReturn(userValue); + PortalRestResponse<List<WidgetParameterResult>> actual = widgetsCatalogController + .getWidgetParameterResult(request, 1); + PortalRestResponse<List<WidgetParameterResult>> expected = new PortalRestResponse<List<WidgetParameterResult>>( + PortalRestStatusEnum.OK, "SUCCESS", new ArrayList<>()); + assertEquals(expected.getStatus(), actual.getStatus()); + } + @SuppressWarnings("unchecked") @Test - public void getUserWidgetCatalogTest() throws RestClientException, Exception{ - - String resourceType = null; - List<WidgetCatalog> widgets = new ArrayList<>(); - PowerMockito.mockStatic(EcompPortalUtils.class); - PowerMockito.mockStatic(SystemProperties.class); - PowerMockito.mockStatic(EPCommonSystemProperties.class); - Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); - Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); -// Mockito.when(WidgetServiceHeaders.getInstance()).thenReturn(HttpHeaders.ACCEPT); - Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); - Mockito.when(consulHealthService.getServiceLocation("widgets-service", - "test")).thenReturn("test.com"); - Mockito.when(new HttpEntity(WidgetServiceHeaders.getInstance())).thenReturn(mockHttpEntity); -// HttpEntity<String> entity = new HttpEntity<String>("helloWorld"); -// ResponseEntity<ArrayList> ans = new ResponseEntity<>(statusCode); -// Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), -// Matchers.<HttpEntity<?>>any(), Matchers.eq(ArrayList.class))).thenReturn(ans); -// List<WidgetCatalog> expectedWidgets = widgetsCatalogController.getUserWidgetCatalog(mockedRequest, mockedResponse, "guestT"); + public void doDownloadTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + Mockito.when(EcompPortalUtils.widgetMsProtocol()).thenReturn("test1"); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.WIDGET_MS_PROTOCOL)).thenReturn("https"); + Mockito.when(SystemProperties.getProperty("microservices.widget.local.port")).thenReturn("test"); + Mockito.when(EcompPortalUtils.getPropertyOrDefault("microservices.widget.username", "widget_user")) + .thenReturn("test"); + Mockito.when(CipherUtil + .decryptPKC(EcompPortalUtils.getPropertyOrDefault("microservices.widget.password", "widget_password"))) + .thenReturn("abc"); + Mockito.when(consulHealthService.getServiceLocation("widgets-service", "test")).thenReturn("test.com"); + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + ResponseEntity<byte[]> mockData = new ResponseEntity("testfile.zip".getBytes(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), Matchers.<HttpEntity<?>>any(), + Matchers.eq(byte[].class))).thenReturn(mockData); + widgetsCatalogController.doDownload(request, response, 1l); + } + + @Test + public void saveWidgetParameterTest() { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + WidgetCatalogParameter widgetCatalogParameter = new WidgetCatalogParameter(); + widgetCatalogParameter.setId(1l); + widgetCatalogParameter.setParamId(1l); + widgetCatalogParameter.setUserId(user.getId()); + widgetCatalogParameter.setUser_value("test123"); + MockHttpServletRequest request = new MockHttpServletRequest(); + Mockito.when(EPUserUtils.getUserSession(request)).thenReturn(user); + Mockito.when(widgetParameterService.getUserParamById(widgetCatalogParameter.getWidgetId(), + widgetCatalogParameter.getUserId(), widgetCatalogParameter.getParamId())).thenReturn(widgetCatalogParameter); + PortalRestResponse<String> response = widgetsCatalogController.saveWidgetParameter(request, + widgetCatalogParameter); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.OK, "SUCCESS", ""); + assertEquals(expected.getMessage(), response.getMessage()); + } + + @Test + public void saveWidgetParameterExceptionTest() { + PowerMockito.mockStatic(EPUserUtils.class); + EPUser user = mockUser.mockEPUser(); + WidgetCatalogParameter widgetCatalogParameter = new WidgetCatalogParameter(); + widgetCatalogParameter.setId(1l); + widgetCatalogParameter.setParamId(1l); + widgetCatalogParameter.setUserId(user.getId()); + widgetCatalogParameter.setUser_value("test123"); + MockHttpServletRequest request = new MockHttpServletRequest(); + Mockito.when(EPUserUtils.getUserSession(request)).thenReturn(user); + Mockito.doThrow(new NullPointerException()).when(widgetParameterService).getUserParamById(widgetCatalogParameter.getWidgetId(), + widgetCatalogParameter.getUserId(), widgetCatalogParameter.getParamId()); + PortalRestResponse<String> response = widgetsCatalogController.saveWidgetParameter(request, + widgetCatalogParameter); + PortalRestResponse<String> expected = new PortalRestResponse<String>(PortalRestStatusEnum.ERROR, "FAILURE", ""); + assertEquals(expected.getMessage(), response.getMessage()); } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/PopulateSampleTestData.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/PopulateSampleTestData.java index e3eeaa54..3a7d4f39 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/PopulateSampleTestData.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/PopulateSampleTestData.java @@ -36,7 +36,7 @@ package org.onap.portalapp.portal.core; * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -//package org.openecomp.portalapp.portal.core; +//package org.onap.portalapp.portal.core; // //import java.sql.Connection; //import java.sql.SQLException; @@ -45,7 +45,7 @@ package org.onap.portalapp.portal.core; // //import org.junit.Before; //import org.junit.Test; -//import org.openecomp.portalapp.framework.ApplicationCommonContextTestSuite; +//import org.onap.portalapp.framework.ApplicationCommonContextTestSuite; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.core.io.ClassPathResource; //import org.springframework.jdbc.datasource.DataSourceUtils; diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RemoveSampleTestData.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RemoveSampleTestData.java index 1fa6c7d1..2aedae69 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RemoveSampleTestData.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RemoveSampleTestData.java @@ -36,7 +36,7 @@ package org.onap.portalapp.portal.core; * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -//package org.openecomp.portalapp.portal.core; +//package org.onap.portalapp.portal.core; // //import java.sql.Connection; //import java.sql.SQLException; @@ -45,7 +45,7 @@ package org.onap.portalapp.portal.core; // //import org.junit.After; //import org.junit.Test; -//import org.openecomp.portalapp.framework.ApplicationCommonContextTestSuite; +//import org.onap.portalapp.framework.ApplicationCommonContextTestSuite; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.core.io.ClassPathResource; //import org.springframework.jdbc.datasource.DataSourceUtils; diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RestURLsTestSuite.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RestURLsTestSuite.java index 8bb21812..9c93790a 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RestURLsTestSuite.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/core/RestURLsTestSuite.java @@ -36,7 +36,7 @@ package org.onap.portalapp.portal.core; * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -//package org.openecomp.portalapp.portal.core; +//package org.onap.portalapp.portal.core; // //import static org.junit.Assert.assertEquals; //import static org.junit.Assert.assertTrue; @@ -47,12 +47,12 @@ package org.onap.portalapp.portal.core; // //import org.junit.Assert; //import org.junit.Test; -//import org.openecomp.portalapp.framework.ApplicationCommonContextTestSuite; -//import org.openecomp.portalapp.portal.domain.EPUser; -//import org.openecomp.portalapp.portal.test.core.MockEPUser; -//import org.openecomp.portalapp.portal.transport.AppNameIdIsAdmin; -//import org.openecomp.portalapp.portal.transport.AppsListWithAdminRole; -//import org.openecomp.portalsdk.core.util.SystemProperties; +//import org.onap.portalapp.framework.ApplicationCommonContextTestSuite; +//import org.onap.portalapp.portal.domain.EPUser; +//import org.onap.portalapp.portal.test.core.MockEPUser; +//import org.onap.portalapp.portal.transport.AppNameIdIsAdmin; +//import org.onap.portalapp.portal.transport.AppsListWithAdminRole; +//import org.onap.portalsdk.core.util.SystemProperties; //import org.springframework.http.MediaType; //import org.springframework.test.web.servlet.ResultActions; //import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java index 2923eb2b..0b6a7e13 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPUserAppsManualSortPreferenceTest.java @@ -46,7 +46,7 @@ public class EPUserAppsManualSortPreferenceTest { public EPUserAppsManualSortPreference mockEPUserAppsManualSortPreference(){ EPUserAppsManualSortPreference epUserAppsManualSortPreference = new EPUserAppsManualSortPreference(); - epUserAppsManualSortPreference.setUserId(1); + epUserAppsManualSortPreference.setUserId(1l); epUserAppsManualSortPreference.setAppId((long)1); epUserAppsManualSortPreference.setAppManualSortOrder(1); @@ -58,7 +58,7 @@ public class EPUserAppsManualSortPreferenceTest { EPUserAppsManualSortPreference epUserAppsManualSortPreference = mockEPUserAppsManualSortPreference(); - assertEquals(epUserAppsManualSortPreference.getUserId(), 1); + assertEquals(epUserAppsManualSortPreference.getUserId(), new Long(1)); assertEquals(epUserAppsManualSortPreference.getAppId(), new Long(1)); assertEquals(epUserAppsManualSortPreference.getAppManualSortOrder(), 1); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java index b4b4780d..5dbca6eb 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/domain/EPWidgetsManualSortPreferenceTest.java @@ -47,7 +47,7 @@ public class EPWidgetsManualSortPreferenceTest { public EPWidgetsManualSortPreference mockEPWidgetsManualSortPreference(){ EPWidgetsManualSortPreference epWidgetsManualSortPreference = new EPWidgetsManualSortPreference(); - epWidgetsManualSortPreference.setUserId(1); + epWidgetsManualSortPreference.setUserId(1l); epWidgetsManualSortPreference.setWidgetId((long)1); epWidgetsManualSortPreference.setWidgetRow(1); epWidgetsManualSortPreference.setWidgetCol(1); @@ -62,7 +62,7 @@ public class EPWidgetsManualSortPreferenceTest { EPWidgetsManualSortPreference epWidgetsManualSortPreference = mockEPWidgetsManualSortPreference(); assertEquals(epWidgetsManualSortPreference.getWidgetId(), new Long(1)); - assertEquals(epWidgetsManualSortPreference.getUserId(), 1); + assertEquals(epWidgetsManualSortPreference.getUserId(), new Long(1)); assertEquals(epWidgetsManualSortPreference.getWidgetRow(), 1); assertEquals(epWidgetsManualSortPreference.getWidgetCol(), 1); assertEquals(epWidgetsManualSortPreference.getWidgetHeight(), 1); diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/framework/ApplicationCommonContextTestSuite.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/framework/ApplicationCommonContextTestSuite.java index 764cebab..96c41729 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/framework/ApplicationCommonContextTestSuite.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/framework/ApplicationCommonContextTestSuite.java @@ -36,20 +36,20 @@ package org.onap.portalapp.portal.framework; * * ECOMP is a trademark and service mark of AT&T Intellectual Property. */ -//package org.openecomp.portalapp.portal.framework; +//package org.onap.portalapp.portal.framework; // //import java.io.IOException; // //import org.junit.Before; //import org.junit.runner.RunWith; -//import org.openecomp.portalsdk.core.conf.AppConfig; -////import org.openecomp.portalapp.conf.ExternalAppConfig; -////import org.openecomp.portalapp.conf.HibernateMappingLocations; -//import org.openecomp.portalsdk.core.conf.HibernateConfiguration; -//import org.openecomp.portalsdk.core.conf.HibernateMappingLocatable; -//import org.openecomp.portalsdk.core.objectcache.AbstractCacheManager; -//import org.openecomp.portalsdk.core.util.CacheManager; -//import org.openecomp.portalsdk.core.util.SystemProperties; +//import org.onap.portalsdk.core.conf.AppConfig; +////import org.onap.portalapp.conf.ExternalAppConfig; +////import org.onap.portalapp.conf.HibernateMappingLocations; +//import org.onap.portalsdk.core.conf.HibernateConfiguration; +//import org.onap.portalsdk.core.conf.HibernateMappingLocatable; +//import org.onap.portalsdk.core.objectcache.AbstractCacheManager; +//import org.onap.portalsdk.core.util.CacheManager; +//import org.onap.portalsdk.core.util.SystemProperties; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.ComponentScan; @@ -118,14 +118,14 @@ package org.onap.portalapp.portal.framework; //} // //@Configuration -//@ComponentScan(basePackages = "org.openecomp", excludeFilters = { +//@ComponentScan(basePackages = "org.onap", excludeFilters = { // // the following source configurations should not be scanned; instead of // // using Exclusion filter, we can use the @Profile annotation to exclude // // them -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.portalsdk.core.controller.LogoutController*"), -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.portalsdk.core.controller.SDKLoginController*"), -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.portalapp.conf.ExternalAppConfig*"), -// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.openecomp.*.*InitUebHandler*") }) +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.portalsdk.core.controller.LogoutController*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.portalsdk.core.controller.SDKLoginController*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.portalapp.conf.ExternalAppConfig*"), +// @ComponentScan.Filter(type = FilterType.REGEX, pattern = "org.onap.*.*InitUebHandler*") }) //@Profile("test") //class MockAppConfig extends AppConfig { // @@ -185,7 +185,7 @@ package org.onap.portalapp.portal.framework; // } // // public String[] getPackagesToScan() { -// return new String[] { "org.openecomp", "src" }; +// return new String[] { "org.onap", "src" }; // } // //} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdviceTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdviceTest.java new file mode 100644 index 00000000..5f8319cf --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/logging/aop/EPEELFLoggerAdviceTest.java @@ -0,0 +1,158 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.logging.aop; + +import static org.junit.Assert.assertNotEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.util.SystemProperties.SecurityEventTypeEnum; +import org.onap.portalsdk.core.web.support.AppUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpSession; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, SystemProperties.class, + EPCommonSystemProperties.class }) +public class EPEELFLoggerAdviceTest { + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Mock + SecurityEventTypeEnum securityEventTypeEnum; + + @InjectMocks + EPEELFLoggerAdvice epEELFLoggerAdvice = new EPEELFLoggerAdvice(); + + @Test + @SuppressWarnings("static-access") + public void getCurrentDateTimeUTCTest(){ + String actual = epEELFLoggerAdvice.getCurrentDateTimeUTC(); + assertNotEquals("", actual); + } + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void loadServletRequestBasedDefaultsTest(){ + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + MockHttpSession session = new MockHttpSession(); + session.setAttribute("user_attribute_name", user); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServletPath("http:test.com"); + request.setSession(session); + request.addHeader("user-agent", "Mozilla/5.0"); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("user_attribute_name"); + epEELFLoggerAdvice.loadServletRequestBasedDefaults(request, securityEventTypeEnum); + } + + @Test + public void afterTest(){ + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + MockHttpSession session = new MockHttpSession(); + session.setAttribute("user_attribute_name", user); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServletPath("http:test.com"); + request.setSession(session); + request.addHeader("user-agent", "Mozilla/5.0"); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("user_attribute_name"); + List<Object> args = new ArrayList<>(); + args.add("testClassName"); + args.add("testMethodName"); + Object[] passOnArgs = args.toArray(new Object[args.size()]); + List<Object> args2 = new ArrayList<>(); + args2.add(request); + Object[] httpArgs = args2.toArray(new Object[args2.size()]); + epEELFLoggerAdvice.after(securityEventTypeEnum, "200", "200", httpArgs, null, passOnArgs); + } + + @Test + public void BeforeTest(){ + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + MockHttpSession session = new MockHttpSession(); + session.setAttribute("user_attribute_name", user); + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setServletPath("http:test.com"); + request.setSession(session); + request.addHeader("user-agent", "Mozilla/5.0"); + Mockito.when(SystemProperties.getProperty(SystemProperties.USER_ATTRIBUTE_NAME)).thenReturn("user_attribute_name"); + List<Object> args = new ArrayList<>(); + args.add("testClassName"); + args.add("testMethodName"); + Object[] passOnArgs = args.toArray(new Object[args.size()]); + List<Object> args2 = new ArrayList<>(); + args2.add(request); + Object[] httpArgs = args2.toArray(new Object[args2.size()]); + epEELFLoggerAdvice.before(securityEventTypeEnum, httpArgs, passOnArgs); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java new file mode 100644 index 00000000..d9beb4d1 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/AdminRolesServiceImplTest.java @@ -0,0 +1,435 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedSet; + +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.json.simple.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPRole; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserApp; +import org.onap.portalapp.portal.domain.UserRole; +import org.onap.portalapp.portal.transport.AppNameIdIsAdmin; +import org.onap.portalapp.portal.transport.AppsListWithAdminRole; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, PortalConstants.class, SystemProperties.class, + EPCommonSystemProperties.class }) +public class AdminRolesServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @Mock + RestTemplate template = new RestTemplate(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @After + public void after() { + session.close(); + } + + @InjectMocks + AdminRolesServiceImpl adminRolesServiceImpl = new AdminRolesServiceImpl(); + + private Long ACCOUNT_ADMIN_ROLE_ID = 999L; + + private Long ECOMP_APP_ID = 1L; + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("deprecation") + @Test + public void getAppsWithAdminRoleStateForUserTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + app.setId(1l); + List<EPUser> users = new ArrayList<>(); + users.add(user); + Map<String, String> userParams = new HashMap<>(); + userParams.put("org_user_id", user.getOrgUserId()); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null)).thenReturn(users); + List<EPUserApp> userAppList = new ArrayList<>(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(1l); + role.setName("test role"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + userAppList.add(epUserApp); + Mockito.when(dataAccessService.getList(EPUserApp.class, + " where userId = " + user.getId() + " and role.id = " + 999, null, null)).thenReturn(userAppList); + List<EPApp> appsList = new ArrayList<>(); + appsList.add(app); + Mockito.when(dataAccessService.getList(EPApp.class, + " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", null, null)).thenReturn(appsList); + AppsListWithAdminRole actual = adminRolesServiceImpl.getAppsWithAdminRoleStateForUser(user.getOrgUserId()); + assertNotNull(actual); + } + + @SuppressWarnings({ "deprecation", "unchecked" }) + @Test + public void setAppsWithAdminRoleStateForUserTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + app.setId(1l); + EPApp app2 = mockApp(); + app2.setName("app2"); + app2.setNameSpace("com.test.app2"); + app2.setId(2l); + EPApp app3 = mockApp(); + app3.setName("app3"); + app3.setNameSpace("com.test.app3"); + app3.setId(3l); + List<EPApp> apps = new ArrayList<>(); + apps.add(app); + apps.add(app2); + apps.add(app3); + Mockito.when(epAppCommonServiceImpl.getAppsFullList()).thenReturn(apps); + + List<EPUser> localUserList = new ArrayList<>(); + localUserList.add(user); + Mockito.when( + dataAccessService.getList(EPUser.class, " where org_user_id='" + user.getOrgUserId() + "'", null, null)) + .thenReturn(localUserList); + List<EPUserApp> oldAppsWhereUserIsAdmin = new ArrayList<EPUserApp>(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(999l); + role.setName("app5"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + oldAppsWhereUserIsAdmin.add(epUserApp); + Mockito.when(dataAccessService.getList(EPUserApp.class, + " where userId = " + user.getId() + " and role.id = " + ACCOUNT_ADMIN_ROLE_ID, null, + null)).thenReturn(oldAppsWhereUserIsAdmin); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + EPApp app4 = mockApp(); + app4.setId(6l); + app4.setName("app7"); + app4.setNameSpace("com.test.app7"); + List<EPApp> apps2 = new ArrayList<>(); + apps2.add(app); + apps2.add(app2); + apps2.add(app3); + apps2.add(app4); + Mockito.when(dataAccessService.executeNamedQuery("getCentralizedApps", null, null)).thenReturn(apps2); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + JSONObject getUserRoles = new JSONObject(); + ResponseEntity<String> getResponse = new ResponseEntity<>(getUserRoles.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + + AppsListWithAdminRole newAppsListWithAdminRoles = new AppsListWithAdminRole(); + ArrayList<AppNameIdIsAdmin> appsRoles = new ArrayList<>(); + AppNameIdIsAdmin appNameIdIsAdmin = new AppNameIdIsAdmin(); + appNameIdIsAdmin.setAppName("app1"); + appNameIdIsAdmin.setId(2l); + appNameIdIsAdmin.setIsAdmin(true); + appNameIdIsAdmin.setRestrictedApp(false); + AppNameIdIsAdmin appNameIdIsAdmin2 = new AppNameIdIsAdmin(); + appNameIdIsAdmin2.setAppName("app2"); + appNameIdIsAdmin2.setId(3l); + appNameIdIsAdmin2.setIsAdmin(true); + appNameIdIsAdmin2.setRestrictedApp(false); + appsRoles.add(appNameIdIsAdmin); + appsRoles.add(appNameIdIsAdmin2); + newAppsListWithAdminRoles.setOrgUserId(user.getOrgUserId()); + newAppsListWithAdminRoles.setAppsRoles(appsRoles); + Mockito.when((EPApp) session.get(EPApp.class, appNameIdIsAdmin.id)).thenReturn(app2); + Mockito.when((EPApp) session.get(EPApp.class, appNameIdIsAdmin2.id)).thenReturn(app3); + JSONObject getUserRoles2 = new JSONObject(); + JSONObject getUserRoles3 = new JSONObject(); + JSONObject getUserRoles4 = new JSONObject(); + JSONObject finalUserRoles = new JSONObject(); + getUserRoles2.put("role", "com.test.app3.Account_Administrator"); + getUserRoles3.put("role", "com.test.app3.admin"); + getUserRoles4.put("role", "com.test.app3.owner"); + List<JSONObject> userRoles = new ArrayList<>(); + userRoles.add(getUserRoles2); + userRoles.add(getUserRoles3); + userRoles.add(getUserRoles4); + finalUserRoles.put("userRole", userRoles); + ResponseEntity<String> getResponse2 = new ResponseEntity<>(finalUserRoles.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse2); + boolean actual = adminRolesServiceImpl.setAppsWithAdminRoleStateForUser(newAppsListWithAdminRoles); + assertTrue(actual); + } + + @Test + public void isSuperAdminTest() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + List<UserRole> userRoleList = new ArrayList<>(); + UserRole userRole = new UserRole(); + userRole.setFirstName("Hello"); + userRole.setLastName("World"); + userRole.setRoleId(1l); + userRole.setRoleName("test"); + userRole.setUser_Id(1l); + userRoleList.add(userRole); + Mockito.when(dataAccessService.executeSQLQuery(Matchers.anyString(), Matchers.any(), Matchers.anyMap())) + .thenReturn(userRoleList); + boolean actual = adminRolesServiceImpl.isSuperAdmin(user); + assertTrue(actual); + } + + @Test + public void isSuperAdminExceptionTest() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeSQLQuery(Matchers.anyString(), + Matchers.any(), Matchers.anyMap()); + boolean actual = adminRolesServiceImpl.isSuperAdmin(user); + assertFalse(actual); + } + + @Test + public void isAccountAdminTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + app.setId(2l); + SortedSet<EPUserApp> userApps = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(999l); + role.setName("test role"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + userApps.add(epUserApp); + user.setUserApps(userApps); + Mockito.when((EPUser) dataAccessService.getDomainObject(Matchers.any(), Matchers.anyLong(), Matchers.anyMap())) + .thenReturn(user); + boolean actual = adminRolesServiceImpl.isAccountAdmin(user); + assertTrue(actual); + } + + @Test + public void isAccountAdminExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).getDomainObject(Matchers.any(), + Matchers.anyLong(), Matchers.anyMap()); + boolean actual = adminRolesServiceImpl.isAccountAdmin(user); + assertFalse(actual); + } + + @Test + public void isUserTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + app.setId(2l); + SortedSet<EPUserApp> userApps = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(2l); + role.setName("test role"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + userApps.add(epUserApp); + user.setUserApps(userApps); + Mockito.when((EPUser) dataAccessService.getDomainObject(Matchers.any(), Matchers.anyLong(), Matchers.anyMap())) + .thenReturn(user); + boolean actual = adminRolesServiceImpl.isUser(user); + assertTrue(actual); + } + + @Test + public void isUserExceptionTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).getDomainObject(Matchers.any(), + Matchers.anyLong(), Matchers.anyMap()); + boolean actual = adminRolesServiceImpl.isUser(user); + assertFalse(actual); + } + + @Test + public void getRolesByAppTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + List<EPRole> expected = new ArrayList<>(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(1l); + role.setName("test role"); + expected.add(role); + Mockito.when(dataAccessService.executeSQLQuery(Matchers.anyString(), Matchers.any(), Matchers.anyMap())) + .thenReturn(expected); + List<EPRole> actual = adminRolesServiceImpl.getRolesByApp(user, app.getId()); + assertEquals(expected, actual); + } + + @Test + public void isAccountAdminOfApplicationTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + SortedSet<EPUserApp> userApps = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole role = new EPRole(); + role.setActive(true); + role.setId(999l); + role.setName("test role"); + epUserApp.setApp(app); + epUserApp.setRole(role); + epUserApp.setUserId(1l); + userApps.add(epUserApp); + user.setUserApps(userApps); + Mockito.when((EPUser) dataAccessService.getDomainObject(Matchers.any(), Matchers.anyLong(), Matchers.anyMap())) + .thenReturn(user); + boolean actual = adminRolesServiceImpl.isAccountAdminOfApplication(user, app); + assertTrue(actual); + } + + @Test + public void isAccountAdminOfApplicationExceptionTest() { + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).getDomainObject(Matchers.any(), + Matchers.anyLong(), Matchers.anyMap()); + boolean actual = adminRolesServiceImpl.isAccountAdminOfApplication(user, app); + assertFalse(actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java new file mode 100644 index 00000000..3bfd7ec4 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPAppCommonServiceImplTest.java @@ -0,0 +1,815 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.AppIdAndNameTransportModel; +import org.onap.portalapp.portal.domain.AppsResponse; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserAppsManualSortPreference; +import org.onap.portalapp.portal.domain.EPUserAppsSortPreference; +import org.onap.portalapp.portal.domain.EPWidgetsManualSortPreference; +import org.onap.portalapp.portal.domain.EcompApp; +import org.onap.portalapp.portal.domain.UserRole; +import org.onap.portalapp.portal.domain.UserRoles; +import org.onap.portalapp.portal.transport.EPAppsSortPreference; +import org.onap.portalapp.portal.transport.EPDeleteAppsManualSortPref; +import org.onap.portalapp.portal.transport.EPWidgetsSortPreference; +import org.onap.portalapp.portal.transport.FieldsValidator; +import org.onap.portalapp.portal.transport.FunctionalMenuItem; +import org.onap.portalapp.portal.transport.LocalRole; +import org.onap.portalapp.portal.transport.OnboardingApp; +import org.onap.portalapp.portal.ueb.EPUebHelper; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.apiClient.credentials.ApiCredential; +import com.att.nsa.cambria.client.CambriaClientBuilders; +import com.att.nsa.cambria.client.CambriaIdentityManager; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({ "org.apache.http.conn.ssl.*", "javax.net.ssl.*", "javax.crypto.*" }) +@PrepareForTest({ EcompPortalUtils.class, PortalApiProperties.class, PortalApiConstants.class, SystemProperties.class, + PortalConstants.class, EPCommonSystemProperties.class }) +public class EPAppCommonServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + AdminRolesServiceImpl adminRolesServiceImpl = new AdminRolesServiceImpl(); + + @Mock + EPUebHelper epUebHelper; + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + MockEPUser mockUser = new MockEPUser(); + + String ECOMP_APP_ID = "1"; + String SUPER_ADMIN_ROLE_ID = "1"; + String ACCOUNT_ADMIN_ROLE_ID = "999"; + String RESTRICTED_APP_ROLE_ID = "900"; + + @InjectMocks + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(false); + app.setCentralAuth(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + @Test + public void getUserAsAdminAppsTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> expected = new ArrayList<>(); + expected.add(mockApp); + expected.add(mockApp2); + String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where " + + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + Mockito.when(dataAccessService.executeSQLQuery(sql, EPApp.class, null)).thenReturn(expected); + Mockito.when(adminRolesServiceImpl.isAccountAdmin(user)).thenReturn(true); + List<EPApp> actual = epAppCommonServiceImpl.getUserAsAdminApps(user); + assertEquals(expected, actual); + } + + @Test + public void getUserAsAdminAppsTestException() { + EPUser user = mockUser.mockEPUser(); + String sql = "SELECT * FROM FN_APP join FN_USER_ROLE ON FN_USER_ROLE.APP_ID=FN_APP.APP_ID where " + + "FN_USER_ROLE.USER_ID=" + user.getId() + " AND FN_USER_ROLE.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeSQLQuery(sql, EPApp.class, null); + Mockito.when(adminRolesServiceImpl.isAccountAdmin(user)).thenReturn(true); + List<EPApp> actual = epAppCommonServiceImpl.getUserAsAdminApps(user); + assertNull(actual); + } + + @Test + public void getUserByOrgUserIdAsAdminAppsTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> expected = new ArrayList<>(); + expected.add(mockApp); + expected.add(mockApp2); + String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID " + + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + String sql = String.format(format, user.getOrgUserId()); + Mockito.when(dataAccessService.executeSQLQuery(sql, EPApp.class, null)).thenReturn(expected); + List<EPApp> actual = epAppCommonServiceImpl.getUserByOrgUserIdAsAdminApps(user.getOrgUserId()); + assertEquals(expected, actual); + } + + @Test + public void getUserByOrgUserIdAsAdminAppsTestException() { + EPUser user = mockUser.mockEPUser(); + String format = "SELECT * FROM FN_APP app INNER JOIN FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "INNER JOIN FN_USER user on user.USER_ID = userrole.USER_ID " + + "WHERE user.org_user_id = '%s' AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND FN_APP.ENABLED = 'Y'"; + String sql = String.format(format, user.getOrgUserId()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeSQLQuery(sql, EPApp.class, null); + List<EPApp> actual = epAppCommonServiceImpl.getUserByOrgUserIdAsAdminApps(user.getOrgUserId()); + assertNull(actual); + } + + @SuppressWarnings("deprecation") + @Test + public void getAppsFullListTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> expected = new ArrayList<>(); + expected.add(mockApp); + expected.add(mockApp2); + Mockito.when(dataAccessService.getList(EPApp.class, null)).thenReturn(expected); + List<EPApp> actual = epAppCommonServiceImpl.getAppsFullList(); + assertEquals(expected, actual); + + } + + @Test + public void getEcompAppAppsFullListTest() { + List<EcompApp> expected = new ArrayList<>(); + List<EcompApp> actual = epAppCommonServiceImpl.getEcompAppAppsFullList(); + assertEquals(expected, actual); + } + + @Test + public void transformAppsToEcompAppsTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> epAppsList = new ArrayList<>(); + epAppsList.add(mockApp); + epAppsList.add(mockApp2); + List<EcompApp> expected = new ArrayList<>(); + EcompApp ecompApp = new EcompApp(); + ecompApp.setName("test1"); + EcompApp ecompApp2 = new EcompApp(); + ecompApp2.setName("test2"); + expected.add(ecompApp); + expected.add(ecompApp2); + List<EcompApp> actual = epAppCommonServiceImpl.transformAppsToEcompApps(epAppsList); + assertEquals(expected.size(), actual.size()); + } + + @SuppressWarnings({ "unchecked", "deprecation" }) + @Test + public void getAllAppsForAllTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> appsList = new ArrayList<>(); + appsList.add(mockApp); + appsList.add(mockApp2); + List<AppsResponse> expected = new ArrayList<>(); + AppsResponse appResponse1 = new AppsResponse(mockApp.getId(), mockApp.getName(), mockApp.isRestrictedApp(), + mockApp.getEnabled()); + AppsResponse appResponse2 = new AppsResponse(mockApp2.getId(), mockApp2.getName(), mockApp2.isRestrictedApp(), + mockApp2.getEnabled()); + expected.add(appResponse1); + expected.add(appResponse2); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, " where id != " + ECOMP_APP_ID, "name", null)) + .thenReturn(appsList); + List<AppsResponse> actual = epAppCommonServiceImpl.getAllApps(true); + assertEquals(expected.size(), actual.size()); + } + + @SuppressWarnings({ "unchecked", "deprecation" }) + @Test + public void getAllAppsIsNotAllTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp2.setId(2l); + List<EPApp> appsList = new ArrayList<>(); + appsList.add(mockApp); + appsList.add(mockApp2); + List<AppsResponse> expected = new ArrayList<>(); + AppsResponse appResponse1 = new AppsResponse(mockApp.getId(), mockApp.getName(), mockApp.isRestrictedApp(), + mockApp.getEnabled()); + AppsResponse appResponse2 = new AppsResponse(mockApp2.getId(), mockApp2.getName(), mockApp2.isRestrictedApp(), + mockApp2.getEnabled()); + expected.add(appResponse1); + expected.add(appResponse2); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, + " where ( enabled = 'Y' or id = " + ECOMP_APP_ID + ")", "name", null)).thenReturn(appsList); + List<AppsResponse> actual = epAppCommonServiceImpl.getAllApps(false); + assertEquals(expected.size(), actual.size()); + } + + @Test + public void getAppTest() { + EPApp expected = mockApp(); + Mockito.when((EPApp) dataAccessService.getDomainObject(EPApp.class, expected.getId(), null)) + .thenReturn(expected); + EPApp actual = epAppCommonServiceImpl.getApp(expected.getId()); + assertEquals(expected, actual); + } + + @Test + public void getAppExceptionTest() { + EPApp expected = mockApp(); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).getDomainObject(EPApp.class, + expected.getId(), null); + EPApp actual = epAppCommonServiceImpl.getApp(expected.getId()); + assertNull(actual); + } + + @SuppressWarnings("unchecked") + @Test + public void getAppDetailTest() { + EPApp expected = mockApp(); + List<EPApp> appList = new ArrayList<>(); + appList.add(expected); + final Map<String, String> params = new HashMap<String, String>(); + params.put("appName", expected.getName()); + Mockito.when((List<EPApp>) dataAccessService.executeNamedQuery("getMyloginAppDetails", params, null)) + .thenReturn(appList); + EPApp actual = epAppCommonServiceImpl.getAppDetail(expected.getName()); + assertEquals(expected, actual); + } + + @Test + public void getAppDetailExceptionTest() { + EPApp expected = mockApp(); + List<EPApp> appList = new ArrayList<>(); + appList.add(expected); + final Map<String, String> params = new HashMap<String, String>(); + params.put("appName", expected.getName()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeNamedQuery("getMyloginAppDetails", + params, null); + EPApp actual = epAppCommonServiceImpl.getAppDetail(expected.getName()); + assertNull(actual); + } + + @Test + public void getUserProfile() { + EPUser user = mockUser.mockEPUser(); + final Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List<UserRole> userRoleList = new ArrayList<>(); + UserRole userRole = new UserRole(); + userRole.setFirstName("GuestT"); + userRole.setLastName("GuestT"); + userRole.setOrgUserId("guestT"); + userRole.setRoleId(1l); + userRole.setRoleName("Test"); + userRole.setUser_Id(-1l); + userRoleList.add(userRole); + UserRoles expected = new UserRoles(userRole); + Mockito.when(dataAccessService.executeNamedQuery("getUserRoles", params, null)).thenReturn(userRoleList); + UserRoles actual = epAppCommonServiceImpl.getUserProfile(user.getOrgUserId()); + assertEquals(expected.getOrgUserId(), actual.getOrgUserId()); + } + + @Test + public void getUserProfileNullTest() { + EPUser user = mockUser.mockEPUser(); + final Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List<UserRole> userRoleList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getUserRoles", params, null)).thenReturn(userRoleList); + UserRoles actual = epAppCommonServiceImpl.getUserProfile(user.getOrgUserId()); + assertNull(actual); + } + + @Test + public void getUserProfileNormalizedTest() { + EPUser user = mockUser.mockEPUser(); + user.setGuest(true); + user.setLoginId("guestT"); + final Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List<UserRole> userRoleList = new ArrayList<>(); + UserRole userRole = new UserRole(); + userRole.setFirstName("GuestT"); + userRole.setLastName("GuestT"); + userRole.setOrgUserId("guestT"); + userRole.setRoleId(1l); + userRole.setRoleName("Test"); + userRole.setUser_Id(-1l); + userRoleList.add(userRole); + UserRoles expected = new UserRoles(userRole); + Mockito.when(dataAccessService.executeNamedQuery("getUserRoles", params, null)).thenReturn(userRoleList); + UserRoles actual = epAppCommonServiceImpl.getUserProfileNormalized(user); + assertEquals(expected.getOrgUserId(), actual.getOrgUserId()); + } + + @Test + public void getRestrictedAppRolesTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setRestrictedApp(true); + user.setLoginId("guestT"); + List<LocalRole> expected = new ArrayList<>(); + LocalRole localRole = new LocalRole(); + localRole.setRoleId(1); + localRole.setRolename("test1"); + expected.add(localRole); + String sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND ROLE_ID = '" + + RESTRICTED_APP_ROLE_ID + "'"; + Mockito.when(dataAccessService.executeSQLQuery(sql, LocalRole.class, null)).thenReturn(expected); + Mockito.when((EPApp) dataAccessService.getDomainObject(EPApp.class, mockApp.getId(), null)).thenReturn(mockApp); + List<LocalRole> actual = epAppCommonServiceImpl.getAppRoles(mockApp.getId()); + assertEquals(expected, actual); + } + + @Test + public void getPoralAppRolesTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setRestrictedApp(false); + mockApp.setId(1l); + user.setLoginId("guestT"); + List<LocalRole> expected = new ArrayList<>(); + LocalRole localRole = new LocalRole(); + localRole.setRoleId(1); + localRole.setRolename("test1"); + expected.add(localRole); + String sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID IS NULL"; + Mockito.when(dataAccessService.executeSQLQuery(sql, LocalRole.class, null)).thenReturn(expected); + Mockito.when((EPApp) dataAccessService.getDomainObject(EPApp.class, mockApp.getId(), null)).thenReturn(mockApp); + List<LocalRole> actual = epAppCommonServiceImpl.getAppRoles(mockApp.getId()); + assertEquals(expected, actual); + } + + @Test + public void getNonPortalAndNonRestrictedAppRolesTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setRestrictedApp(false); + mockApp.setId(2l); + user.setLoginId("guestT"); + List<LocalRole> expected = new ArrayList<>(); + LocalRole localRole = new LocalRole(); + localRole.setRoleId(1); + localRole.setRolename("test1"); + expected.add(localRole); + String sql = "SELECT ROLE_ID, ROLE_NAME from FN_ROLE where UPPER(ACTIVE_YN) = 'Y' AND APP_ID = '" + + mockApp.getId() + "'"; + Mockito.when(dataAccessService.executeSQLQuery(sql, LocalRole.class, null)).thenReturn(expected); + Mockito.when((EPApp) dataAccessService.getDomainObject(EPApp.class, mockApp.getId(), null)).thenReturn(mockApp); + List<LocalRole> actual = epAppCommonServiceImpl.getAppRoles(mockApp.getId()); + assertEquals(expected, actual); + } + + @Test + public void getAdminAppsTest() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + List<AppIdAndNameTransportModel> expected = new ArrayList<>(); + AppIdAndNameTransportModel appIdAndNameTransportModel = new AppIdAndNameTransportModel(); + appIdAndNameTransportModel.setId(1l); + appIdAndNameTransportModel.setName("test1"); + expected.add(appIdAndNameTransportModel); + Mockito.when(adminRolesServiceImpl.isAccountAdmin(user)).thenReturn(true); + String format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)"; + String sql = String.format(format, user.getId()); + Mockito.when(dataAccessService.executeSQLQuery(sql, AppIdAndNameTransportModel.class, null)) + .thenReturn(expected); + List<AppIdAndNameTransportModel> actual = epAppCommonServiceImpl.getAdminApps(user); + assertEquals(expected, actual); + } + + @Test + public void getAdminAppsExceptionTest() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + List<AppIdAndNameTransportModel> expected = new ArrayList<>(); + Mockito.when(adminRolesServiceImpl.isAccountAdmin(user)).thenReturn(true); + String format = "SELECT app.APP_ID, app.APP_NAME, app.APP_TYPE FROM FN_APP app inner join FN_USER_ROLE userrole ON userrole.APP_ID=app.APP_ID " + + "where userrole.USER_ID = %d AND userrole.ROLE_ID=" + ACCOUNT_ADMIN_ROLE_ID + + " AND (app.ENABLED = 'Y' OR app.APP_ID=1)"; + String sql = String.format(format, user.getId()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeSQLQuery(sql, + AppIdAndNameTransportModel.class, null); + List<AppIdAndNameTransportModel> actual = epAppCommonServiceImpl.getAdminApps(user); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void addOnboardingAppUnKnownHostExceptionTest() throws Exception { + PowerMockito.mockStatic(PortalApiConstants.class); + PowerMockito.mockStatic(PortalApiProperties.class); + EPUser user = mockUser.mockEPUser(); + List<EPApp> mockAppList = new ArrayList<>(); + OnboardingApp onboardApp = new OnboardingApp(); + onboardApp.setRestrictedApp(false); + onboardApp.name = "test1"; + onboardApp.url = "http://test.com"; + onboardApp.isOpen = false; + onboardApp.isEnabled = true; + onboardApp.username = "test123"; + onboardApp.appPassword = "test123"; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion urlCrit = Restrictions.eq("url", onboardApp.url); + Criterion nameCrit = Restrictions.eq("name", onboardApp.name); + Criterion orCrit = Restrictions.or(urlCrit, nameCrit); + restrictionsList.add(orCrit); + List<String> uebList = new ArrayList<>(); + uebList.add("localhost"); + com.att.nsa.apiClient.credentials.ApiCredential apiCredential = new ApiCredential(user.getEmail(), + "ECOMP Portal Owner"); + CambriaIdentityManager mockIm = Mockito + .spy(new CambriaClientBuilders.IdentityManagerBuilder().usingHosts(uebList).build()); + Mockito.doReturn(apiCredential).when(mockIm).createApiKey(user.getEmail(), "ECOMP Portal Owner"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST)).thenReturn("localhost"); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList, null)) + .thenReturn(mockAppList); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); + FieldsValidator actual = epAppCommonServiceImpl.addOnboardingApp(onboardApp, user); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void modifyOnboardingAppTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setName("test1"); + mockApp.setId(2l); + mockApp.setUrl("http://test.com"); + mockApp.setUsername("test123"); + mockApp.setAppPassword("test123"); + mockApp.setRestrictedApp(false); + mockApp.setEnabled(true); + mockApp.setOpen(false); + List<EPApp> mockAppList = new ArrayList<>(); + mockAppList.add(mockApp); + OnboardingApp onboardApp = new OnboardingApp(); + onboardApp.setRestrictedApp(false); + onboardApp.name = "test1"; + onboardApp.id = 2l; + onboardApp.url = "http://test.com"; + onboardApp.isOpen = false; + onboardApp.isEnabled = true; + onboardApp.thumbnail = "test123imgthumbnail"; + onboardApp.username = "test123"; + onboardApp.appPassword = "test123"; + List<Criterion> restrictionsList1 = new ArrayList<Criterion>(); + Criterion idCrit = Restrictions.eq("id", onboardApp.id); + Criterion urlCrit = Restrictions.eq("url", onboardApp.url); + Criterion nameCrit = Restrictions.eq("name", onboardApp.name); + Criterion orCrit = Restrictions.or(idCrit, urlCrit, nameCrit); + restrictionsList1.add(orCrit); + Mockito.when((List<EPApp>) dataAccessService.getList(EPApp.class, null, restrictionsList1, null)) + .thenReturn(mockAppList); + Mockito.when((EPApp) session.get(EPApp.class, onboardApp.id)).thenReturn(mockApp); + String sql = "SELECT m.menu_id, m.column_num, m.text, m.parent_menu_id, m.url, m.active_yn " + + "FROM fn_menu_functional m, fn_menu_functional_roles r " + "WHERE m.menu_id = r.menu_id " + + " AND r.app_id = '" + onboardApp.id + "' "; + List<Integer> roles = new ArrayList<>(); + roles.add(1); + roles.add(2); + List<FunctionalMenuItem> menuItems = new ArrayList<>(); + FunctionalMenuItem functionalMenuItem = new FunctionalMenuItem(); + functionalMenuItem.setRestrictedApp(false); + functionalMenuItem.setUrl("http://test1.com"); + functionalMenuItem.setRoles(roles); + menuItems.add(functionalMenuItem); + Mockito.when(dataAccessService.executeSQLQuery(sql, FunctionalMenuItem.class, null)).thenReturn(menuItems); + Mockito.when((FunctionalMenuItem) session.get(FunctionalMenuItem.class, functionalMenuItem.menuId)) + .thenReturn(functionalMenuItem); + Mockito.doNothing().when(epUebHelper).addPublisher(mockApp); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + FieldsValidator actual = epAppCommonServiceImpl.modifyOnboardingApp(onboardApp, user); + assertEquals(expected, actual); + } + + @Test + public void saveWidgetsSortManualTest() { + EPUser user = mockUser.mockEPUser(); + List<EPWidgetsManualSortPreference> mockEPManualWidgets = new ArrayList<>(); + EPWidgetsManualSortPreference epWidgetsManualSortPreference = new EPWidgetsManualSortPreference(); + epWidgetsManualSortPreference.setUserId(user.getId()); + epWidgetsManualSortPreference.setWidgetCol(1); + epWidgetsManualSortPreference.setWidgetHeight(1); + epWidgetsManualSortPreference.setWidgetId(1l); + epWidgetsManualSortPreference.setWidgetRow(1); + epWidgetsManualSortPreference.setWidgetWidth(1); + mockEPManualWidgets.add(epWidgetsManualSortPreference); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null)) + .thenReturn(mockEPManualWidgets); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + List<EPWidgetsSortPreference> epWidgetsSortPreferenceList = new ArrayList<>(); + EPWidgetsSortPreference mockEPWidgetsSortPreference = new EPWidgetsSortPreference(); + mockEPWidgetsSortPreference.setRow(2); + mockEPWidgetsSortPreference.setHeaderText("test"); + mockEPWidgetsSortPreference.setSizeX(2); + mockEPWidgetsSortPreference.setSizeY(2); + mockEPWidgetsSortPreference.setWidgetid(2l); + mockEPWidgetsSortPreference.setWidgetIdentifier("test"); + mockEPWidgetsSortPreference.setCol(2); + epWidgetsSortPreferenceList.add(mockEPWidgetsSortPreference); + FieldsValidator actual = epAppCommonServiceImpl.saveWidgetsSortManual(epWidgetsSortPreferenceList, user); + assertEquals(expected, actual); + } + + @Test + public void saveWidgetsSortManualExistingRecordTest() { + EPUser user = mockUser.mockEPUser(); + List<EPWidgetsManualSortPreference> mockEPManualWidgets = new ArrayList<>(); + EPWidgetsManualSortPreference epWidgetsManualSortPreference = new EPWidgetsManualSortPreference(); + epWidgetsManualSortPreference.setUserId(user.getId()); + epWidgetsManualSortPreference.setWidgetCol(1); + epWidgetsManualSortPreference.setWidgetHeight(1); + epWidgetsManualSortPreference.setWidgetId(2l); + epWidgetsManualSortPreference.setWidgetRow(1); + epWidgetsManualSortPreference.setWidgetWidth(1); + mockEPManualWidgets.add(epWidgetsManualSortPreference); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null)) + .thenReturn(mockEPManualWidgets); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + List<EPWidgetsSortPreference> epWidgetsSortPreferenceList = new ArrayList<>(); + EPWidgetsSortPreference mockEPWidgetsSortPreference = new EPWidgetsSortPreference(); + mockEPWidgetsSortPreference.setRow(2); + mockEPWidgetsSortPreference.setHeaderText("test"); + mockEPWidgetsSortPreference.setSizeX(2); + mockEPWidgetsSortPreference.setSizeY(2); + mockEPWidgetsSortPreference.setWidgetid(2l); + mockEPWidgetsSortPreference.setWidgetIdentifier("test"); + mockEPWidgetsSortPreference.setCol(2); + epWidgetsSortPreferenceList.add(mockEPWidgetsSortPreference); + FieldsValidator actual = epAppCommonServiceImpl.saveWidgetsSortManual(epWidgetsSortPreferenceList, user); + assertEquals(expected, actual); + } + + @Test + public void deleteUserWidgetSortPrefTest() { + EPUser user = mockUser.mockEPUser(); + List<EPWidgetsManualSortPreference> mockEPManualWidgets = new ArrayList<>(); + EPWidgetsManualSortPreference epWidgetsManualSortPreference = new EPWidgetsManualSortPreference(); + epWidgetsManualSortPreference.setUserId(user.getId()); + epWidgetsManualSortPreference.setWidgetCol(1); + epWidgetsManualSortPreference.setWidgetHeight(1); + epWidgetsManualSortPreference.setWidgetId(2l); + epWidgetsManualSortPreference.setWidgetRow(1); + epWidgetsManualSortPreference.setWidgetWidth(1); + mockEPManualWidgets.add(epWidgetsManualSortPreference); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userWidgetManualSortPrfQuery", params, null)) + .thenReturn(mockEPManualWidgets); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + List<EPWidgetsSortPreference> epWidgetsSortPreferenceList = new ArrayList<>(); + EPWidgetsSortPreference mockEPWidgetsSortPreference = new EPWidgetsSortPreference(); + mockEPWidgetsSortPreference.setRow(2); + mockEPWidgetsSortPreference.setHeaderText("test"); + mockEPWidgetsSortPreference.setSizeX(2); + mockEPWidgetsSortPreference.setSizeY(2); + mockEPWidgetsSortPreference.setWidgetid(2l); + mockEPWidgetsSortPreference.setWidgetIdentifier("test"); + mockEPWidgetsSortPreference.setCol(2); + epWidgetsSortPreferenceList.add(mockEPWidgetsSortPreference); + FieldsValidator actual = epAppCommonServiceImpl.deleteUserWidgetSortPref(epWidgetsSortPreferenceList, user); + assertEquals(expected, actual); + } + + @Test + public void saveAppsSortPreferenceForNewUserTest() { + EPUser user = mockUser.mockEPUser(); + List<EPUserAppsSortPreference> mockEPAppSortPrefList = new ArrayList<>(); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null)) + .thenReturn(mockEPAppSortPrefList); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + EPAppsSortPreference mockEPAppsSortPreference = new EPAppsSortPreference(); + mockEPAppsSortPreference.setIndex(1); + mockEPAppsSortPreference.setTitle("Last Used"); + mockEPAppsSortPreference.setValue("L"); + FieldsValidator actual = epAppCommonServiceImpl.saveAppsSortPreference(mockEPAppsSortPreference, user); + assertEquals(expected, actual); + } + + @Test + public void saveAppsSortPreferenceUpdateTest() { + EPUser user = mockUser.mockEPUser(); + List<EPUserAppsSortPreference> mockEPAppSortPrefList = new ArrayList<>(); + EPUserAppsSortPreference mockEPAppSortPref = new EPUserAppsSortPreference(); + mockEPAppSortPref.setSortPref("L"); + mockEPAppSortPref.setId(2l); + mockEPAppSortPref.setUserId((int) (long) user.getId()); + mockEPAppSortPrefList.add(mockEPAppSortPref); + final Map<String, Long> params = new HashMap<>(); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null)) + .thenReturn(mockEPAppSortPrefList); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + EPAppsSortPreference mockEPAppsSortPreference = new EPAppsSortPreference(); + mockEPAppsSortPreference.setIndex(1); + mockEPAppsSortPreference.setTitle("Last Used"); + mockEPAppsSortPreference.setValue("L"); + FieldsValidator actual = epAppCommonServiceImpl.saveAppsSortPreference(mockEPAppsSortPreference, user); + assertEquals(expected, actual); + } + + @Test + public void getUserAppsSortTypePreferenceTest() { + EPUser user = mockUser.mockEPUser(); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsSortPreference> mockEPAppSortPrefList = new ArrayList<>(); + EPUserAppsSortPreference mockEPAppSortPref = new EPUserAppsSortPreference(); + mockEPAppSortPref.setSortPref("L"); + mockEPAppSortPref.setId(2l); + mockEPAppSortPref.setUserId((int) (long) user.getId()); + mockEPAppSortPrefList.add(mockEPAppSortPref); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppsSortPreferenceQuery", params, null)) + .thenReturn(mockEPAppSortPrefList); + String actual = epAppCommonServiceImpl.getUserAppsSortTypePreference(user); + assertEquals(mockEPAppSortPref.getSortPref(), actual); + } + + @Test + public void getUserAppsSortTypePreferenceExceptionTest() { + EPUser user = mockUser.mockEPUser(); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsSortPreference> mockEPAppSortPrefList = new ArrayList<>(); + EPUserAppsSortPreference mockEPAppSortPref = new EPUserAppsSortPreference(); + mockEPAppSortPref.setSortPref("L"); + mockEPAppSortPref.setId(2l); + mockEPAppSortPref.setUserId((int) (long) user.getId()); + mockEPAppSortPrefList.add(mockEPAppSortPref); + params.put("userId", user.getId()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService) + .executeNamedQuery("userAppsSortPreferenceQuery", params, null); + String actual = epAppCommonServiceImpl.getUserAppsSortTypePreference(user); + assertNull(actual); + } + + @Test + public void deleteUserAppSortManualTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setId(1l); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>(); + EPUserAppsManualSortPreference epManualApp = new EPUserAppsManualSortPreference(); + epManualApp.setAppId(mockApp.getId()); + epManualApp.setAppManualSortOrder(1); + epManualApp.setId(1l); + epManualApp.setUserId(user.getId()); + epManualApps.add(epManualApp); + params.put("userId", user.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppsManualSortPrfQuery", params, null)).thenReturn(epManualApps); + EPDeleteAppsManualSortPref delAppSortManual = new EPDeleteAppsManualSortPref(); + delAppSortManual.setAppId(mockApp.getId()); + delAppSortManual.setPending(false); + delAppSortManual.setSelect(false); + FieldsValidator actual = epAppCommonServiceImpl.deleteUserAppSortManual(delAppSortManual, user); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(200l); + assertEquals(expected, actual); + } + + @Test + public void deleteUserAppSortManualExceptionTest() { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setId(1l); + final Map<String, Long> params = new HashMap<>(); + List<EPUserAppsManualSortPreference> epManualApps = new ArrayList<EPUserAppsManualSortPreference>(); + EPUserAppsManualSortPreference epManualApp = new EPUserAppsManualSortPreference(); + epManualApp.setAppId(mockApp.getId()); + epManualApp.setAppManualSortOrder(1); + epManualApp.setId(1l); + epManualApp.setUserId(user.getId()); + epManualApps.add(epManualApp); + params.put("userId", user.getId()); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeNamedQuery("userAppsManualSortPrfQuery", params, null); + EPDeleteAppsManualSortPref delAppSortManual = new EPDeleteAppsManualSortPref(); + delAppSortManual.setAppId(mockApp.getId()); + delAppSortManual.setPending(false); + delAppSortManual.setSelect(false); + FieldsValidator actual = epAppCommonServiceImpl.deleteUserAppSortManual(delAppSortManual, user); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(500l); + assertEquals(expected, actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImplTest.java new file mode 100644 index 00000000..3cc6762f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLeftMenuServiceImplTest.java @@ -0,0 +1,117 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertNotEquals; + +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 org.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.CentralizedApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalsdk.core.domain.MenuData; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; + +public class EPLeftMenuServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + ExternalAccessRolesServiceImpl externalAccessRolesServiceImpl = new ExternalAccessRolesServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + EPLeftMenuServiceImpl epLeftMenuServiceImpl = new EPLeftMenuServiceImpl(); + + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getLeftMenuItemsTest() { + EPUser user = mockUser.mockEPUser(); + Set<MenuData> fullMenuSet = new TreeSet<>(); + MenuData menuData = new MenuData(); + menuData.setAction("test"); + menuData.setFunctionCd("test_1"); + menuData.setActive(true); + menuData.setExternalUrl("test"); + menuData.setId(1l); + menuData.setMenuSetCode("test"); + menuData.setSortOrder((short) 1); + menuData.setSeparator(true); + fullMenuSet.add(menuData); + Set<String> roleFunctionSet = new TreeSet<>(); + roleFunctionSet.add("test"); + roleFunctionSet.add("test2"); + Map<String, String> params = new HashMap<>(); + params.put("userId", user.getOrgUserId()); + List<CentralizedApp> applicationsList = new ArrayList<>(); + List<CentralizedApp> applicationsList2 = new ArrayList<>(); + CentralizedApp centralizedApp = new CentralizedApp(); + centralizedApp.setAppId(1); + centralizedApp.setAppName("test"); + applicationsList.add(centralizedApp); + applicationsList2.add(centralizedApp); + Mockito.when(dataAccessService.executeNamedQuery(Matchers.anyString(), Matchers.anyMap(), Matchers.anyMap())).thenReturn(applicationsList); + Mockito.when(externalAccessRolesServiceImpl.getCentralizedAppsOfUser(Matchers.anyString())).thenReturn(applicationsList2); + String actual = epLeftMenuServiceImpl.getLeftMenuItems(user, fullMenuSet, roleFunctionSet); + JSONObject notExpected = new JSONObject(); + assertNotEquals(notExpected.toString(), actual); + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLoginServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLoginServiceImplTest.java new file mode 100644 index 00000000..5eaa40fd --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPLoginServiceImplTest.java @@ -0,0 +1,239 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.command.EPLoginBean; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.util.EPUserUtils; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.onap.portalsdk.core.web.support.AppUtils; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EPUserUtils.class, CipherUtil.class, AppUtils.class, SystemProperties.class, + EPCommonSystemProperties.class }) +public class EPLoginServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + RestTemplate template = new RestTemplate(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + EPLoginServiceImpl epLoginServiceImpl = new EPLoginServiceImpl(); + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + EPLoginBean expected = new EPLoginBean(); + expected.setOrgUserId("guestT"); + Map<String, String> params = new HashMap<>(); + params.put("org_user_id", expected.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", params, new HashMap())).thenReturn(list); + EPLoginBean actual = epLoginServiceImpl.findUser(expected, "test", new HashMap<>()); + assertNotNull(actual); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserPasswordMatchTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + user.setLoginId("guestT"); + user.setLoginPwd("abc"); + EPLoginBean expected = new EPLoginBean(); + expected.setLoginId(user.getLoginId()); + expected.setLoginPwd("xyz"); + Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", params, new HashMap())).thenReturn(list); + Map<String, String> params2 = new HashMap<>(); + params2.put("login_id", user.getOrgUserId()); + List list2 = new ArrayList<>(); + list2.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByLoginId", params2, new HashMap())).thenReturn(list2); + Mockito.when(CipherUtil.decryptPKC(user.getLoginPwd())).thenReturn("xyz"); + EPLoginBean actual = epLoginServiceImpl.findUser(expected, "test", new HashMap<>()); + assertNotNull(actual); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserExcpetionTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + user.setLoginId("guestT"); + user.setLoginPwd("abc"); + EPLoginBean expected = new EPLoginBean(); + expected.setLoginId(user.getLoginId()); + expected.setLoginPwd("xyz"); + Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", params, new HashMap())).thenReturn(list); + Map<String, String> params2 = new HashMap<>(); + params2.put("login_id", user.getOrgUserId()); + List list2 = new ArrayList<>(); + list2.add(user); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeNamedQuery("getEPUserByLoginId", params2, new HashMap()); + Mockito.when(CipherUtil.decryptPKC(user.getLoginPwd())).thenReturn("xyz"); + EPLoginBean actual = epLoginServiceImpl.findUser(expected, "test", new HashMap<>()); + assertEquals(expected,actual); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserAppUtilsExcpetionTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(AppUtils.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + user.setLoginId("guestT"); + user.setLoginPwd("abc"); + user.setActive(false); + EPLoginBean expected = new EPLoginBean(); + expected.setOrgUserId(user.getOrgUserId()); + Map<String, String> params = new HashMap<>(); + params.put("org_user_id", user.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", params, new HashMap())).thenReturn(list); + Mockito.when(EPUserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))).thenReturn(false); + Mockito.when(AppUtils.isApplicationLocked()).thenReturn(true); + Mockito.when(EPUserUtils.hasRole(user, SystemProperties.getProperty(SystemProperties.SYS_ADMIN_ROLE_ID))).thenReturn(false); + Mockito.when(AppUtils.isApplicationLocked()).thenReturn(true); + EPLoginBean actual = epLoginServiceImpl.findUser(expected, "test", new HashMap<>()); + assertEquals(expected,actual); + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Test + public void findUserWithoutPwdTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<>(); + params.put("login_id", user.getOrgUserId()); + List list = new ArrayList<>(); + list.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByLoginId", params, new HashMap())).thenReturn(list); + EPUser actual = epLoginServiceImpl.findUserWithoutPwd(user.getOrgUserId()); + assertEquals(user.getOrgUserId(), actual.getOrgUserId()); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPProfileServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPProfileServiceImplTest.java new file mode 100644 index 00000000..9aa60185 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/EPProfileServiceImplTest.java @@ -0,0 +1,86 @@ +/* +* ============LICENSE_START======================================================= +* ONAP PORTAL +* ================================================================================ +* Copyright 2018 TechMahindra +*================================================================================= +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============LICENSE_END========================================================= +*/ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.service.EPProfileServiceImpl; +import org.onap.portalsdk.core.dao.ProfileDao; +import org.onap.portalsdk.core.domain.Profile; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; + +public class EPProfileServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + ProfileDao profileDao; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + EPProfileServiceImpl epProfileServiceImpl = new EPProfileServiceImpl(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void findAllTest() { + List<Profile> profileList = new ArrayList<>(); + Mockito.when(dataAccessService.getList(Profile.class, null)).thenReturn(profileList); + List<Profile> expectedRoleList = epProfileServiceImpl.findAll(); + assertEquals(expectedRoleList, profileList); + } + + @Test(expected = java.lang.NumberFormatException.class) + public void getUserTest() { + EPUser epUser = new EPUser(); + Mockito.when(dataAccessService.getDomainObject(EPUser.class, Long.parseLong("test"), null)).thenReturn(epUser); + epProfileServiceImpl.getUser("test"); + } + + @Test + public void saveUserTest() { + EPUser user = mockUser.mockEPUser(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(user, null); + epProfileServiceImpl.saveUser(user); + } + + @Test + public void getProfileTest() { + epProfileServiceImpl.getProfile(1); + + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java index 66cfdd31..172b9421 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/ExternalAccessRolesServiceImplTest.java @@ -39,16 +39,29 @@ package org.onap.portalapp.portal.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.json.JSONObject; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -59,16 +72,30 @@ import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.portalapp.portal.core.MockEPUser; import org.onap.portalapp.portal.domain.CentralV2RoleFunction; +import org.onap.portalapp.portal.domain.CentralizedApp; import org.onap.portalapp.portal.domain.EPApp; import org.onap.portalapp.portal.domain.EPAppRoleFunction; import org.onap.portalapp.portal.domain.EPRole; import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserApp; import org.onap.portalapp.portal.exceptions.InactiveApplicationException; +import org.onap.portalapp.portal.exceptions.InvalidUserException; import org.onap.portalapp.portal.framework.MockitoTestSuite; +import org.onap.portalapp.portal.transport.BulkUploadRoleFunction; +import org.onap.portalapp.portal.transport.BulkUploadUserRoles; +import org.onap.portalapp.portal.transport.CentralRole; +import org.onap.portalapp.portal.transport.CentralUser; +import org.onap.portalapp.portal.transport.CentralV2Role; import org.onap.portalapp.portal.transport.EcompUserRoles; +import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.onap.portalapp.portal.transport.GlobalRoleWithApplicationRoleFunction; +import org.onap.portalapp.portal.transport.LocalRole; import org.onap.portalapp.portal.utils.EPCommonSystemProperties; import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalapp.util.EPUserUtils; import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.domain.RoleFunction; import org.onap.portalsdk.core.restful.domain.EcompUser; import org.onap.portalsdk.core.service.DataAccessService; import org.onap.portalsdk.core.service.DataAccessServiceImpl; @@ -84,11 +111,14 @@ import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; +import com.fasterxml.jackson.databind.ObjectMapper; + @RunWith(PowerMockRunner.class) -@PrepareForTest({ EcompPortalUtils.class, SystemProperties.class, EPCommonSystemProperties.class }) +@PrepareForTest({ EcompPortalUtils.class, Criterion.class, Restrictions.class, SystemProperties.class, + EPCommonSystemProperties.class }) public class ExternalAccessRolesServiceImplTest { @Mock - DataAccessService dataAccessService1 = new DataAccessServiceImpl(); + DataAccessService dataAccessService = new DataAccessServiceImpl(); @Mock RestTemplate template = new RestTemplate(); @@ -96,11 +126,44 @@ public class ExternalAccessRolesServiceImplTest { @InjectMocks ExternalAccessRolesServiceImpl externalAccessRolesServiceImpl = new ExternalAccessRolesServiceImpl(); + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + @Before public void setup() { MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @After + public void after() { + session.close(); } + 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 FUNCTION_PIPE = "|"; + + private static final String APP_ID = "appId"; + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); @@ -113,6 +176,8 @@ public class ExternalAccessRolesServiceImplTest { EPApp app = new EPApp(); app.setName("Test"); app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); app.setDescription("test"); app.setNotes("test"); app.setUrl("test"); @@ -125,7 +190,7 @@ public class ExternalAccessRolesServiceImplTest { app.setUsername("test"); app.setAppPassword("test"); app.setOpen(false); - app.setEnabled(false); + app.setEnabled(true); app.setUebKey("test"); app.setUebSecret("test"); app.setUebTopicName("test"); @@ -133,38 +198,29 @@ public class ExternalAccessRolesServiceImplTest { return app; } + @SuppressWarnings("deprecation") @Test public void getAppRolesIfAppIsPortalTest() throws Exception { List<EPRole> applicationRoles = new ArrayList<>(); - Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); + Mockito.when(dataAccessService.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); List<EPRole> expectedApplicationRoles = externalAccessRolesServiceImpl.getAppRoles((long) 1); assertEquals(expectedApplicationRoles, applicationRoles); } + @SuppressWarnings("deprecation") @Test public void getAppRolesTest() throws Exception { List<EPRole> applicationRoles = new ArrayList<>(); - Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); + Mockito.when(dataAccessService.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); List<EPRole> expectedApplicationRoles = externalAccessRolesServiceImpl.getAppRoles((long) 10); assertEquals(expectedApplicationRoles, applicationRoles); } - // @SuppressWarnings("null") - // @Test(expected = java.lang.Exception.class) - // public void getAppRolesExceptionTest() throws Exception{ - // List<EPRole> applicationRoles = new ArrayList<>(); - // DataAccessService dataAccessService = null ; - // Mockito.when(dataAccessService.getList(EPRole.class, "where app_id = 10", - // null, null)).thenThrow(nullPointerException); - // List<EPRole> expectedApplicationRoles = - // externalAccessRolesServiceImpl.getAppRoles((long) 10); - // assertEquals(expectedApplicationRoles,applicationRoles); - // } - + @SuppressWarnings("deprecation") @Test public void getAppExceptionTest() throws Exception { List<EPApp> app = new ArrayList<>(); - Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) + Mockito.when(dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) .thenReturn(app); List<EPApp> expectedapp = externalAccessRolesServiceImpl.getApp(uebKey); assertEquals(app, expectedapp); @@ -174,11 +230,12 @@ public class ExternalAccessRolesServiceImplTest { public void getAppErrorTest() throws Exception { List<EPApp> appList = new ArrayList<>(); EPApp app = mockApp(); + app.setEnabled(false); appList.add(app); final Map<String, String> appUebkeyParams = new HashMap<>(); appUebkeyParams.put("appKey", "test-ueb-key"); - Mockito.when(dataAccessService1.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) - .thenReturn(appList); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); externalAccessRolesServiceImpl.getApp(uebKey); } @@ -190,7 +247,7 @@ public class ExternalAccessRolesServiceImplTest { appList.add(app); final Map<String, String> appUebkeyParams = new HashMap<>(); appUebkeyParams.put("appKey", "test-ueb-key"); - Mockito.when(dataAccessService1.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) .thenReturn(appList); List<EPApp> expectedapp = externalAccessRolesServiceImpl.getApp(uebKey); assertEquals(appList, expectedapp); @@ -218,12 +275,13 @@ public class ExternalAccessRolesServiceImplTest { roleList.add(ePRole); final Map<String, String> appUebkeyParams = new HashMap<>(); appUebkeyParams.put("appKey", "test-ueb-key"); - Mockito.when(dataAccessService1.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) .thenReturn(appList); final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); getPartnerAppRoleParams.put("appRoleId", role.getId()); - getPartnerAppRoleParams.put("appId", app.getId()); - Mockito.when(dataAccessService1.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)).thenReturn(roleList); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(roleList); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)) .thenReturn("Testurl"); ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); @@ -233,7 +291,6 @@ public class ExternalAccessRolesServiceImplTest { assertTrue(externalAccessRolesServiceImpl.addRole(role, uebKey)); } - @Test public void addRoleMethodNotAllowedTest() throws Exception { HttpHeaders headers = new HttpHeaders(); @@ -255,12 +312,13 @@ public class ExternalAccessRolesServiceImplTest { roleList.add(ePRole); final Map<String, String> appUebkeyParams = new HashMap<>(); appUebkeyParams.put("appKey", "test-ueb-key"); - Mockito.when(dataAccessService1.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) .thenReturn(appList); final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); getPartnerAppRoleParams.put("appRoleId", role.getId()); - getPartnerAppRoleParams.put("appId", app.getId()); - Mockito.when(dataAccessService1.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)).thenReturn(roleList); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(roleList); Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_URL)) .thenReturn("Testurl"); ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.METHOD_NOT_ALLOWED); @@ -295,6 +353,9 @@ public class ExternalAccessRolesServiceImplTest { @Test public void deleteCentralRoleFunctionTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); final Map<String, String> params = new HashMap<>(); EPApp app = mockApp(); params.put("functionCode", "menu_fun_code"); @@ -303,20 +364,110 @@ public class ExternalAccessRolesServiceImplTest { CentralV2RoleFunction domainCentralRoleFunction = new CentralV2RoleFunction(); domainCentralRoleFunction.setCode("menu_fun_code"); centralRoleFunctionList.add(domainCentralRoleFunction); - Mockito.when(dataAccessService1.executeNamedQuery("getRoleFunction", params, null)) + Mockito.when(dataAccessService.executeNamedQuery("getRoleFunction", params, null)) .thenReturn(centralRoleFunctionList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.OK); Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); HttpHeaders headers = new HttpHeaders(); - PowerMockito.mockStatic(EcompPortalUtils.class); Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); - - Mockito.doNothing().when(dataAccessService1).deleteDomainObjects(EPAppRoleFunction.class, + Mockito.doNothing().when(dataAccessService).deleteDomainObjects(EPAppRoleFunction.class, "app_id = " + app.getId() + " and function_cd = '" + "menu_fun_code" + "'", null); - assertTrue(externalAccessRolesServiceImpl.deleteCentralRoleFunction("menu_fun_code", app)); } + + @Test + public void deleteRoleForApplicationTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, String> deleteRoleParams = new HashMap<>(); + deleteRoleParams.put(APP_ROLE_NAME_PARAM, "test_delete"); + deleteRoleParams.put(APP_ID, String.valueOf(app.getId())); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole epRole = new EPRole(); + epRole.setName("test_delete"); + epRole.setId(1l); + epRole.setActive(true); + epRole.setAppRoleId(11l); + epRoleList.add(epRole); + Mockito.when( + dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, deleteRoleParams, null)) + .thenReturn(epRoleList); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", epRole.getId()); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setCode("test_code"); + epAppRoleFunction.setAppId(app.getId()); + epAppRoleFunction.setRoleAppId(null); + appRoleFunctionList.add(epAppRoleFunction); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + PowerMockito.mockStatic(EcompPortalUtils.class); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> DelResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(DelResponse); + assertTrue(externalAccessRolesServiceImpl.deleteRoleForApplication(epRole.getName(), app.getUebKey())); + } + + @Test + public void deleteRoleForPortalApplicationTest() throws Exception { + EPApp app = mockApp(); + app.setId(1l); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, String> deleteRoleParams2 = new HashMap<>(); + deleteRoleParams2.put(APP_ROLE_NAME_PARAM, "test_delete"); + List<EPRole> epRoleList2 = new ArrayList<>(); + EPRole epRole = new EPRole(); + epRole.setName("test_delete"); + epRole.setId(1l); + epRole.setActive(true); + epRoleList2.add(epRole); + Mockito.when(dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, deleteRoleParams2, null)) + .thenReturn(epRoleList2); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", epRole.getId()); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setCode("test_code"); + epAppRoleFunction.setAppId(app.getId()); + epAppRoleFunction.setRoleAppId(null); + appRoleFunctionList.add(epAppRoleFunction); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + PowerMockito.mockStatic(EcompPortalUtils.class); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> DelResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(DelResponse); + assertTrue(externalAccessRolesServiceImpl.deleteRoleForApplication(epRole.getName(), app.getUebKey())); + } + @Test public void deleteCentralRoleFunctionFailTest() throws Exception { final Map<String, String> params = new HashMap<>(); @@ -328,16 +479,14 @@ public class ExternalAccessRolesServiceImplTest { domainCentralRoleFunction.setCode("menu_fun_code"); centralRoleFunctionList.add(domainCentralRoleFunction); HttpClientErrorException httpClientErrorException = new HttpClientErrorException(HttpStatus.NOT_FOUND); - Mockito.when(dataAccessService1.executeNamedQuery("getRoleFunction", params, null)) + Mockito.when(dataAccessService.executeNamedQuery("getRoleFunction", params, null)) .thenReturn(centralRoleFunctionList); - ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.NOT_FOUND); Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenThrow(httpClientErrorException); HttpHeaders headers = new HttpHeaders(); PowerMockito.mockStatic(EcompPortalUtils.class); Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); - - Mockito.doNothing().when(dataAccessService1).deleteDomainObjects(EPAppRoleFunction.class, + Mockito.doNothing().when(dataAccessService).deleteDomainObjects(EPAppRoleFunction.class, "app_id = " + app.getId() + " and function_cd = '" + "menu_fun_code" + "'", null); boolean returnedValue = externalAccessRolesServiceImpl.deleteCentralRoleFunction("menu_fun_code", app); @@ -354,71 +503,233 @@ public class ExternalAccessRolesServiceImplTest { CentralV2RoleFunction domainCentralRoleFunction = new CentralV2RoleFunction(); domainCentralRoleFunction.setCode("menu_fun_code"); centralRoleFunctionList.add(domainCentralRoleFunction); - Mockito.when(dataAccessService1.executeNamedQuery("getAppFunctionDetails", params, null)) + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionDetails", params, null)) .thenThrow(nullPointerException); assertTrue(externalAccessRolesServiceImpl.deleteCentralRoleFunction("menu_fun_code", app)); } @Test - public void getUserTest() { + public void getRoleFunctionTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type|type_code|*")).thenReturn("type_code"); + Mockito.when(EcompPortalUtils.getFunctionType("test_type|type_code|*")).thenReturn("test_type"); + Mockito.when(EcompPortalUtils.getFunctionAction("test_type|type_code|*")).thenReturn("*"); + List<CentralV2RoleFunction> getRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction getCenRole = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); + getRoleFuncList.add(getCenRole); + final Map<String, String> params = new HashMap<>(); + params.put(FUNCTION_CODE_PARAMS, "test_type|type_code|*"); + params.put(APP_ID, String.valueOf(app.getId())); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null)) + .thenReturn(getRoleFuncList); + CentralV2RoleFunction actual = externalAccessRolesServiceImpl.getRoleFunction("test_type|type_code|*", + app.getUebKey()); + assertEquals(getCenRole.getCode(), actual.getCode()); + } + + @Test + public void getRoleFunctionMutilpleFilterTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + CentralV2RoleFunction expected = new CentralV2RoleFunction(null, "type_code", "test_name", null, "test_type", + "*", null); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type|type_code|*")).thenReturn("type_code"); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type_1|type_code_1|*")).thenReturn("type_code_1"); + Mockito.when(EcompPortalUtils.getFunctionType("test_type|type_code|*")).thenReturn("test_type"); + Mockito.when(EcompPortalUtils.getFunctionAction("test_type|type_code|*")).thenReturn("*"); + List<CentralV2RoleFunction> getRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction getCenRole = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); + CentralV2RoleFunction getCenRole2 = new CentralV2RoleFunction("test_type_1|type_code_1|*", "test_name_1"); + getRoleFuncList.add(getCenRole); + getRoleFuncList.add(getCenRole2); + final Map<String, String> params = new HashMap<>(); + params.put(FUNCTION_CODE_PARAMS, "test_type|type_code|*"); + params.put(APP_ID, String.valueOf(app.getId())); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, params, null)) + .thenReturn(getRoleFuncList); + CentralV2RoleFunction actual = externalAccessRolesServiceImpl.getRoleFunction("test_type|type_code|*", + app.getUebKey()); + assertEquals(expected.getCode(), actual.getCode()); + } + + @Test + public void getUserTest() throws InvalidUserException { List<EPUser> userList = new ArrayList<>(); EPUser user = mockUser.mockEPUser(); userList.add(user); final Map<String, String> userParams = new HashMap<>(); userParams.put("org_user_id", "guestT"); - Mockito.when(dataAccessService1.executeNamedQuery("getEPUserByOrgUserId", userParams, null)) + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null)) .thenReturn(userList); List<EPUser> expectedUserList = externalAccessRolesServiceImpl.getUser("guestT"); assertEquals(expectedUserList, userList); } - - - public void saveCentralRoleFunctionTest() throws Exception { + + @Test + public void getV2UserWithRolesTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + appList.add(app); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, String> userParams = new HashMap<>(); + userParams.put("org_user_id", user.getOrgUserId()); + List<EPUser> userList = new ArrayList<>(); + Set<EPUserApp> userAppSet = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setName("test"); + epRole.setId(1l); + epRole.setActive(true); + epRole.setAppRoleId(11l); + epUserApp.setApp(app); + epUserApp.setUserId(user.getId()); + epUserApp.setRole(epRole); + userAppSet.add(epUserApp); + user.setUserApps(userAppSet); + userList.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null)) + .thenReturn(userList); + final Map<String, Long> params = new HashMap<>(); + List<CentralV2RoleFunction> appRoleFunctionList = new ArrayList<>(); CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(); - centralV2RoleFunction.setCode("menu_test"); + centralV2RoleFunction.setCode("test_type|test_code|*"); + centralV2RoleFunction.setName("test name"); + centralV2RoleFunction.setAppId(app.getId()); + appRoleFunctionList.add(centralV2RoleFunction); + params.put("roleId", epUserApp.getRole().getId()); + params.put(APP_ID, epUserApp.getApp().getId()); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null)) + .thenReturn(appRoleFunctionList); + String actual = externalAccessRolesServiceImpl.getV2UserWithRoles(user.getOrgUserId(), app.getUebKey()); + String notExpected = ""; + assertNotEquals(actual, notExpected); + } + + @Test + public void saveCentralRoleFunctionNewTestForV2() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); EPApp app = mockApp(); app.setId((long) 1); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(); + centralV2RoleFunction.setCode("test_code"); + centralV2RoleFunction.setName("test name"); + centralV2RoleFunction.setAppId(app.getId()); + centralV2RoleFunction.setAction("*"); + centralV2RoleFunction.setType("test_type"); final Map<String, String> params = new HashMap<>(); - params.put("functionCd", "menu_test"); params.put("appId", String.valueOf(1)); + + List<CentralV2RoleFunction> appRoleFunc = new ArrayList<>(); + appRoleFunc.add(centralV2RoleFunction); + params.put(FUNCTION_CODE_PARAMS, centralV2RoleFunction.getType() + FUNCTION_PIPE + + centralV2RoleFunction.getCode() + FUNCTION_PIPE + centralV2RoleFunction.getAction()); + Mockito.when(dataAccessService.executeNamedQuery("getRoleFunction", params, null)).thenReturn(appRoleFunc); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectPerm = new JSONObject(); + JSONObject mockJsonObjectFinalPerm = new JSONObject(); + mockJsonObjectPerm.put("type", "com.test.app.test_type"); + mockJsonObjectPerm.put("instance", "com.test.app.test_code"); + mockJsonObjectPerm.put("action", "*"); + mockJsonObjectPerm.put("description", "test name"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObjectPerm); + mockJsonObjectFinalPerm.put("perm", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalPerm.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> updateResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(updateResponse); + Boolean actual = externalAccessRolesServiceImpl.saveCentralRoleFunction(centralV2RoleFunction, app); + assertEquals(true, actual); + } + + @Test + public void saveCentralRoleFunctionUpdateForV2Test() throws Exception { PowerMockito.mockStatic(EcompPortalUtils.class); + EPApp app = mockApp(); + app.setId((long) 1); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(); + centralV2RoleFunction.setCode("test_code"); + centralV2RoleFunction.setName("test name2"); + centralV2RoleFunction.setAppId(app.getId()); + centralV2RoleFunction.setAction("*"); + centralV2RoleFunction.setType("test_type"); + CentralV2RoleFunction centralV2RoleFunctionExisting = new CentralV2RoleFunction(); + centralV2RoleFunctionExisting.setCode("test_code"); + centralV2RoleFunctionExisting.setName("test name"); + centralV2RoleFunctionExisting.setAppId(app.getId()); + centralV2RoleFunctionExisting.setAction("*"); + centralV2RoleFunctionExisting.setType("test_type"); + final Map<String, String> params = new HashMap<>(); + params.put("appId", String.valueOf(1)); + List<CentralV2RoleFunction> appRoleFunc = new ArrayList<>(); + appRoleFunc.add(centralV2RoleFunctionExisting); + params.put(FUNCTION_CODE_PARAMS, centralV2RoleFunction.getType() + FUNCTION_PIPE + + centralV2RoleFunction.getCode() + FUNCTION_PIPE + centralV2RoleFunction.getAction()); + Mockito.when(dataAccessService.executeNamedQuery("getRoleFunction", params, null)).thenReturn(appRoleFunc); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); HttpHeaders headers = new HttpHeaders(); Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); - List<CentralV2RoleFunction> appRoleFunc = new ArrayList<>(); - appRoleFunc.add(centralV2RoleFunction); - Mockito.when(dataAccessService1.executeNamedQuery("getAppFunctionDetails", params, - null)).thenReturn(appRoleFunc); - ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.OK); + JSONObject mockJsonObjectPerm = new JSONObject(); + JSONObject mockJsonObjectFinalPerm = new JSONObject(); + mockJsonObjectPerm.put("type", "com.test.app.test_type"); + mockJsonObjectPerm.put("instance", "test_code"); + mockJsonObjectPerm.put("action", "*"); + mockJsonObjectPerm.put("description", "test name"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObjectPerm); + mockJsonObjectFinalPerm.put("perm", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalPerm.toString(), HttpStatus.OK); Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), - Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> updateResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(updateResponse); + Boolean actual = externalAccessRolesServiceImpl.saveCentralRoleFunction(centralV2RoleFunction, app); + assertEquals(true, actual); } - -// @Test -// public void getAllAppUsersIfAppIsPortalTest() throws Exception -// { -// List<EPApp> expectedapps = new ArrayList<>(); -// EPApp app = new EPApp(); -// app.setEnabled(true); -// app.setId((long) 1); -// expectedapps.add(app); -// List<EPRole> applicationRoles = new ArrayList<>(); -// Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); -// Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)).thenReturn(expectedapps); -// externalAccessRolesServiceImpl.getAllAppUsers(uebKey); -// } - - - @Test(expected = IndexOutOfBoundsException.class) - public void getAllAppUsersTest() throws Exception - { - List<EPApp> expectedapps = new ArrayList<>(); + + @SuppressWarnings("deprecation") + @Test + public void getAllAppUsersTest() throws Exception { EPApp app = new EPApp(); app.setEnabled(true); app.setId((long) 10); - expectedapps.add(app); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); List<EPRole> applicationRoles = new ArrayList<>(); - Mockito.when(dataAccessService1.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); - Mockito.when(dataAccessService1.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)).thenReturn(expectedapps); + Mockito.when(dataAccessService.getList(EPRole.class, "test", null, null)).thenReturn(applicationRoles); + Mockito.when(dataAccessService.getList(EPApp.class, " where ueb_key = '" + uebKey + "'", null, null)) + .thenReturn(appList); final Map<String, Long> appParams = new HashMap<>(); appParams.put("appId", app.getId()); List<EcompUserRoles> userList = new ArrayList<>(); @@ -426,31 +737,1648 @@ public class ExternalAccessRolesServiceImplTest { ecompUserRoles.setOrgUserId("guestT"); ecompUserRoles.setRoleId((long) 1); ecompUserRoles.setRoleName("test"); - EcompUserRoles ecompUserRoles2 = new EcompUserRoles(); ecompUserRoles2.setOrgUserId("guestT"); ecompUserRoles2.setRoleId((long) 2); ecompUserRoles2.setRoleName("test new"); userList.add(ecompUserRoles); userList.add(ecompUserRoles2); - - Mockito.when(dataAccessService1.executeNamedQuery("ApplicationUserRoles", appParams, null)).thenReturn(userList); - List<EcompUser> usersfinalList = externalAccessRolesServiceImpl.getAllAppUsers(uebKey); + Mockito.when(dataAccessService.executeNamedQuery("ApplicationUserRoles", appParams, null)).thenReturn(userList); + List<EcompUser> usersfinalList = externalAccessRolesServiceImpl.getAllAppUsers(app.getUebKey()); assertEquals(usersfinalList.get(0).getRoles().size(), 2); } - + @Test - public void getGlobalRolesOfPortalTest() - { - Mockito.when(dataAccessService1.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(null); + public void getGlobalRolesOfPortalTest() { + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(null); assertEquals(externalAccessRolesServiceImpl.getGlobalRolesOfPortal(), null); } - + @Test - public void getGlobalRolesOfPortalExceptionTest() - { + public void getGlobalRolesOfPortalExceptionTest() { List<EPRole> globalRoles = new ArrayList<>(); - Mockito.when(dataAccessService1.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenThrow(nullPointerException); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)) + .thenThrow(nullPointerException); assertEquals(externalAccessRolesServiceImpl.getGlobalRolesOfPortal(), globalRoles); } + + @Test + public void getRolesForAppTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> applicationRoles = new ArrayList<>(); + EPRole appRole = new EPRole(); + appRole.setActive(true); + appRole.setAppId(app.getId()); + appRole.setAppRoleId(100l); + appRole.setId(10l); + appRole.setName("test"); + applicationRoles.add(appRole); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(applicationRoles); + List<CentralV2RoleFunction> cenRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction = new CentralV2RoleFunction(); + v2RoleFunction.setAppId(app.getId()); + v2RoleFunction.setCode("test_type|test_code|*"); + v2RoleFunction.setName("test name"); + cenRoleFuncList.add(v2RoleFunction); + final Map<String, Long> params = new HashMap<>(); + params.put("roleId", appRole.getId()); + params.put(APP_ID, appList.get(0).getId()); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null)) + .thenReturn(cenRoleFuncList); + List<GlobalRoleWithApplicationRoleFunction> mockGlobalRoles = new ArrayList<>(); + GlobalRoleWithApplicationRoleFunction mockGlobalRole = new GlobalRoleWithApplicationRoleFunction(); + mockGlobalRole.setActive(true); + mockGlobalRole.setAppId(app.getId()); + mockGlobalRole.setRoleId(1111l); + mockGlobalRole.setRoleName("global_test"); + mockGlobalRole.setFunctionCd("test_type|test_code|*"); + mockGlobalRole.setFunctionName("test name"); + mockGlobalRoles.add(mockGlobalRole); + Map<String, Long> params2 = new HashMap<>(); + params2.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params2, null)) + .thenReturn(mockGlobalRoles); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<CentralV2Role> expected = new ArrayList<>(); + CentralV2Role cenV2Role = new CentralV2Role(); + CentralV2Role cenV2Role2 = new CentralV2Role(); + expected.add(cenV2Role); + expected.add(cenV2Role2); + List<CentralV2Role> actual = externalAccessRolesServiceImpl.getRolesForApp(app.getUebKey()); + assertEquals(expected.size(), actual.size()); + } + + @Test + public void getRoleFuncListTest() throws Exception { + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, Long> params = new HashMap<>(); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> expected = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); + expected.add(centralV2RoleFunction); + Mockito.when(dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null)).thenReturn(expected); + List<CentralV2RoleFunction> actual = externalAccessRolesServiceImpl.getRoleFuncList(app.getUebKey()); + assertEquals(expected, actual); + } + + @Test + public void getRoleInfoTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(2l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<GlobalRoleWithApplicationRoleFunction> mockGlobalRoles = new ArrayList<>(); + GlobalRoleWithApplicationRoleFunction mockGlobalRole = new GlobalRoleWithApplicationRoleFunction(); + mockGlobalRole.setActive(true); + mockGlobalRole.setAppId(app.getId()); + mockGlobalRole.setRoleId(2l); + mockGlobalRole.setRoleName("global_test"); + mockGlobalRole.setFunctionCd("test_type|test_code|*"); + mockGlobalRole.setFunctionName("test name"); + mockGlobalRoles.add(mockGlobalRole); + Map<String, Long> params = new HashMap<>(); + params.put("roleId", 2l); + params.put("requestedAppId", 2l); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", params, null)) + .thenReturn(mockGlobalRoles); + CentralV2Role actual = externalAccessRolesServiceImpl.getRoleInfo(2l, app.getUebKey()); + assertNotEquals(null, actual); + } + + @Test + public void getPartnerRoleInfoTest() throws Exception { + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> applicationRoles = new ArrayList<>(); + EPRole appRole = new EPRole(); + appRole.setActive(true); + appRole.setAppId(app.getId()); + appRole.setAppRoleId(100l); + appRole.setId(10l); + appRole.setName("test"); + applicationRoles.add(appRole); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("appRoleId", 10l); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(applicationRoles); + final Map<String, Long> params = new HashMap<>(); + params.put("roleId", appRole.getId()); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> cenRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction("test_type|type_code|*", "test_name"); + cenRoleFuncList.add(centralV2RoleFunction); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null)) + .thenReturn(cenRoleFuncList); + CentralV2Role actual = externalAccessRolesServiceImpl.getRoleInfo(10l, app.getUebKey()); + assertNotEquals(null, actual); + } + + @Test + public void saveRoleForPortalApplicationNewTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + EPApp app = mockApp(); + app.setId(1l); + Role addRoleTest = new Role(); + addRoleTest.setActive(true); + addRoleTest.setName("Test"); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + JSONObject mockJsonObjectRole = new JSONObject(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + final Map<String, String> epAppPortalRoleParams = new HashMap<>(); + epAppPortalRoleParams.put(APP_ROLE_NAME_PARAM, addRoleTest.getName()); + List<EPRole> getRoleCreated = new ArrayList<>(); + EPRole roleCreate = new EPRole(); + roleCreate.setActive(true); + roleCreate.setId(10l); + roleCreate.setName("test"); + getRoleCreated.add(roleCreate); + Mockito.when(dataAccessService.executeNamedQuery(GET_PORTAL_APP_ROLES_QUERY, epAppPortalRoleParams, null)) + .thenReturn(getRoleCreated); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveRoleForPortalApplicationUpdateTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(1l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(true); + addRoleTest.setName("Test2"); + addRoleTest.setId(2l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("roleId", addRoleTest.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectRole = new JSONObject(); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + JSONObject mockJsonObjectPerm1 = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + mockJsonObjectPerm1.put("type", "com.test.app.test_type"); + mockJsonObjectPerm1.put("instance", "test_instance"); + mockJsonObjectPerm1.put("action", "*"); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm1); + permsList.add(mockJsonObjectPerm2); + mockJsonObjectRole.put("name", "com.test.app.Test"); + mockJsonObjectRole.put("perms", permsList); + mockJsonObjectRole.put("description", + "{\"id\":\"2\",\"name\":\"Test\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"null\",\"appRoleId\":\"null\"}"); + List<JSONObject> roleList = new ArrayList<>(); + roleList.add(mockJsonObjectRole); + mockJsonObjectFinalRole.put("role", roleList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> delResponse = new ResponseEntity<>(roleList.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(delResponse); + ResponseEntity<String> addRoleResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addRoleResponse); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(getEPRole.getId())); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace("com.test.app"); + bulkUploadUserRoles.setOrgUserId("guestT"); + bulkUploadUserRoles.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null)) + .thenReturn(userRolesList); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + ResponseEntity<String> mockBulkUsersUpload = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(mockBulkUsersUpload); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", getEPRole.getId()); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> v2RoleFunction = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction1 = new CentralV2RoleFunction("test_type|test_instance|*", "Test Name"); + v2RoleFunction.add(v2RoleFunction1); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(v2RoleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> v2RoleFunction2 = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction3 = new CentralV2RoleFunction("test_type3|test_instance3|*", "Test Name3"); + v2RoleFunction2.add(v2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(v2RoleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveRoleExitsInDbButNotInExtAuthSystemTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(1l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(true); + addRoleTest.setName("Test2"); + addRoleTest.setId(2l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("roleId", addRoleTest.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> addRoleResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addRoleResponse); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(getEPRole.getId())); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace("com.test.app"); + bulkUploadUserRoles.setOrgUserId("guestT"); + bulkUploadUserRoles.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null)) + .thenReturn(userRolesList); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", getEPRole.getId()); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> v2RoleFunction = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction1 = new CentralV2RoleFunction("test_type|test_instance|*", "Test Name"); + v2RoleFunction.add(v2RoleFunction1); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(v2RoleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> v2RoleFunction2 = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction3 = new CentralV2RoleFunction("test_type3|test_instance3|*", "Test Name3"); + v2RoleFunction2.add(v2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(v2RoleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveGlobalRoleForPortalApplicationUpdateTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(1l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(true); + addRoleTest.setName("global_test2"); + addRoleTest.setId(1111l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("global_test"); + getEPRole.setId(1111l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("roleId", addRoleTest.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectRole = new JSONObject(); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + JSONObject mockJsonObjectPerm1 = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + mockJsonObjectPerm1.put("type", "com.test.app.test_type"); + mockJsonObjectPerm1.put("instance", "test_instance"); + mockJsonObjectPerm1.put("action", "*"); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm1); + permsList.add(mockJsonObjectPerm2); + mockJsonObjectRole.put("name", "com.test.app.global_test"); + mockJsonObjectRole.put("perms", permsList); + mockJsonObjectRole.put("description", + "{\"id\":\"1111\",\"name\":\"global_test\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"null\",\"appRoleId\":\"null\"}"); + List<JSONObject> roleList = new ArrayList<>(); + roleList.add(mockJsonObjectRole); + mockJsonObjectFinalRole.put("role", roleList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> delResponse = new ResponseEntity<>(roleList.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(delResponse); + ResponseEntity<String> addRoleResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addRoleResponse); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(getEPRole.getId())); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace("com.test.app"); + bulkUploadUserRoles.setOrgUserId("guestT"); + bulkUploadUserRoles.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null)) + .thenReturn(userRolesList); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + ResponseEntity<String> mockBulkUsersUpload = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(mockBulkUsersUpload); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", getEPRole.getId()); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> v2RoleFunction = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction1 = new CentralV2RoleFunction("test_type|test_instance|*", "Test Name"); + v2RoleFunction.add(v2RoleFunction1); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(v2RoleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> v2RoleFunction2 = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction3 = new CentralV2RoleFunction("test_type3|test_instance3|*", "Test Name3"); + v2RoleFunction2.add(v2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(v2RoleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveRoleForPartnerApplicationUpdateTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(false); + addRoleTest.setName("Test2"); + addRoleTest.setId(22l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test2"); + getEPRole.setId(2l); + getEPRole.setActive(true); + getEPRole.setAppRoleId(22l); + epRoleList.add(getEPRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("appRoleId", addRoleTest.getId()); + getPortalAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObjectRole = new JSONObject(); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + JSONObject mockJsonObjectPerm1 = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + mockJsonObjectPerm1.put("type", "com.test.app.test_type"); + mockJsonObjectPerm1.put("instance", "test_instance"); + mockJsonObjectPerm1.put("action", "*"); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm1); + permsList.add(mockJsonObjectPerm2); + mockJsonObjectRole.put("name", "com.test.app.Test"); + mockJsonObjectRole.put("perms", permsList); + mockJsonObjectRole.put("description", + "{\"id\":\"2\",\"name\":\"Test2\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"2\",\"appRoleId\":\"22\"}"); + List<JSONObject> roleList = new ArrayList<>(); + roleList.add(mockJsonObjectRole); + mockJsonObjectFinalRole.put("role", roleList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> delResponse = new ResponseEntity<>(roleList.toString(), HttpStatus.OK); + final Map<String, String> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put(APP_ROLE_NAME_PARAM, addRoleTest.getName()); + getPartnerAppRoleParams.put("appId", String.valueOf(app.getId())); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + getPartnerAppRoleParams, null)).thenReturn(epRoleList); + ResponseEntity<String> updateRoleResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(updateRoleResponse); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(delResponse); + ResponseEntity<String> addRoleResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addRoleResponse); + final Map<String, String> params = new HashMap<>(); + params.put("uebKey", app.getUebKey()); + params.put("roleId", String.valueOf(getEPRole.getId())); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace("com.test.app"); + bulkUploadUserRoles.setOrgUserId("guestT"); + bulkUploadUserRoles.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUsersForSingleRole", params, null)) + .thenReturn(userRolesList); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + ResponseEntity<String> mockBulkUsersUpload = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(mockBulkUsersUpload); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", getEPRole.getId()); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> v2RoleFunction = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction1 = new CentralV2RoleFunction("test_type|test_instance|*", "Test Name"); + v2RoleFunction.add(v2RoleFunction1); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(v2RoleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> v2RoleFunction2 = new ArrayList<>(); + CentralV2RoleFunction v2RoleFunction3 = new CentralV2RoleFunction("test_type3|test_instance3|*", "Test Name3"); + v2RoleFunction2.add(v2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(v2RoleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void saveGlobalRoleFunctionsForPartnerApplicationUpdateTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + Role addRoleTest = new Role(); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("test_type|test_instance|*"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("test_type3|test_instance3|*"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + addRoleTest.setActive(true); + addRoleTest.setName("global_test"); + addRoleTest.setId(1111l); + addRoleTest.setRoleFunctions(roleFuncSet); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + EPRole globalRole2 = new EPRole(); + globalRole2.setName("global_test2"); + globalRole2.setId(2222l); + globalRole2.setActive(true); + globalRoles.add(globalRole); + globalRoles.add(globalRole2); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> getGlobalRoles = new ArrayList<>(); + EPRole getEPGlobalRole = new EPRole(); + getEPGlobalRole.setName("global_test"); + getEPGlobalRole.setId(1111l); + getEPGlobalRole.setActive(true); + getGlobalRoles.add(getEPGlobalRole); + final Map<String, Long> getPortalAppRoleParams = new HashMap<>(); + getPortalAppRoleParams.put("roleId", globalRole.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPortalAppRoleParams, null)) + .thenReturn(getGlobalRoles); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when(epAppCommonServiceImpl.getApp(PortalConstants.PORTAL_APP_ID)).thenReturn(app); + JSONObject mockJsonObjectPerm = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + JSONObject mockJsonObjectPerm3 = new JSONObject(); + JSONObject mockJsonObjectPerm4 = new JSONObject(); + JSONObject mockJsonObjectFinalPerm = new JSONObject(); + mockJsonObjectPerm.put("type", "com.test.app.test_type"); + mockJsonObjectPerm.put("instance", "test_instance"); + mockJsonObjectPerm.put("action", "*"); + mockJsonObjectPerm.put("description", "Test Name"); + mockJsonObjectPerm2.put("type", "com.test.app.access"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + mockJsonObjectPerm2.put("description", "Test Name2"); + mockJsonObjectPerm3.put("type", "com.test.app.test_type3"); + mockJsonObjectPerm3.put("instance", "test_instance3"); + mockJsonObjectPerm3.put("action", "*"); + mockJsonObjectPerm3.put("description", "Test Name3"); + mockJsonObjectPerm4.put("type", "com.test.app.test_type4"); + mockJsonObjectPerm4.put("instance", "test_instance4"); + mockJsonObjectPerm4.put("action", "*"); + mockJsonObjectPerm4.put("description", "Test Name4"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObjectPerm); + mockJson.add(mockJsonObjectPerm2); + mockJson.add(mockJsonObjectPerm3); + mockJson.add(mockJsonObjectPerm4); + mockJsonObjectFinalPerm.put("perm", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalPerm.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + ResponseEntity<String> postResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(postResponse); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + final Map<String, Long> epAppRoleFuncParams = new HashMap<>(); + epAppRoleFuncParams.put("requestedAppId", app.getId()); + epAppRoleFuncParams.put("roleId", globalRole.getId()); + List<GlobalRoleWithApplicationRoleFunction> mockGlobalRoles = new ArrayList<>(); + GlobalRoleWithApplicationRoleFunction mockGlobalRole = new GlobalRoleWithApplicationRoleFunction(); + mockGlobalRole.setActive(true); + mockGlobalRole.setAppId(app.getId()); + mockGlobalRole.setRoleId(1111l); + mockGlobalRole.setRoleName("global_test"); + mockGlobalRole.setFunctionCd("test_type4|test_instance4|*"); + mockGlobalRole.setFunctionName("test name"); + mockGlobalRoles.add(mockGlobalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRoleForRequestedApp", epAppRoleFuncParams, null)) + .thenReturn(mockGlobalRoles); + ResponseEntity<String> delResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(delResponse); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", globalRole.getId()); + List<EPAppRoleFunction> appRoleFunctionList = new ArrayList<>(); + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setAppId(app.getId()); + epAppRoleFunction.setRoleAppId("1"); + epAppRoleFunction.setCode("test"); + epAppRoleFunction.setRoleId(1111l); + appRoleFunctionList.add(epAppRoleFunction); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctionList); + final Map<String, String> getAppFunctionParams = new HashMap<>(); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(roleFunc2.getCode())).thenReturn("test_instance3"); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type4|test_instance4|*")).thenReturn("test_instance4"); + getAppFunctionParams.put("appId", String.valueOf(app.getId())); + getAppFunctionParams.put(FUNCTION_CODE_PARAMS, roleFunc.getCode()); + List<CentralV2RoleFunction> roleFunction = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(null, roleFunc.getCode(), + roleFunc.getName(), app.getId(), null); + roleFunction.add(centralV2RoleFunction); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams, null)) + .thenReturn(roleFunction); + final Map<String, String> getAppFunctionParams2 = new HashMap<>(); + getAppFunctionParams2.put("appId", String.valueOf(app.getId())); + getAppFunctionParams2.put(FUNCTION_CODE_PARAMS, roleFunc2.getCode()); + List<CentralV2RoleFunction> roleFunction2 = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction2 = new CentralV2RoleFunction(null, roleFunc2.getCode(), + roleFunc2.getName(), app.getId(), null); + roleFunction2.add(centralV2RoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_FUNCTION_QUERY, getAppFunctionParams2, null)) + .thenReturn(roleFunction2); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.saveRoleForApplication(addRoleTest, + app.getUebKey()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void syncRoleFunctionFromExternalAccessSystemTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + JSONObject mockJsonObjectFinalPerm = new JSONObject(); + JSONObject mockJsonObjectPerm = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + JSONObject mockJsonObjectPerm3 = new JSONObject(); + mockJsonObjectPerm.put("type", "com.test.app.test_type"); + mockJsonObjectPerm.put("instance", "test_instance"); + mockJsonObjectPerm.put("action", "*"); + mockJsonObjectPerm.put("description", "test_name"); + List<String> rolePermList = new ArrayList<>(); + rolePermList.add("com.test.app|test1"); + mockJsonObjectPerm.put("roles", rolePermList); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + List<String> rolePermList2 = new ArrayList<>(); + rolePermList2.add("com.test.app|test1"); + rolePermList2.add("com.test.app|test2"); + rolePermList2.add("com.test.app|test6"); + rolePermList2.add("com.test.app.new|global_test"); + mockJsonObjectPerm2.put("action", "*"); + mockJsonObjectPerm2.put("roles", rolePermList2); + mockJsonObjectPerm2.put("description", "test_name2"); + mockJsonObjectPerm3.put("type", "com.test.app.access"); + mockJsonObjectPerm3.put("instance", "test_instance3"); + mockJsonObjectPerm3.put("action", "*"); + mockJsonObjectPerm3.put("description", "test_name3"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm); + permsList.add(mockJsonObjectPerm2); + permsList.add(mockJsonObjectPerm3); + mockJsonObjectFinalPerm.put("perm", permsList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalPerm.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + final Map<String, Long> params = new HashMap<>(); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> appFunctions = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(null, "test_type|test_instance|*", + "test_name", app.getId(), null); + CentralV2RoleFunction centralV2RoleFunction2 = new CentralV2RoleFunction(null, "test_instance2", "test_name2", + app.getId(), null); + CentralV2RoleFunction centralV2RoleFunction3 = new CentralV2RoleFunction(null, "test_instance5", "test_name5", + app.getId(), null); + appFunctions.add(centralV2RoleFunction); + appFunctions.add(centralV2RoleFunction2); + appFunctions.add(centralV2RoleFunction3); + Mockito.when(dataAccessService.executeNamedQuery("getAllRoleFunctions", params, null)).thenReturn(appFunctions); + List<EPRole> globalRoles = new ArrayList<>(); + EPRole globalRole = new EPRole(); + globalRole.setName("global_test"); + globalRole.setId(1111l); + globalRole.setActive(true); + globalRoles.add(globalRole); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRolesOfPortal", null, null)).thenReturn(globalRoles); + List<EPRole> getCurrentRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("test1"); + getEPRole.setId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("global_test"); + getEPRole2.setId(1111l); + getEPRole2.setActive(true); + EPRole getEPRole3 = new EPRole(); + getEPRole3.setName("test2"); + getEPRole3.setId(4l); + getEPRole3.setActive(true); + getCurrentRoleList.add(getEPRole); + getCurrentRoleList.add(getEPRole2); + getCurrentRoleList.add(getEPRole3); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(getCurrentRoleList); + final Map<String, String> appSyncFuncsParams = new HashMap<>(); + appSyncFuncsParams.put("appId", String.valueOf(app.getId())); + appSyncFuncsParams.put("functionCd", ""); + List<CentralV2RoleFunction> roleFunctionList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null)) + .thenReturn(roleFunctionList); + String code = centralV2RoleFunction.getCode(); + appSyncFuncsParams.put("functionCd", code); + CentralV2RoleFunction getCentralV2RoleFunction = new CentralV2RoleFunction(null, "test_type|test_instance|*", + "test_name", app.getId(), null); + roleFunctionList.add(getCentralV2RoleFunction); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null)) + .thenReturn(roleFunctionList); + List<LocalRole> localRoles = new ArrayList<>(); + LocalRole localRole = new LocalRole(); + localRole.setRoleId(2); + localRole.setRolename("test1"); + LocalRole localRole2 = new LocalRole(); + localRole2.setRoleId(3); + localRole2.setRolename("test3"); + localRoles.add(localRole); + localRoles.add(localRole2); + final Map<String, String> appRoleFuncParams = new HashMap<>(); + appRoleFuncParams.put("functionCd", "test_type2|test_instance2|*"); + appRoleFuncParams.put("appId", String.valueOf(app.getId())); + Mockito.when(dataAccessService.executeNamedQuery("getCurrentAppRoleFunctions", appRoleFuncParams, null)) + .thenReturn(localRoles); + Mockito.when(EcompPortalUtils.checkNameSpaceMatching("com.test.app", app.getNameSpace())).thenReturn(true); + Mockito.when(EcompPortalUtils.getFunctionCode("test_type2|test_instance2|*")).thenReturn("test_instance2"); + appSyncFuncsParams.put("functionCd", "test_instance2"); + List<CentralV2RoleFunction> roleFunctionList2 = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null)) + .thenReturn(roleFunctionList2); + String code2 = "test_type2|test_instance2|*"; + appSyncFuncsParams.put("functionCd", code2); + CentralV2RoleFunction getCentralV2RoleFunction2 = new CentralV2RoleFunction(null, "test_type2|test_instance2|*", + "test_name2", app.getId(), null); + roleFunctionList2.add(getCentralV2RoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appSyncFuncsParams, null)) + .thenReturn(roleFunctionList2); + final Map<String, Long> params3 = new HashMap<>(); + params3.put("appId", app.getId()); + params3.put("roleId", getEPRole2.getId()); + List<EPAppRoleFunction> currentGlobalRoleFunctionsList = new ArrayList<>(); + EPAppRoleFunction addGlobalRoleFunction = new EPAppRoleFunction(); + addGlobalRoleFunction.setAppId(app.getId()); + addGlobalRoleFunction.setCode("test_type|test_instance|*"); + addGlobalRoleFunction.setRoleId(1111l); + currentGlobalRoleFunctionsList.add(addGlobalRoleFunction); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", params3, null)) + .thenReturn(currentGlobalRoleFunctionsList); + final Map<String, String> roleParams = new HashMap<>(); + roleParams.put(APP_ROLE_NAME_PARAM, "test6"); + roleParams.put("appId", String.valueOf(app.getId())); + List<EPRole> roleCreated = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null)) + .thenReturn(roleCreated); + final Map<String, String> getRoleByNameParams = new HashMap<>(); + getRoleByNameParams.put(APP_ROLE_NAME_PARAM, "test6"); + getRoleByNameParams.put("appId", String.valueOf(app.getId())); + EPRole getNewEPRole = new EPRole(); + getNewEPRole.setName("test6"); + getNewEPRole.setId(8l); + getNewEPRole.setActive(true); + List<EPRole> roleCreated2 = new ArrayList<>(); + roleCreated2.add(getNewEPRole); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + getRoleByNameParams, null)).thenReturn(roleCreated2); + EPRole getNewEPRoleFinal = new EPRole(); + getNewEPRoleFinal.setName("test6"); + getNewEPRoleFinal.setId(8l); + getNewEPRoleFinal.setActive(true); + getNewEPRoleFinal.setAppRoleId(8l); + final Map<String, String> getRoleByNameParams2 = new HashMap<>(); + getRoleByNameParams2.put(APP_ROLE_NAME_PARAM, "test6"); + getRoleByNameParams2.put("appId", String.valueOf(app.getId())); + List<EPRole> roleCreated3 = new ArrayList<>(); + roleCreated3.add(getNewEPRole); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, + getRoleByNameParams2, null)).thenReturn(roleCreated3); + List<EPRole> roleInfo = new ArrayList<>(); + roleInfo.add(getNewEPRoleFinal); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("appRoleId", getNewEPRoleFinal.getId()); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(roleInfo); + externalAccessRolesServiceImpl.syncRoleFunctionFromExternalAccessSystem(app); + } + + @Test + public void syncApplicationRolesWithEcompDBTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + JSONObject mockJsonObjectRole = new JSONObject(); + JSONObject mockJsonObjectRole2 = new JSONObject(); + JSONObject mockJsonObjectFinalRole = new JSONObject(); + JSONObject mockJsonObjectPerm1 = new JSONObject(); + JSONObject mockJsonObjectPerm2 = new JSONObject(); + mockJsonObjectPerm1.put("type", "com.test.app.test_type"); + mockJsonObjectPerm1.put("instance", "test_instance"); + mockJsonObjectPerm1.put("action", "*"); + mockJsonObjectPerm2.put("type", "com.test.app.test_type2"); + mockJsonObjectPerm2.put("instance", "test_instance2"); + mockJsonObjectPerm2.put("action", "*"); + List<JSONObject> permsList = new ArrayList<>(); + permsList.add(mockJsonObjectPerm1); + permsList.add(mockJsonObjectPerm2); + mockJsonObjectRole.put("name", "com.test.app.Test"); + mockJsonObjectRole.put("perms", permsList); + mockJsonObjectRole.put("description", + "{\"id\":\"2\",\"name\":\"test1\",\"active\":\"true\",\"priority\":\"null\",\"appId\":\"2\",\"appRoleId\":\"2\"}"); + mockJsonObjectRole2.put("name", "com.test.app.Test2"); + List<JSONObject> permsList2 = new ArrayList<>(); + permsList2.add(mockJsonObjectPerm1); + mockJsonObjectRole2.put("perms", permsList2); + List<JSONObject> roleList = new ArrayList<>(); + roleList.add(mockJsonObjectRole); + roleList.add(mockJsonObjectRole2); + mockJsonObjectFinalRole.put("role", roleList); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObjectFinalRole.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + List<EPRole> getCurrentRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setAppId(app.getId()); + getEPRole.setAppRoleId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("Test3"); + getEPRole2.setId(3l); + getEPRole.setAppId(app.getId()); + getEPRole.setAppRoleId(3l); + getEPRole2.setActive(true); + getCurrentRoleList.add(getEPRole); + getCurrentRoleList.add(getEPRole2); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(getCurrentRoleList); + Mockito.when(EcompPortalUtils.checkNameSpaceMatching("com.test.app.test_type", app.getNameSpace())) + .thenReturn(true); + Mockito.when(EcompPortalUtils.checkNameSpaceMatching("com.test.app.test_type2", app.getNameSpace())) + .thenReturn(true); + List<EPAppRoleFunction> appRoleFunctions = new ArrayList<>(); + EPAppRoleFunction epAppRoleFunction = new EPAppRoleFunction(); + epAppRoleFunction.setAppId(app.getId()); + epAppRoleFunction.setCode("test_type|test_instance|*"); + epAppRoleFunction.setRoleId(getEPRole.getId()); + appRoleFunctions.add(epAppRoleFunction); + final Map<String, Long> appRoleFuncsParams = new HashMap<>(); + appRoleFuncsParams.put("appId", app.getId()); + appRoleFuncsParams.put("roleId", Long.valueOf(getEPRole.getId())); + Mockito.when( + dataAccessService.executeNamedQuery("getAppRoleFunctionOnRoleIdandAppId", appRoleFuncsParams, null)) + .thenReturn(appRoleFunctions); + List<CentralV2RoleFunction> getV2RoleFunction = new ArrayList<>(); + final Map<String, String> appFuncsParams = new HashMap<>(); + appFuncsParams.put("appId", String.valueOf(app.getId())); + appFuncsParams.put("functionCd", "test_instance2"); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null)) + .thenReturn(getV2RoleFunction); + appFuncsParams.put("functionCd", "test_type2|test_instance2|*"); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction(); + centralV2RoleFunction.setAppId(app.getId()); + centralV2RoleFunction.setCode("test_type2|test_instance2|*"); + centralV2RoleFunction.setName("test_name2"); + getV2RoleFunction.add(centralV2RoleFunction); + final Map<String, String> extRoleParams = new HashMap<>(); + List<EPRole> roleListDeactivate = new ArrayList<>(); + extRoleParams.put(APP_ROLE_NAME_PARAM, "Test3"); + extRoleParams.put(APP_ID, app.getId().toString()); + EPRole getEPRoleDeactivate = new EPRole(); + getEPRoleDeactivate.setName("Test3"); + getEPRoleDeactivate.setId(3l); + getEPRoleDeactivate.setAppId(app.getId()); + getEPRoleDeactivate.setAppRoleId(3l); + roleListDeactivate.add(getEPRoleDeactivate); + Mockito.when( + dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, extRoleParams, null)) + .thenReturn(roleListDeactivate); + Mockito.when(dataAccessService.executeNamedQuery("getAppFunctionOnCodeAndAppId", appFuncsParams, null)) + .thenReturn(getV2RoleFunction); + List<EPRole> updateLocalFromExtAuth = new ArrayList<>(); + updateLocalFromExtAuth.add(getEPRole); + final Map<String, String> roleParams = new HashMap<>(); + roleParams.put(APP_ROLE_NAME_PARAM, getEPRole.getName()); + roleParams.put(APP_ID, app.getId().toString()); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, roleParams, null)) + .thenReturn(updateLocalFromExtAuth); + roleParams.put(APP_ROLE_NAME_PARAM, getEPRole2.getName()); + List<EPRole> updateLocalFromExtAuth2 = new ArrayList<>(); + updateLocalFromExtAuth.add(getEPRole); + Mockito.when(dataAccessService.executeNamedQuery("getRoletoUpdateInExternalAuthSystem", roleParams, null)) + .thenReturn(updateLocalFromExtAuth2); + final Map<String, String> globalRoleParams = new HashMap<>(); + globalRoleParams.put("appId", String.valueOf(app.getId())); + globalRoleParams.put("appRoleName", "Test2"); + List<EPRole> addNewRoleList = new ArrayList<>(); + EPRole addRoleInLocal = new EPRole(); + addRoleInLocal.setName("Test2"); + addRoleInLocal.setId(4l); + addRoleInLocal.setAppId(app.getId()); + addRoleInLocal.setActive(true); + addNewRoleList.add(addRoleInLocal); + Mockito.when( + dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, globalRoleParams, null)) + .thenReturn(addNewRoleList); + final Map<String, String> params = new HashMap<>(); + params.put(APP_ROLE_NAME_PARAM, "Test2"); + params.put(APP_ID, app.getId().toString()); + addRoleInLocal.setAppRoleId(4l); + addNewRoleList.add(addRoleInLocal); + Mockito.when(dataAccessService.executeNamedQuery(GET_ROLE_TO_UPDATE_IN_EXTERNAL_AUTH_SYSTEM, params, null)) + .thenReturn(addNewRoleList); + externalAccessRolesServiceImpl.syncApplicationRolesWithEcompDB(app); + } + + @Test + public void deleteDependencyRoleRecord() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + EPApp app = mockApp(); + app.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setAppRoleId(2l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("appRoleId", getEPRole.getId()); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + JSONObject getUser = new JSONObject(); + getUser.put("name", "com.test.app.test1"); + ResponseEntity<String> getResponse = new ResponseEntity<>(getUser.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> DelResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(DelResponse); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.deleteDependencyRoleRecord(2l, + app.getUebKey(), user.getOrgUserId()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void deleteDependencyRoleRecordForPortal() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + SQLQuery SqlQuery = Mockito.mock(SQLQuery.class); + EPApp app = mockApp(); + app.setId(1l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setAppRoleId(2l); + getEPRole.setActive(true); + epRoleList.add(getEPRole); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("roleId", getEPRole.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPortalAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(epRoleList); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + JSONObject getUser = new JSONObject(); + getUser.put("name", "com.test.app.test1"); + ResponseEntity<String> getResponse = new ResponseEntity<>(getUser.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> DelResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(DelResponse); + Mockito.when(session.createSQLQuery(Matchers.anyString())).thenReturn(SqlQuery); + ExternalRequestFieldsValidator actual = externalAccessRolesServiceImpl.deleteDependencyRoleRecord(2l, + app.getUebKey(), user.getOrgUserId()); + ExternalRequestFieldsValidator expected = new ExternalRequestFieldsValidator(true, ""); + assertEquals(expected, actual); + } + + @Test + public void bulkUploadFunctionsTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<RoleFunction> roleFuncList = new ArrayList<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setCode("test_code"); + roleFunc.setName("test_name"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setCode("test_code2"); + roleFunc2.setName("test_name2"); + roleFuncList.add(roleFunc); + roleFuncList.add(roleFunc2); + Mockito.when(dataAccessService.executeNamedQuery("getAllFunctions", null, null)).thenReturn(roleFuncList); + JSONObject perm = new JSONObject(); + JSONObject permList = new JSONObject(); + perm.put("type", app.getNameSpace() + ".access"); + perm.put("instance", "type_instance"); + perm.put("action", "*"); + List<JSONObject> addPerms = new ArrayList<>(); + addPerms.add(perm); + permList.put("perm", addPerms); + ResponseEntity<String> getResponse = new ResponseEntity<>(permList.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + ResponseEntity<String> postResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(postResponse); + Integer actual = externalAccessRolesServiceImpl.bulkUploadFunctions(app.getUebKey()); + Integer expected = 2; + assertEquals(expected, actual); + } + + @Test + public void bulkUploadRolesTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> epRoleList = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setAppRoleId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("Test2"); + getEPRole2.setId(3l); + getEPRole2.setAppRoleId(3l); + getEPRole2.setActive(true); + epRoleList.add(getEPRole); + epRoleList.add(getEPRole2); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(epRoleList); + List<EPRole> epRoleList1 = new ArrayList<>(); + EPRole ePRole = new EPRole(); + ePRole.setName("Test"); + ePRole.setId(2l); + ePRole.setAppRoleId(2l); + ePRole.setActive(true); + epRoleList1.add(ePRole); + final Map<String, Long> getPartnerAppRoleParams = new HashMap<>(); + getPartnerAppRoleParams.put("appRoleId", ePRole.getId()); + getPartnerAppRoleParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams, null)) + .thenReturn(epRoleList1); + List<EPRole> epRoleList2 = new ArrayList<>(); + EPRole ePRole2 = new EPRole(); + ePRole2.setName("Test2"); + ePRole2.setId(3l); + ePRole2.setAppRoleId(3l); + ePRole2.setActive(true); + epRoleList2.add(ePRole2); + final Map<String, Long> getPartnerAppRoleParams2 = new HashMap<>(); + getPartnerAppRoleParams2.put("appRoleId", ePRole2.getId()); + getPartnerAppRoleParams2.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRoleByRoleId", getPartnerAppRoleParams2, null)) + .thenReturn(epRoleList2); + ResponseEntity<String> postResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(postResponse); + Integer actual = externalAccessRolesServiceImpl.bulkUploadRoles(app.getUebKey()); + Integer expected = 2; + assertEquals(expected, actual); + } + + @Test + public void bulkUploadUserRolesTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + app.setId(2l); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<BulkUploadUserRoles> userRolesList = new ArrayList<>(); + BulkUploadUserRoles bulkUploadUserRoles = new BulkUploadUserRoles(); + bulkUploadUserRoles.setAppNameSpace(app.getName()); + bulkUploadUserRoles.setOrgUserId(user.getOrgUserId()); + bulkUploadUserRoles.setRoleName("Test1"); + BulkUploadUserRoles bulkUploadUserRoles2 = new BulkUploadUserRoles(); + bulkUploadUserRoles2.setAppNameSpace(app.getName()); + bulkUploadUserRoles2.setOrgUserId(user.getOrgUserId()); + bulkUploadUserRoles2.setRoleName("Test2"); + userRolesList.add(bulkUploadUserRoles); + userRolesList.add(bulkUploadUserRoles2); + final Map<String, String> appParams = new HashMap<>(); + appParams.put("uebKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getBulkUserRoles", appParams, null)) + .thenReturn(userRolesList); + ResponseEntity<String> postResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(postResponse); + Integer actual = externalAccessRolesServiceImpl.bulkUploadUserRoles(app.getUebKey()); + Integer expected = 2; + assertEquals(expected, actual); + } + + @Test + public void getUserRolesTest() throws Exception { + EPApp app = mockApp(); + EPUser user = mockUser.mockEPUser(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, String> userParams = new HashMap<>(); + userParams.put("org_user_id", user.getOrgUserId()); + List<EPUser> userList = new ArrayList<>(); + Set<EPUserApp> userAppSet = user.getEPUserApps(); + EPUserApp epUserApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setName("test"); + epRole.setId(1l); + epRole.setActive(true); + epRole.setAppRoleId(11l); + epUserApp.setApp(app); + epUserApp.setUserId(user.getId()); + epUserApp.setRole(epRole); + userAppSet.add(epUserApp); + user.setUserApps(userAppSet); + userList.add(user); + Mockito.when(dataAccessService.executeNamedQuery("getEPUserByOrgUserId", userParams, null)) + .thenReturn(userList); + CentralUser actual = externalAccessRolesServiceImpl.getUserRoles(user.getOrgUserId(), app.getUebKey()); + assertNotNull(actual); + } + + @SuppressWarnings("unchecked") + @Test + public void getActiveRolesTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPUserUtils.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + EPApp app = mockApp(); + app.setId(1l); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> epRoles = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("Test2"); + getEPRole2.setId(3l); + getEPRole2.setActive(true); + epRoles.add(getEPRole); + epRoles.add(getEPRole2); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion active_ynCrt = Restrictions.eq("active", Boolean.TRUE); + Criterion appIdCrt = Restrictions.isNull("appId"); + Criterion andCrit = Restrictions.and(active_ynCrt, appIdCrt); + restrictionsList.add(andCrit); + Mockito.when((List<EPRole>) dataAccessService.getList(EPRole.class, null, restrictionsList, null)) + .thenReturn(epRoles); + final Map<String, Long> params = new HashMap<>(); + params.put("roleId", getEPRole.getId()); + params.put(APP_ID, app.getId()); + List<CentralV2RoleFunction> cenRoleFuncList = new ArrayList<>(); + CentralV2RoleFunction centralV2RoleFunction = new CentralV2RoleFunction("test_type|test_instance|*", + "test_name"); + CentralV2RoleFunction centralV2RoleFunction2 = new CentralV2RoleFunction("test_instance2", "test_name2"); + cenRoleFuncList.add(centralV2RoleFunction); + cenRoleFuncList.add(centralV2RoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params, null)) + .thenReturn(cenRoleFuncList); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("roleId", getEPRole2.getId()); + params2.put(APP_ID, app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getAppRoleFunctionList", params2, null)) + .thenReturn(cenRoleFuncList); + List<GlobalRoleWithApplicationRoleFunction> mockGlobalRoles = new ArrayList<>(); + GlobalRoleWithApplicationRoleFunction mockGlobalRole = new GlobalRoleWithApplicationRoleFunction(); + mockGlobalRole.setActive(true); + mockGlobalRole.setAppId(app.getId()); + mockGlobalRole.setRoleId(1111l); + mockGlobalRole.setRoleName("global_test"); + mockGlobalRole.setFunctionCd("test_type|test_code|*"); + mockGlobalRole.setFunctionName("test name"); + mockGlobalRoles.add(mockGlobalRole); + Map<String, Long> params3 = new HashMap<>(); + params3.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getGlobalRoleWithApplicationRoleFunctions", params3, null)) + .thenReturn(mockGlobalRoles); + Mockito.when(EcompPortalUtils.getFunctionCode(centralV2RoleFunction.getCode())).thenReturn("test_instance"); + Mockito.when(EcompPortalUtils.getFunctionCode(centralV2RoleFunction2.getCode())).thenReturn("test_instance2"); + List<CentralV2Role> actual = externalAccessRolesServiceImpl.getActiveRoles(app.getUebKey()); + assertEquals(actual.size(), 3); + } + + @Test + public void bulkUploadRolesFunctionsTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<EPRole> applicationRoles = new ArrayList<>(); + EPRole getEPRole = new EPRole(); + getEPRole.setName("Test"); + getEPRole.setId(2l); + getEPRole.setActive(true); + EPRole getEPRole2 = new EPRole(); + getEPRole2.setName("Test2"); + getEPRole2.setId(3l); + getEPRole2.setActive(true); + applicationRoles.add(getEPRole); + applicationRoles.add(getEPRole2); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", app.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getPartnerAppRolesList", appParams, null)) + .thenReturn(applicationRoles); + final Map<String, Long> params = new HashMap<>(); + params.put("roleId", getEPRole.getId()); + List<BulkUploadRoleFunction> appRoleFunc = new ArrayList<>(); + BulkUploadRoleFunction bulkUploadRoleFunction = new BulkUploadRoleFunction(); + bulkUploadRoleFunction.setFunctionCd("testcode"); + bulkUploadRoleFunction.setFunctionName("test_name"); + BulkUploadRoleFunction bulkUploadRoleFunction2 = new BulkUploadRoleFunction(); + bulkUploadRoleFunction2.setFunctionCd("menu_testcode2"); + bulkUploadRoleFunction2.setFunctionName("test_name2"); + appRoleFunc.add(bulkUploadRoleFunction); + appRoleFunc.add(bulkUploadRoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params, null)) + .thenReturn(appRoleFunc); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("roleId", getEPRole2.getId()); + List<BulkUploadRoleFunction> appRoleFunc2 = new ArrayList<>(); + appRoleFunc2.add(bulkUploadRoleFunction); + appRoleFunc2.add(bulkUploadRoleFunction2); + Mockito.when(dataAccessService.executeNamedQuery("uploadAllRoleFunctions", params2, null)) + .thenReturn(appRoleFunc2); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + Integer actual = externalAccessRolesServiceImpl.bulkUploadRolesFunctions(app.getUebKey()); + Integer expected = 4; + assertEquals(actual, expected); + } + + @Test + public void bulkUploadPartnerRoleFunctionsTest() throws Exception { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(SystemProperties.class); + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + List<Role> roles = new ArrayList<>(); + Role role = new Role(); + role.setName("Test"); + role.setId(2l); + role.setActive(true); + Role role2 = new Role(); + role2.setName("Test2"); + role2.setId(3l); + role2.setActive(true); + roles.add(role); + roles.add(role2); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("testcode"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("menu_testcode2"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + role.setRoleFunctions(roleFuncSet); + role2.setRoleFunctions(roleFuncSet); + ResponseEntity<String> getResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.PUT), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + externalAccessRolesServiceImpl.bulkUploadPartnerRoleFunctions(app.getUebKey(), roles); + } + + @Test + public void getMenuFunctionsListTest() throws Exception { + EPApp app = mockApp(); + List<EPApp> appList = new ArrayList<>(); + final Map<String, String> appUebkeyParams = new HashMap<>(); + appList.add(app); + appUebkeyParams.put("appKey", app.getUebKey()); + Mockito.when(dataAccessService.executeNamedQuery("getMyAppDetailsByUebKey", appUebkeyParams, null)) + .thenReturn(appList); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put(APP_ID, app.getId()); + List<String> expected = new ArrayList<>(); + expected.add("test_menu1"); + expected.add("test_menu2"); + Mockito.when(dataAccessService.executeNamedQuery("getMenuFunctions", appParams, null)).thenReturn(expected); + List<String> actual = externalAccessRolesServiceImpl.getMenuFunctionsList(app.getUebKey()); + assertEquals(expected, actual); + } + + @Test + public void getCentralizedAppsOfUserTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<>(); + params.put("userId", user.getOrgUserId()); + List<CentralizedApp> expected = new ArrayList<>(); + CentralizedApp centralizedApp = new CentralizedApp(); + centralizedApp.setAppId(2); + centralizedApp.setAppName("testapp1"); + expected.add(centralizedApp); + Mockito.when(dataAccessService.executeNamedQuery("getCentralizedAppsOfUser", params, null)) + .thenReturn(expected); + List<CentralizedApp> actual = externalAccessRolesServiceImpl.getCentralizedAppsOfUser(user.getOrgUserId()); + assertEquals(expected, actual); + } + + @Test + public void ConvertCentralRoleToRoleTest() throws Exception { + ObjectMapper mapper = new ObjectMapper(); + Role role = new Role(); + role.setName("Test"); + role.setId(3l); + role.setActive(true); + SortedSet<RoleFunction> roleFuncSet = new TreeSet<>(); + RoleFunction roleFunc = new RoleFunction(); + roleFunc.setName("Test Name"); + roleFunc.setCode("testcode"); + RoleFunction roleFunc2 = new RoleFunction(); + roleFunc2.setName("Test Name3"); + roleFunc2.setCode("menu_testcode2"); + roleFuncSet.add(roleFunc); + roleFuncSet.add(roleFunc2); + role.setRoleFunctions(roleFuncSet); + String roleInfo = mapper.writeValueAsString(role); + Role actual = externalAccessRolesServiceImpl.ConvertCentralRoleToRole(roleInfo); + assertNotNull(actual); + } + + @Test + public void convertV2CentralRoleListToOldVerisonCentralRoleListTest() { + List<CentralV2Role> v2CenRoleList = new ArrayList<>(); + CentralV2Role cenV2Role = new CentralV2Role(2l, "test1"); + CentralV2RoleFunction CentralV2Role = new CentralV2RoleFunction("testcode", "test_name"); + SortedSet<CentralV2RoleFunction> setV2RoleFuncs = new TreeSet<>(); + setV2RoleFuncs.add(CentralV2Role); + cenV2Role.setRoleFunctions(setV2RoleFuncs); + v2CenRoleList.add(cenV2Role); + List<CentralRole> actual = externalAccessRolesServiceImpl.convertV2CentralRoleListToOldVerisonCentralRoleList(v2CenRoleList); + assertEquals(1, actual.size()); + } } diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/FunctionalMenuServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/FunctionalMenuServiceImplTest.java deleted file mode 100644 index c954fcbd..00000000 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/FunctionalMenuServiceImplTest.java +++ /dev/null @@ -1,92 +0,0 @@ -package org.onap.portalapp.portal.service; -/*- - * ============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============================================ - * - * ECOMP is a trademark and service mark of AT&T Intellectual Property. - */ -//package org.openecomp.portalapp.portal.test.service; -// -//import static org.junit.Assert.assertTrue; -// -//import java.util.ArrayList; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -//import org.junit.Test; -//import org.openecomp.portalapp.portal.service.FunctionalMenuService; -//import org.openecomp.portalapp.portal.transport.BusinessCardApplicationRole; -//import org.openecomp.portalapp.portal.transport.FunctionalMenuRole; -//import org.openecomp.portalapp.test.framework.ApplicationCommonContextTestSuite; -//import org.springframework.beans.factory.annotation.Autowired; -// -//public class FunctionalMenuServiceImplTest extends ApplicationCommonContextTestSuite { -// -// @Autowired -// FunctionalMenuService functionalMenuService; -// -// @Test -// public void getAppListTestService() throws Exception { -// -// String userId = "guestT"; -// List<BusinessCardApplicationRole> userAppRolesActualResult = null; -// -// List<BusinessCardApplicationRole> userAppRolesExpectedResult = new ArrayList<BusinessCardApplicationRole>(); -// BusinessCardApplicationRole businessCardApplicationRole = new BusinessCardApplicationRole(); -// businessCardApplicationRole.setAppName("ECOMP Portal"); -// businessCardApplicationRole.setRoleName("System Administrator"); -// userAppRolesExpectedResult.add(businessCardApplicationRole); -// Map<String, String> params = new HashMap<String, String>(); -// params.put("userId", userId); -// userAppRolesActualResult = functionalMenuService.getUserAppRolesList(userId); -// assertTrue(userAppRolesActualResult.contains(businessCardApplicationRole)); -// -// } -// -// @Test -// public void getFunctionalMenuRoleTest() throws Exception { -// -// FunctionalMenuRole expectedFunctionalMenuRole = new FunctionalMenuRole(); -// expectedFunctionalMenuRole.setId(new Integer(-1)); -// -// expectedFunctionalMenuRole.setMenuId((long) 137); -// expectedFunctionalMenuRole.setAppId(new Integer(456)); -// expectedFunctionalMenuRole.setRoleId(new Integer(6214)); -// List<FunctionalMenuRole> actualFunctionalMenuRoleList = null; -// actualFunctionalMenuRoleList = functionalMenuService.getFunctionalMenuRole(); -// assertTrue(actualFunctionalMenuRoleList.contains(expectedFunctionalMenuRole)); -// -// } -//} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/MicroserviceServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/MicroserviceServiceImplTest.java new file mode 100644 index 00000000..fba7e6d2 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/MicroserviceServiceImplTest.java @@ -0,0 +1,207 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.util.ArrayList; +import java.util.List; + +import javax.crypto.BadPaddingException; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.domain.MicroserviceData; +import org.onap.portalapp.portal.domain.MicroserviceParameter; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({Criterion.class, Restrictions.class, CipherUtil.class, EPCommonSystemProperties.class, SystemProperties.class, Restrictions.class}) +public class MicroserviceServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + MicroserviceServiceImpl microserviceServiceImpl = new MicroserviceServiceImpl(); + + @Test + public void saveMicroserviceTest() throws Exception { + MicroserviceData microserviceData = new MicroserviceData(); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setId(1l); + microserviceData.setParameterList(microserviceParameters); + Long actual = microserviceServiceImpl.saveMicroservice(microserviceData); + assertEquals((Long)1l, actual); + } + + @Test + public void saveServiceParametersTest() throws Exception { + MicroserviceData microserviceData = new MicroserviceData(); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setId(1l); + microserviceData.setParameterList(microserviceParameters); + microserviceServiceImpl.saveServiceParameters(1l, microserviceParameters); + } + + @SuppressWarnings("unchecked") + @Test + public void getMicroserviceDataByIdTest() throws Exception { + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + MicroserviceData microserviceData = new MicroserviceData(); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setId(1l); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion idCriterion = Restrictions.eq("id", 1l); + restrictionsList.add(idCriterion); + List<MicroserviceData> microserviceDatas = new ArrayList<>(); + microserviceDatas.add(microserviceData); + Mockito.when((List<MicroserviceData>) dataAccessService.getList(MicroserviceData.class, null, restrictionsList, null)).thenReturn(microserviceDatas); + List<Criterion> restrictionsList2 = new ArrayList<Criterion>(); + Criterion serviceIdCriterion = Restrictions.eq("serviceId", 1l); + restrictionsList2.add(serviceIdCriterion); + Mockito.when((List<MicroserviceParameter>) dataAccessService.getList(MicroserviceParameter.class, null, restrictionsList2, null)).thenReturn(microserviceParameters); + MicroserviceData actual = microserviceServiceImpl.getMicroserviceDataById(1l); + assertNotNull(actual); + } + + @SuppressWarnings({ "unchecked", "deprecation" }) + @Test + public void getMicroserviceDataTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceData microserviceData = new MicroserviceData(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setPassword("xyz"); + microserviceData.setId(1l); + List<MicroserviceData> microserviceDatas = new ArrayList<>(); + microserviceDatas.add(microserviceData); + Mockito.when((List<MicroserviceData>) dataAccessService.getList(MicroserviceData.class, null)).thenReturn(microserviceDatas); + List<Criterion> restrictionsList2 = new ArrayList<Criterion>(); + Criterion serviceIdCriterion = Restrictions.eq("serviceId", 1l); + restrictionsList2.add(serviceIdCriterion); + Mockito.when((List<MicroserviceParameter>) dataAccessService.getList(MicroserviceParameter.class, null, restrictionsList2, null)).thenReturn(microserviceParameters); + Mockito.when(CipherUtil.decryptPKC("xyz", + SystemProperties.getProperty(SystemProperties.Decryption_Key))).thenReturn("abc"); + List<MicroserviceData> actual = microserviceServiceImpl.getMicroserviceData(); + assertNotNull(actual); + } + + @SuppressWarnings({ "unchecked", "deprecation", "static-access" }) + @Test + public void getMicroserviceDataBadPaddingExceptionTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(CipherUtil.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + List<MicroserviceParameter> microserviceParameters = new ArrayList<>(); + MicroserviceData microserviceData = new MicroserviceData(); + MicroserviceParameter microserviceParameter = new MicroserviceParameter(); + microserviceParameter.setId(1l); + microserviceParameter.setPara_key("test"); + microserviceParameter.setPara_value("test"); + microserviceParameters.add(microserviceParameter); + microserviceData.setActive("true"); + microserviceData.setAppId(1l); + microserviceData.setPassword("xyz"); + microserviceData.setId(1l); + List<MicroserviceData> microserviceDatas = new ArrayList<>(); + microserviceDatas.add(microserviceData); + Mockito.when((List<MicroserviceData>) dataAccessService.getList(MicroserviceData.class, null)).thenReturn(microserviceDatas); + List<Criterion> restrictionsList2 = new ArrayList<Criterion>(); + Criterion serviceIdCriterion = Restrictions.eq("serviceId", 1l); + restrictionsList2.add(serviceIdCriterion); + Mockito.when((List<MicroserviceParameter>) dataAccessService.getList(MicroserviceParameter.class, null, restrictionsList2, null)).thenReturn(microserviceParameters); + Mockito.when(CipherUtil.decryptPKC("xyz", + SystemProperties.getProperty(SystemProperties.Decryption_Key))).thenThrow(BadPaddingException.class); + List<MicroserviceData> actual = microserviceServiceImpl.getMicroserviceData(); + assertNotNull(actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PersUserWidgetServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PersUserWidgetServiceImplTest.java new file mode 100644 index 00000000..67c56eb3 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PersUserWidgetServiceImplTest.java @@ -0,0 +1,145 @@ +/* +* ============LICENSE_START======================================================= +* ONAP : PORTAL +* ================================================================================ +* Copyright 2018 TechMahindra +*================================================================================= +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============LICENSE_END========================================================= +*/ +package org.onap.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.PersUserWidgetSelection; +import org.onap.portalapp.portal.framework.MockitoTestSuite; +import org.onap.portalsdk.core.service.DataAccessService; + +public class PersUserWidgetServiceImplTest { + + @Mock + DataAccessService dataAccessService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + PersUserWidgetServiceImpl persUserWidgetServiceImpl = new PersUserWidgetServiceImpl(); + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + MockEPUser mockUser = new MockEPUser(); + + + @Test(expected = IllegalArgumentException.class) + public void setPersUserAppValueIfUserNull() { + persUserWidgetServiceImpl.setPersUserAppValue(null, null, false); + } + + @Test + public void setPersUserAppValueTest() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId((long) 1); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, false); + } + + public void setPersUserAppValueTestPass() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId((long) 1); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, false); + } + + @Test + public void setPersUserAppValueIfSelectTest_DeleteDomain() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId((long) 1); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, true); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(persUserWidgetSelection, null); + } + + @Test + public void setPersUserAppValueIfSelectTest_SaveDomain() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId(null); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserWidgetSelection, null); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, true); + persUserWidgetSelection.setStatusCode("S"); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserWidgetSelection, null); + } + + @Test + public void setPersUserAppValueWithoutSelectTest_DeleteDomain() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, false); + persUserWidgetSelection.setId((long) 1); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(persUserWidgetSelection, null); + } + + @Test + public void setPersUserAppValueWithoutSelectTest_SaveDomain() { + EPUser user = mockUser.mockEPUser(); + List<PersUserWidgetSelection> persUserAppSelectionList = new ArrayList<>(); + PersUserWidgetSelection persUserWidgetSelection = new PersUserWidgetSelection(); + persUserWidgetSelection.setId(null); + persUserAppSelectionList.add(persUserWidgetSelection); + Mockito.when(dataAccessService.getList(PersUserWidgetSelection.class, "test", null, null)) + .thenReturn(persUserAppSelectionList); + persUserWidgetServiceImpl.setPersUserAppValue(user, (long)999, false); + persUserWidgetSelection.setStatusCode("H"); + Mockito.doNothing().when(dataAccessService).saveDomainObject(persUserWidgetSelection, null); + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PortalAdminServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PortalAdminServiceImplTest.java new file mode 100644 index 00000000..ffad364c --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/PortalAdminServiceImplTest.java @@ -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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.transport.FieldsValidator; +import org.onap.portalapp.portal.transport.PortalAdmin; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, Criterion.class, Restrictions.class, PortalConstants.class, + SystemProperties.class, EPCommonSystemProperties.class }) +public class PortalAdminServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @Mock + RestTemplate template = new RestTemplate(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @After + public void after() { + session.close(); + } + + @InjectMocks + PortalAdminServiceImpl portalAdminServiceImpl = new PortalAdminServiceImpl(); + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("unchecked") + @Test + public void getPortalAdminsTest() { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + List<PortalAdmin> portalAdmins = new ArrayList<>(); + PortalAdmin portalAdmin = new PortalAdmin(); + portalAdmin.setFirstName("guest"); + portalAdmin.setLastName("test"); + portalAdmin.setLoginId("test"); + portalAdmin.setUserId(1l); + portalAdmins.add(portalAdmin); + Map<String, String> params = new HashMap<>(); + params.put("adminRoleId", "1"); + Mockito.when((List<PortalAdmin>) dataAccessService.executeNamedQuery("getPortalAdmins", params, null)) + .thenReturn(portalAdmins); + List<PortalAdmin> actual = portalAdminServiceImpl.getPortalAdmins(); + assertEquals(1, actual.size()); + } + + @Test + public void getPortalAdminsExceptionTest() { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + List<PortalAdmin> portalAdmins = new ArrayList<>(); + PortalAdmin portalAdmin = new PortalAdmin(); + portalAdmin.setFirstName("guest"); + portalAdmin.setLastName("test"); + portalAdmin.setLoginId("test"); + portalAdmin.setUserId(1l); + portalAdmins.add(portalAdmin); + Map<String, String> params = new HashMap<>(); + params.put("adminRoleId", "1"); + Mockito.doThrow(new NullPointerException()).when(dataAccessService).executeNamedQuery("getPortalAdmins", params, + null); + List<PortalAdmin> actual = portalAdminServiceImpl.getPortalAdmins(); + assertNull(actual); + } + + @SuppressWarnings("unchecked") + @Test + public void createPortalAdminNewUserTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + List<EPUser> users = new ArrayList<>(); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("orgUserId", user.getOrgUserId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)) + .thenReturn(users); + List<PortalAdmin> portalAdmins = new ArrayList<>(); + Mockito.when(dataAccessService.executeSQLQuery(Matchers.anyString(), Matchers.any() , Matchers.anyMap())) + .thenReturn(portalAdmins); + Mockito.when(searchServiceImpl.searchUserByUserId(user.getOrgUserId())).thenReturn(user); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + Mockito.when(epAppCommonServiceImpl.getApp(PortalConstants.PORTAL_APP_ID)).thenReturn(app); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + FieldsValidator actual = portalAdminServiceImpl.createPortalAdmin(user.getOrgUserId()); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void createPortalAdminExistingUserTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + List<EPUser> users = new ArrayList<>(); + users.add(user); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("orgUserId", user.getOrgUserId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)) + .thenReturn(users); + List<PortalAdmin> portalAdmins = new ArrayList<>(); + Mockito.when(dataAccessService.executeSQLQuery(Matchers.anyString(), Matchers.any() , Matchers.anyMap())) + .thenReturn(portalAdmins); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + Mockito.when(epAppCommonServiceImpl.getApp(PortalConstants.PORTAL_APP_ID)).thenReturn(app); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + FieldsValidator actual = portalAdminServiceImpl.createPortalAdmin(user.getOrgUserId()); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + assertEquals(expected, actual); + } + + @SuppressWarnings("unchecked") + @Test + public void deletePortalAdminTest() { + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + EPUser user = mockUser.mockEPUser(); + EPApp app = mockApp(); + List<EPUser> users = new ArrayList<>(); + users.add(user); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("id", user.getId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)) + .thenReturn(users); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + Mockito.when( + EPCommonSystemProperties.containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + Mockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + Mockito.when(epAppCommonServiceImpl.getApp(PortalConstants.PORTAL_APP_ID)).thenReturn(app); + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + FieldsValidator actual = portalAdminServiceImpl.deletePortalAdmin(user.getId()); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + assertEquals(expected, actual); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SearchServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SearchServiceImplTest.java new file mode 100644 index 00000000..61244ddd --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SearchServiceImplTest.java @@ -0,0 +1,141 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.command.support.SearchResult; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, PortalConstants.class, SystemProperties.class, + EPCommonSystemProperties.class }) +public class SearchServiceImplTest { + + @InjectMocks + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + EPLdapService epLdapService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("unchecked") + @Test + public void searchUsersInPhoneBookTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + List<String> tokens = new ArrayList<>(); + tokens.add("ts1234"); + tokens.add("TestName"); + EPUser user = new EPUser(); + user.setOrgUserId("ts1234"); + user.setFirstName("TestName"); + Mockito.when(EcompPortalUtils.parsingByRegularExpression(Matchers.anyString(), Matchers.anyString())).thenReturn(tokens); + SearchResult searchResult = new SearchResult(); + searchResult.add(user); + Mockito.when(epLdapService.searchPost(Matchers.any(EPUser.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt())).thenReturn(searchResult); + String actual = searchServiceImpl.searchUsersInPhoneBook("ts1234"); + assertNotEquals("[]", actual); + } + + @SuppressWarnings("unchecked") + @Test + public void searchUsersInPhoneBookFirtAndLastNameTest() throws Exception { + PowerMockito.mockStatic(EcompPortalUtils.class); + List<String> tokens = new ArrayList<>(); + tokens.add("ts1234"); + tokens.add("TestFirstName"); + tokens.add("TestLastName"); + EPUser user = new EPUser(); + user.setOrgUserId("ts1234"); + user.setFirstName("TestFirstName"); + user.setLastName("TestLastName"); + Mockito.when(EcompPortalUtils.parsingByRegularExpression(Matchers.anyString(), Matchers.anyString())).thenReturn(tokens); + SearchResult searchResult = new SearchResult(); + searchResult.add(user); + Mockito.when(epLdapService.searchPost(Matchers.any(EPUser.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt())).thenReturn(searchResult); + String actual = searchServiceImpl.searchUsersInPhoneBook("ts1234"); + assertNotEquals("[]", actual); + } + + @SuppressWarnings("unchecked") + @Test + public void searchUserByUserIdTest() throws Exception { + EPUser user = new EPUser(); + user.setOrgUserId("ts1234"); + SearchResult searchResult = new SearchResult(); + searchResult.add(user); + Mockito.when(epLdapService.searchPost(Matchers.any(EPUser.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt())).thenReturn(searchResult); + EPUser actual = searchServiceImpl.searchUserByUserId("ts1234"); + assertEquals(user, actual); + } + + @Test + public void searchUserByUserIdExceptionTest() throws Exception { + Mockito.doThrow(new NullPointerException()).when(epLdapService).searchPost(Matchers.any(EPUser.class), Matchers.anyString(), Matchers.anyString(), Matchers.anyString(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt()); + EPUser actual = searchServiceImpl.searchUserByUserId("ts1234"); + assertNull(actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SharedContextServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SharedContextServiceImplTest.java new file mode 100644 index 00000000..417c8b06 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/SharedContextServiceImplTest.java @@ -0,0 +1,131 @@ +/* + * ============LICENSE_START======================================================= + * ONAP PORTAL + * ================================================================================ + * Copyright 2018 TechMahindra + *================================================================================= + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.portalapp.portal.service; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.SharedContext; +import org.onap.portalsdk.core.service.DataAccessService; + +public class SharedContextServiceImplTest { + + @Mock + DataAccessService dataAccessService; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + SharedContextServiceImpl sharedContextServiceImpl = new SharedContextServiceImpl(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getSharedContextsTest() { + String contextId = "test"; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion contextIdCrit = Restrictions.eq("context_id", contextId); + restrictionsList.add(contextIdCrit); + List<SharedContext> contextsList = new ArrayList<>(); + SharedContext sharedContext = new SharedContext(); + contextsList.add(sharedContext); + Mockito.when((List<SharedContext>) dataAccessService.getList(SharedContext.class, null)) + .thenReturn(contextsList); + sharedContextServiceImpl.getSharedContexts("test"); + } + + @Test + public void getSharedContextsTest_usingKey() { + String contextId = "test"; + String key = "key"; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion contextIdCrit = Restrictions.eq("context_id", "test"); + Criterion keyCrit = Restrictions.eq("ckey", "key"); + restrictionsList.add(contextIdCrit); + restrictionsList.add(keyCrit); + List<SharedContext> contextsList = new ArrayList<>(); + SharedContext sharedContext = new SharedContext(); + contextsList.add(sharedContext); + Mockito.when((List<SharedContext>) dataAccessService.getList(SharedContext.class, null)) + .thenReturn(contextsList); + sharedContextServiceImpl.getSharedContext("test", "key"); + } + + @Test + public void addSharedContextTest() { + SharedContext context = new SharedContext(); + context.setContext_id("test"); + context.setCkey("key"); + context.setCvalue("demo"); + context.setId(1l); + Mockito.doNothing().when(dataAccessService).saveDomainObject(context, null); + sharedContextServiceImpl.addSharedContext("test", "key", "demo"); + } + + @Test + public void saveSharedContext() { + SharedContext context = new SharedContext(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(context, null); + sharedContextServiceImpl.saveSharedContext(context);//("test", "key", "demo"); + } + + @Test + public void deleteSharedContextsTest() { + List<SharedContext> contextsList = new ArrayList<>(); + SharedContext sharedContext = new SharedContext(); + contextsList.add(sharedContext); + String contextId = "test"; + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion contextIdCrit = Restrictions.eq("context_id", contextId); + restrictionsList.add(contextIdCrit); + Mockito.when((List<SharedContext>) dataAccessService.getList(SharedContext.class, null)) + .thenReturn(contextsList); + sharedContextServiceImpl.deleteSharedContexts("test"); + } + + @Test + public void deleteSharedContextTest() { + SharedContext context = new SharedContext(); + Mockito.doNothing().when(dataAccessService).deleteDomainObject(context, null); + sharedContextServiceImpl.deleteSharedContext(context); + } + + @Test + public void expireSharedContextsTest() { + final SimpleDateFormat dateFormat = new SimpleDateFormat("2018-02-22 10:00:00"); + Date expiredDateTime = new Date(System.currentTimeMillis() - 3600 * 1000); + final String whereClause = " create_time < '" + dateFormat.format(expiredDateTime) + "'"; + Mockito.doNothing().when(dataAccessService).deleteDomainObjects(SharedContext.class, whereClause, null); + sharedContextServiceImpl.expireSharedContexts(3600); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserNotificationServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserNotificationServiceImplTest.java new file mode 100644 index 00000000..ad41d5f6 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserNotificationServiceImplTest.java @@ -0,0 +1,209 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserNotification; +import org.onap.portalapp.portal.domain.EcompAppRole; +import org.onap.portalapp.portal.transport.EpNotificationItem; +import org.onap.portalapp.portal.transport.EpNotificationItemVO; +import org.onap.portalapp.portal.transport.EpRoleNotificationItem; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; + +public class UserNotificationServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + UserNotificationServiceImpl userNotificationServiceImpl = new UserNotificationServiceImpl(); + + MockEPUser mockUser = new MockEPUser(); + + @Test + public void getNotificationsTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<>(); + params.put("user_id", String.valueOf(user.getId())); + List<EpNotificationItem> mockNotificationList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getNotifications", params, null)).thenReturn(mockNotificationList); + List<EpNotificationItem> notificationList = userNotificationServiceImpl.getNotifications(user.getId()); + assertEquals(notificationList, mockNotificationList); + } + + @Test + public void getNotificationHistoryVOTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<String, String>(); + params.put("user_id", String.valueOf(user.getId())); + List<EpNotificationItemVO> mockNotificationListVO = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getNotificationHistoryVO", + params, null)).thenReturn(mockNotificationListVO); + List<EpNotificationItemVO> notificationListVO = userNotificationServiceImpl.getNotificationHistoryVO(user.getId()); + assertEquals(notificationListVO,mockNotificationListVO); + } + + @Test + public void getAdminNotificationVOSTest() { + EPUser user = mockUser.mockEPUser(); + Map<String, String> params = new HashMap<String, String>(); + params.put("user_id", String.valueOf(user.getId())); + List<EpNotificationItemVO> mockAdminNotificationListItemVO = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getAdminNotificationHistoryVO", + params, null)).thenReturn(mockAdminNotificationListItemVO); + List<EpNotificationItemVO> adminNotificationListItemVO = userNotificationServiceImpl.getAdminNotificationVOS(user.getId()); + assertEquals(adminNotificationListItemVO,mockAdminNotificationListItemVO); + } + + @Test + public void getNotificationRolesTest() { + Map<String, String> params = new HashMap<String, String>(); + params.put("notificationId", Long.toString(1l)); + List<EpRoleNotificationItem> mockRoleNotifList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getNotificationRoles", + params, null)).thenReturn(mockRoleNotifList); + List<EpRoleNotificationItem> roleNotifList = userNotificationServiceImpl.getNotificationRoles(1l); + assertEquals(roleNotifList,mockRoleNotifList); + } + + @Test + public void getAppRoleListTest() { + List<EcompAppRole> mockAppRoleList = new ArrayList<>(); + Mockito.when(dataAccessService + .executeNamedQuery("getEpNotificationAppRoles", null, null)).thenReturn(mockAppRoleList); + List<EcompAppRole> appRoleList = userNotificationServiceImpl.getAppRoleList(); + assertEquals(mockAppRoleList, appRoleList); + } + + @Test + public void setNotificationReadTest() { + EPUserNotification mockUserNotification = new EPUserNotification(); + mockUserNotification.setNotificationId(1l); + mockUserNotification.setId(1l); + mockUserNotification.setUpdateTime(new Date()); + mockUserNotification.setViewed("Y"); + mockUserNotification.setUserId((long) 1); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockUserNotification, null); + userNotificationServiceImpl.setNotificationRead(1l, 1); + } + + @Test + public void saveNotificationTest() throws Exception { + EpNotificationItem epNotificationItem = new EpNotificationItem(); + List<Long> roleIdList = new ArrayList<>(); + Long roleId = new Long(1l); + Long roleId2 = new Long(16l); + roleIdList.add(roleId); + roleIdList.add(roleId2); + epNotificationItem.setIsForAllRoles("N"); + epNotificationItem.setRoleIds(roleIdList); + epNotificationItem.setNotificationId(1l); + Mockito.doNothing().when(dataAccessService).saveDomainObject(epNotificationItem, null); + userNotificationServiceImpl.saveNotification(epNotificationItem); + } + + @Test + public void getUsersByOrgIdsTest() { + Map<String, Object> params = new HashMap<String, Object>(); + params.put("OrgIds", "test"); + List<EPUser> mockUserList = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("getUsersByOrgIdsNotifications", + params, null)).thenReturn(mockUserList); + List<String> orgIdsList = new ArrayList<>(); + String orgId = "test"; + orgIdsList.add(orgId); + List<EPUser> userList = userNotificationServiceImpl.getUsersByOrgIds(orgIdsList); + assertEquals(userList, mockUserList); + } + + @Test + public void getMessageRecipientsTest() { + Map<String, String> params = new HashMap<>(); + params.put("notificationId", Long.toString(1l)); + List<String> mockActiveUsers = new ArrayList<>(); + Mockito.when(dataAccessService.executeNamedQuery("messageRecipients", + params, null)).thenReturn(mockActiveUsers); + List<String> activeUsers = userNotificationServiceImpl.getMessageRecipients(1l); + assertEquals(activeUsers, mockActiveUsers); + } + + @Test + public void deleteNotificationsFromEpNotificationTableTest() { + Map<String, String> params = new HashMap<String, String>(); + Mockito.when(dataAccessService + .executeNamedQuery("deleteNotificationsFromEpUserNotificationTable", params, null)).thenReturn(null); + userNotificationServiceImpl.deleteNotificationsFromEpNotificationTable(); + } + + @Test + public void deleteNotificationsFromEpUserNotificationTable() { + Map<String, String> params = new HashMap<String, String>(); + Mockito.when(dataAccessService + .executeNamedQuery("deleteNotificationsFromEpUserNotificationTable", params, null)).thenReturn(null); + userNotificationServiceImpl.deleteNotificationsFromEpUserNotificationTable(); + } + + @Test + public void deleteNotificationsFromEpRoleNotificationTable() { + Map<String, String> params = new HashMap<String, String>(); + Mockito.when(dataAccessService + .executeNamedQuery("deleteNotificationsFromEpRoleNotificationTable", params, null)).thenReturn(null); + userNotificationServiceImpl.deleteNotificationsFromEpRoleNotificationTable(); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java new file mode 100644 index 00000000..2cb285f3 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserRolesCommonServiceImplTest.java @@ -0,0 +1,1466 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; + +import javax.servlet.http.HttpServletResponse; + +import org.apache.cxf.transport.http.HTTPException; +import org.hibernate.Query; +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.json.JSONObject; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Matchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.externalsystemapproval.model.ExternalSystemRoleApproval; +import org.onap.portalapp.externalsystemapproval.model.ExternalSystemUser; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPRole; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserApp; +import org.onap.portalapp.portal.domain.EPUserAppCatalogRoles; +import org.onap.portalapp.portal.domain.EPUserAppRoles; +import org.onap.portalapp.portal.domain.EPUserAppRolesRequest; +import org.onap.portalapp.portal.domain.EPUserAppRolesRequestDetail; +import org.onap.portalapp.portal.domain.ExternalSystemAccess; +import org.onap.portalapp.portal.transport.AppWithRolesForUser; +import org.onap.portalapp.portal.transport.CentralV2Role; +import org.onap.portalapp.portal.transport.EPUserAppCurrentRoles; +import org.onap.portalapp.portal.transport.EcompUserAppRoles; +import org.onap.portalapp.portal.transport.ExternalRequestFieldsValidator; +import org.onap.portalapp.portal.transport.FieldsValidator; +import org.onap.portalapp.portal.transport.FunctionalMenuItem; +import org.onap.portalapp.portal.transport.FunctionalMenuRole; +import org.onap.portalapp.portal.transport.RemoteRole; +import org.onap.portalapp.portal.transport.RemoteUserWithRoles; +import org.onap.portalapp.portal.transport.RoleInAppForUser; +import org.onap.portalapp.portal.transport.UserApplicationRoles; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.domain.Role; +import org.onap.portalsdk.core.restful.domain.EcompRole; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.service.RoleServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +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.web.client.RestTemplate; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, SystemProperties.class, PortalConstants.class, + EPCommonSystemProperties.class }) +public class UserRolesCommonServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + ExternalAccessRolesServiceImpl externalAccessRolesServiceImpl = new ExternalAccessRolesServiceImpl(); + + @Mock + ApplicationsRestClientService applicationsRestClientService; + + @Mock + RoleServiceImpl roleServiceImpl = new RoleServiceImpl(); + + @Mock + SearchServiceImpl searchServiceImpl = new SearchServiceImpl(); + + @Mock + EPRoleServiceImpl epRoleServiceImpl = new EPRoleServiceImpl(); + + @Mock + RestTemplate template = new RestTemplate(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @InjectMocks + UserRolesCommonServiceImpl userRolesCommonServiceImpl = new UserRolesCommonServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @After + public void after() { + session.close(); + } + + MockEPUser mockUser = new MockEPUser(); + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 1); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(false); + app.setCentralAuth(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + @SuppressWarnings("unchecked") + @Test + public void getAppRolesForUserCentralizedForPortal() throws Exception { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<RoleInAppForUser> mockRoleInAppForUserList = getMockedRoleInAppUserList(); + List<CentralV2Role> mockCenV2Role = new ArrayList<>(); + CentralV2Role cenV2Role = new CentralV2Role(1l, null, null, null, null, null, "test1", true, null, + new TreeSet<>(), new TreeSet<>(), new TreeSet<>()); + CentralV2Role cenV2Role2 = new CentralV2Role(16l, null, null, null, null, null, "test2", true, null, + new TreeSet<>(), new TreeSet<>(), new TreeSet<>()); + mockCenV2Role.add(cenV2Role); + mockCenV2Role.add(cenV2Role2); + Mockito.when(externalAccessRolesServiceImpl.getRolesForApp(mockApp.getUebKey())).thenReturn(mockCenV2Role); + List<EPUser> mockUserList = new ArrayList<>(); + mockUserList.add(user); + Mockito.when((List<EPUser>) dataAccessService + .executeQuery("from EPUser where orgUserId='" + user.getOrgUserId() + "'", null)) + .thenReturn(mockUserList); + Mockito.when(userRolesCommonServiceImpl.getAppRolesForUser(1l, user.getOrgUserId(), true)) + .thenReturn(mockRoleInAppForUserList); + List<RoleInAppForUser> roleInAppForUser = userRolesCommonServiceImpl.getAppRolesForUser(1l, "test", true); + assertEquals(roleInAppForUser, mockRoleInAppForUserList); + } + + private List<RoleInAppForUser> getMockedRoleInAppUserList() { + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser mockRoleInAppForUser = new RoleInAppForUser(); + mockRoleInAppForUser.setIsApplied(false); + mockRoleInAppForUser.setRoleId(1l); + mockRoleInAppForUser.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(false); + mockRoleInAppForUser2.setRoleId(16l); + mockRoleInAppForUser2.setRoleName("test2"); + mockRoleInAppForUserList.add(mockRoleInAppForUser); + mockRoleInAppForUserList.add(mockRoleInAppForUser2); + return mockRoleInAppForUserList; + } + + @SuppressWarnings("unchecked") + @Test + public void getAppRolesForUserNonCentralizedForPortal() throws Exception { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + EPApp mockApp = mockApp(); + mockApp.setCentralAuth(false); + EPRole mockEPRole = new EPRole(); + mockEPRole.setId(1l); + mockEPRole.setName("test1"); + mockEPRole.setActive(true); + SortedSet<EPUserApp> mockUserApps = new TreeSet<EPUserApp>(); + EPUserApp mockEPUserApp = new EPUserApp(); + mockEPUserApp.setApp(mockApp); + mockEPUserApp.setRole(mockEPRole); + mockEPUserApp.setUserId(1l); + mockUserApps.add(mockEPUserApp); + user.setEPUserApps(mockUserApps); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<RoleInAppForUser> mockRoleInAppForUserListNonCentralizedList = getMockedRoleInAppUserList(); + List<Role> mockRole = new ArrayList<>(); + Role role = new Role(); + role.setId(1l); + role.setName("test1"); + role.setActive(true); + Role role2 = new Role(); + role.setId(16l); + role.setName("test2"); + role.setActive(true); + mockRole.add(role); + mockRole.add(role2); + Mockito.when(roleServiceImpl.getAvailableRoles(user.getOrgUserId())).thenReturn(mockRole); + List<EPUser> mockUserList = new ArrayList<>(); + mockUserList.add(user); + Mockito.when((List<EPUser>) dataAccessService + .executeQuery("from EPUser where orgUserId='" + user.getOrgUserId() + "'", null)) + .thenReturn(mockUserList); + Mockito.when(userRolesCommonServiceImpl.getAppRolesForUser(1l, user.getOrgUserId(), true)) + .thenReturn(mockRoleInAppForUserListNonCentralizedList); + List<RoleInAppForUser> roleInAppForUserNonCentralized = userRolesCommonServiceImpl.getAppRolesForUser(1l, + user.getOrgUserId(), true); + assertNull(roleInAppForUserNonCentralized); + } + + @Test + public void getAppRolesForCentralizedPartnerAppTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + EPApp mockApp = mockApp(); + mockApp.setId(2l); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<RoleInAppForUser> mockRoleInAppForUserList = getMockedRoleInAppUserList(); + List<EPRole> mockEPRoleList = new ArrayList<>(); + EPRole mockEpRole = new EPRole(); + mockEpRole.setActive(true); + mockEpRole.setAppId(2l); + mockEpRole.setName("test1"); + mockEpRole.setAppRoleId(333l); + mockEpRole.setId(1l); + EPRole mockEpRole2 = new EPRole(); + mockEpRole2.setActive(true); + mockEpRole2.setAppId(2l); + mockEpRole2.setName("test2"); + mockEpRole2.setAppRoleId(444l); + mockEpRole2.setId(16l); + mockEPRoleList.add(mockEpRole); + mockEPRoleList.add(mockEpRole2); + final Map<String, Long> appParams = new HashMap<>(); + appParams.put("appId", 2l); + Mockito.when(dataAccessService.executeNamedQuery("getActiveRolesOfApplication", appParams, null)) + .thenReturn(mockEPRoleList); + final Map<String, String> params = new HashMap<>(); + params.put("orgUserIdValue", "guestT"); + List<EPUser> mockEPUserList = new ArrayList<>(); + mockEPUserList.add(user); + Mockito.when(dataAccessService.executeNamedQuery("epUserAppId", params, null)).thenReturn(mockEPUserList); + final Map<String, Long> userParams = new HashMap<>(); + userParams.put("appId", mockApp.getId()); + userParams.put("userId", mockEPUserList.get(0).getId()); + List<EPUserAppCurrentRoles> epUserAppCurrentRolesList = new ArrayList<>(); + EPUserAppCurrentRoles epUserAppCurrentRoles = new EPUserAppCurrentRoles(); + epUserAppCurrentRoles.setRoleId(444l); + epUserAppCurrentRoles.setRoleName("TestPartnerRole2"); + epUserAppCurrentRoles.setUserId(mockEPUserList.get(0).getId()); + epUserAppCurrentRolesList.add(epUserAppCurrentRoles); + Mockito.when(dataAccessService.executeNamedQuery("getUserAppCurrentRoles", userParams, null)) + .thenReturn(epUserAppCurrentRolesList); + Mockito.when(userRolesCommonServiceImpl.getAppRolesForUser(2l, user.getOrgUserId(), true)) + .thenReturn(mockRoleInAppForUserList); + List<RoleInAppForUser> roleInAppForUser = userRolesCommonServiceImpl.getAppRolesForUser(2l, user.getOrgUserId(), + true); + assertEquals(roleInAppForUser, mockRoleInAppForUserList); + } + + @Test + public void getAppRolesForNonCentralizedPartnerAppTest() throws Exception { + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setCentralAuth(false); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser mockRoleInAppForUser = new RoleInAppForUser(); + mockRoleInAppForUser.setIsApplied(true); + mockRoleInAppForUser.setRoleId(333l); + mockRoleInAppForUser.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(777l); + mockRoleInAppForUser2.setRoleName("test2"); + RoleInAppForUser mockRoleInAppForUser3 = new RoleInAppForUser(); + mockRoleInAppForUser3.setIsApplied(false); + mockRoleInAppForUser3.setRoleId(888l); + mockRoleInAppForUser3.setRoleName("test5"); + mockRoleInAppForUserList.add(mockRoleInAppForUser); + mockRoleInAppForUserList.add(mockRoleInAppForUser2); + mockRoleInAppForUserList.add(mockRoleInAppForUser3); + List<EcompRole> mockEcompRoleList = new ArrayList<>(); + EcompRole mockEcompRole = new EcompRole(); + mockEcompRole.setId(333l); + mockEcompRole.setName("test1"); + EcompRole mockEcompRole2 = new EcompRole(); + mockEcompRole2.setId(777l); + mockEcompRole2.setName("test2"); + EcompRole mockEcompRole3 = new EcompRole(); + mockEcompRole3.setId(888l); + mockEcompRole3.setName("test5"); + mockEcompRoleList.add(mockEcompRole); + mockEcompRoleList.add(mockEcompRole2); + mockEcompRoleList.add(mockEcompRole3); + EcompRole[] mockEcompRoleArray = mockEcompRoleList.toArray(new EcompRole[mockEcompRoleList.size()]); + List<EPRole> mockEPRoleList = new ArrayList<>(); + EPRole mockEpRole = new EPRole(); + mockEpRole.setActive(true); + mockEpRole.setAppId(2l); + mockEpRole.setName("test1"); + mockEpRole.setAppRoleId(333l); + mockEpRole.setId(16l); + EPRole mockEpRole2 = new EPRole(); + mockEpRole2.setActive(true); + mockEpRole2.setAppId(2l); + mockEpRole2.setName("test3"); + mockEpRole2.setAppRoleId(555l); + mockEpRole2.setId(15l); + EPRole mockEpRole3 = new EPRole(); + mockEpRole3.setActive(true); + mockEpRole3.setAppId(2l); + mockEpRole3.setName("test4"); + mockEpRole3.setAppRoleId(888l); + mockEpRole3.setId(17l); + mockEPRoleList.add(mockEpRole); + mockEPRoleList.add(mockEpRole2); + mockEPRoleList.add(mockEpRole3); + List<EPUserApp> mockUserRolesList = new ArrayList<>(); + EPUserApp mockEpUserApp = new EPUserApp(); + mockEpUserApp.setApp(mockApp); + mockEpUserApp.setRole(mockEpRole2); + mockEpUserApp.setUserId(user.getId()); + mockUserRolesList.add(mockEpUserApp); + List<FunctionalMenuRole> mockFunctionalMenuRolesList = new ArrayList<>(); + FunctionalMenuRole mockFunctionalMenuRole = new FunctionalMenuRole(); + mockFunctionalMenuRole.setAppId((int) (long) mockApp.getId()); + mockFunctionalMenuRole.setRoleId((int) (long) 15l); + mockFunctionalMenuRole.setMenuId(10l); + mockFunctionalMenuRole.setId(10); + mockFunctionalMenuRolesList.add(mockFunctionalMenuRole); + List<FunctionalMenuItem> mockFunctionalMenuItemList = new ArrayList<>(); + FunctionalMenuItem mockFunctionalMenuItem = new FunctionalMenuItem(); + List<Integer> mockRolesList = new ArrayList<>(); + Integer role1 = 1; + mockRolesList.add(role1); + mockFunctionalMenuItem.setRestrictedApp(false); + mockFunctionalMenuItem.setRoles(mockRolesList); + mockFunctionalMenuItem.setUrl("http://test.com"); + mockFunctionalMenuItemList.add(mockFunctionalMenuItem); + Query epRoleQuery = Mockito.mock(Query.class); + Query epUserAppsQuery = Mockito.mock(Query.class); + Query epFunctionalMenuQuery = Mockito.mock(Query.class); + Query epFunctionalMenuQuery2 = Mockito.mock(Query.class); + Query epFunctionalMenuItemQuery = Mockito.mock(Query.class); + Query epUserListQuery = Mockito.mock(Query.class); + Query epUserRolesListQuery = Mockito.mock(Query.class); + Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), "/roles")) + .thenReturn(mockEcompRoleArray); + // syncAppRolesTest + Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId=" + mockApp.getId())) + .thenReturn(epRoleQuery); + Mockito.doReturn(mockEPRoleList).when(epRoleQuery).list(); + Mockito.when(session.createQuery( + "from " + EPUserApp.class.getName() + " where app.id=" + mockApp.getId() + " and role_id=" + 15l)) + .thenReturn(epUserAppsQuery); + Mockito.doReturn(mockUserRolesList).when(epUserAppsQuery).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + 15l)) + .thenReturn(epFunctionalMenuQuery); + Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + 10l)) + .thenReturn(epFunctionalMenuQuery2); + Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery2).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuItem.class.getName() + " where menuId=" + 10l)) + .thenReturn(epFunctionalMenuItemQuery); + Mockito.doReturn(mockFunctionalMenuItemList).when(epFunctionalMenuItemQuery).list(); + List<EcompRole> mockEcompRoleList2 = new ArrayList<>(); + EcompRole mockUserAppRoles = new EcompRole(); + mockUserAppRoles.setId(333l); + mockUserAppRoles.setName("test1"); + EcompRole mockUserAppRoles2 = new EcompRole(); + mockUserAppRoles2.setId(777l); + mockUserAppRoles2.setName("test2"); + mockEcompRoleList2.add(mockUserAppRoles); + mockEcompRoleList2.add(mockUserAppRoles2); + EcompRole[] mockEcompRoleArray2 = mockEcompRoleList2.toArray(new EcompRole[mockEcompRoleList2.size()]); + Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), + String.format("/user/%s/roles", user.getOrgUserId()))).thenReturn(mockEcompRoleArray2); + // SyncUserRoleTest + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epUserListQuery); + Mockito.doReturn(mockEpUserList).when(epUserListQuery).list(); + + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEpRole3); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=2 and role.active = 'Y' and userId=2")) + .thenReturn(epUserRolesListQuery); + Mockito.doReturn(mockUserRolesList2).when(epUserRolesListQuery).list(); + List<RoleInAppForUser> roleInAppForUser = userRolesCommonServiceImpl.getAppRolesForUser(2l, user.getOrgUserId(), + true); + assertEquals(roleInAppForUser, mockRoleInAppForUserList); + } + + @SuppressWarnings("unchecked") + @Test + public void setAppWithUserRoleStateForUserTestForCentralizedAppForPortal() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(PortalConstants.class); + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setNameSpace("com.test.com"); + mockApp.setId(1l); + mockApp.setCentralAuth(true); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + AppWithRolesForUser mockWithRolesForUser = new AppWithRolesForUser(); + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser mockRoleInAppForUser = new RoleInAppForUser(); + mockRoleInAppForUser.setIsApplied(true); + mockRoleInAppForUser.setRoleId(1l); + mockRoleInAppForUser.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(1000l); + mockRoleInAppForUser2.setRoleName("test3"); + mockRoleInAppForUserList.add(mockRoleInAppForUser); + mockRoleInAppForUserList.add(mockRoleInAppForUser2); + mockWithRolesForUser.setAppId(mockApp.getId()); + mockWithRolesForUser.setAppName(mockApp.getName()); + mockWithRolesForUser.setOrgUserId(user.getOrgUserId()); + mockWithRolesForUser.setAppRoles(mockRoleInAppForUserList); + List<EPUserAppRolesRequest> mockEpRequestIdValList = new ArrayList<EPUserAppRolesRequest>(); + Set<EPUserAppRolesRequestDetail> mockEpUserAppRolesRequestDetailList = new TreeSet<>(); + EPUserAppRolesRequestDetail mockEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + EPUserAppRolesRequest mockEPUserAppRolesRequest = new EPUserAppRolesRequest(); + mockEPUserAppRolesRequest.setAppId(mockApp.getId()); + mockEPUserAppRolesRequest.setId(1l); + mockEPUserAppRolesRequest.setRequestStatus("P"); + mockEPUserAppRolesRequest.setUserId(user.getId()); + mockEPUserAppRolesRequest.setEpRequestIdDetail(mockEpUserAppRolesRequestDetailList); + mockEpRequestIdValList.add(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetail.setEpRequestIdData(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetailList.add(mockEpUserAppRolesRequestDetail); + + // Update Requests if any requests are pending + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + Mockito.when((List<EPUserAppRolesRequest>) dataAccessService.executeNamedQuery("userAppRolesRequestList", + params, null)).thenReturn(mockEpRequestIdValList); + mockEPUserAppRolesRequest.setUpdatedDate(new Date()); + mockEPUserAppRolesRequest.setRequestStatus("O"); + HashMap<String, Long> additionalUpdateParam = new HashMap<String, Long>(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEPUserAppRolesRequest, additionalUpdateParam); + List<EPUserAppRolesRequestDetail> mockGetEpUserAppRolesRequestDetailList = new ArrayList<EPUserAppRolesRequestDetail>(); + EPUserAppRolesRequestDetail mockGetEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + mockGetEpUserAppRolesRequestDetailList.add(mockGetEpUserAppRolesRequestDetail); + // Updates in External Auth System + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams, null)) + .thenReturn(mockEpUserList); + PowerMockito + .when(EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + PowerMockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObject1 = new JSONObject(); + JSONObject mockJsonObject2 = new JSONObject(); + JSONObject mockJsonObject3 = new JSONObject(); + mockJsonObject1.put("name", "com.test.com.test1"); + mockJsonObject2.put("name", "com.test.com.test2"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObject1); + mockJson.add(mockJsonObject2); + mockJsonObject3.put("role", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObject3.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + EPRole mockEPRole = new EPRole(); + mockEPRole.setActive(true); + mockEPRole.setAppId(null); + mockEPRole.setAppRoleId(null); + mockEPRole.setId(1l); + mockEPRole.setName("test1"); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setActive(true); + mockEPRole2.setAppId(null); + mockEPRole2.setAppRoleId(null); + mockEPRole2.setId(16l); + mockEPRole2.setName("test2"); + EPRole mockEPRole3 = new EPRole(); + mockEPRole3.setActive(true); + mockEPRole3.setAppId(null); + mockEPRole3.setAppRoleId(null); + mockEPRole3.setId(1000l); + mockEPRole3.setName("test3"); + Map<String, EPRole> mockEPRoleList = new HashMap<>(); + mockEPRoleList.put("test1", mockEPRole); + mockEPRoleList.put("test2", mockEPRole2); + mockEPRoleList.put("test3", mockEPRole3); + Mockito.when(externalAccessRolesServiceImpl.getCurrentRolesInDB(mockApp)).thenReturn(mockEPRoleList); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("appId", mockApp.getId()); + params2.put("userId", user.getId()); + List<EcompUserAppRoles> mockEPuserAppList = getCurrentUserRoles(user, mockApp); + Mockito.when(dataAccessService.executeNamedQuery("getUserAppExistingRoles", params2, null)) + .thenReturn(mockEPuserAppList); + final Map<String, Long> epDetailParams = new HashMap<>(); + epDetailParams.put("reqId", mockEPUserAppRolesRequest.getId()); + Mockito.when(dataAccessService.executeNamedQuery("userAppRolesRequestDetailList", epDetailParams, null)) + .thenReturn(mockGetEpUserAppRolesRequestDetailList); + + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + + ResponseEntity<String> deleteResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(deleteResponse); + + // Updates in EP DB + Query epsetAppWithUserRoleGetUserQuery = Mockito.mock(Query.class); + Query epsetAppWithUserRoleGetUserAppsQuery = Mockito.mock(Query.class); + Query epsetAppWithUserRoleGetRolesQuery = Mockito.mock(Query.class); + SQLQuery epsetAppWithUserRoleUpdateEPRoleQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.get(EPApp.class, mockApp.getId())).thenReturn(mockApp); + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epsetAppWithUserRoleGetUserQuery); + Mockito.doReturn(mockEpUserList).when(epsetAppWithUserRoleGetUserQuery).list(); + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEPRole); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=1 and role.active = 'Y' and userId=2")) + .thenReturn(epsetAppWithUserRoleGetUserAppsQuery); + Mockito.doReturn(mockUserRolesList2).when(epsetAppWithUserRoleGetUserAppsQuery).list(); + List<EPRole> mockEPRoles = new ArrayList<>(); + mockEPRoles.add(mockEPRole2); + mockEPRoles.add(mockEPRole3); + Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId is null and id != 1")) + .thenReturn(epsetAppWithUserRoleGetRolesQuery); + Mockito.doReturn(mockEPRoles).when(epsetAppWithUserRoleGetRolesQuery).list(); + Mockito.when(session.createSQLQuery("update fn_role set app_id = null where app_id = 1 ")) + .thenReturn(epsetAppWithUserRoleUpdateEPRoleQuery); + boolean actual = userRolesCommonServiceImpl.setAppWithUserRoleStateForUser(user, mockWithRolesForUser); + assertTrue(actual); + } + + private List<EcompUserAppRoles> getCurrentUserRoles(EPUser user, EPApp mockApp) { + List<EcompUserAppRoles> mockEPuserAppList = new ArrayList<>(); + EcompUserAppRoles mockEcompUserAppRoles = new EcompUserAppRoles(); + mockEcompUserAppRoles.setAppId(String.valueOf(mockApp.getId())); + mockEcompUserAppRoles.setRoleId(1l); + mockEcompUserAppRoles.setRoleName("test1"); + mockEcompUserAppRoles.setUserId(user.getId()); + mockEPuserAppList.add(mockEcompUserAppRoles); + return mockEPuserAppList; + } + + @SuppressWarnings("unchecked") + @Test + public void setAppWithUserRoleStateForUserTestForNonCentralizedApp() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(PortalConstants.class); + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setNameSpace("com.test.com"); + mockApp.setId(2l); + mockApp.setCentralAuth(false); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + AppWithRolesForUser mockWithRolesForUser = new AppWithRolesForUser(); + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser mockRoleInAppForUser = new RoleInAppForUser(); + mockRoleInAppForUser.setIsApplied(true); + mockRoleInAppForUser.setRoleId(1l); + mockRoleInAppForUser.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(1000l); + mockRoleInAppForUser2.setRoleName("test3"); + mockRoleInAppForUserList.add(mockRoleInAppForUser); + mockRoleInAppForUserList.add(mockRoleInAppForUser2); + mockWithRolesForUser.setAppId(mockApp.getId()); + mockWithRolesForUser.setAppName(mockApp.getName()); + mockWithRolesForUser.setOrgUserId(user.getOrgUserId()); + mockWithRolesForUser.setAppRoles(mockRoleInAppForUserList); + List<EPUserAppRolesRequest> mockEpRequestIdValList = new ArrayList<EPUserAppRolesRequest>(); + Set<EPUserAppRolesRequestDetail> mockEpUserAppRolesRequestDetailList = new TreeSet<>(); + EPUserAppRolesRequestDetail mockEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + EPUserAppRolesRequest mockEPUserAppRolesRequest = new EPUserAppRolesRequest(); + mockEPUserAppRolesRequest.setAppId(mockApp.getId()); + mockEPUserAppRolesRequest.setId(1l); + mockEPUserAppRolesRequest.setRequestStatus("P"); + mockEPUserAppRolesRequest.setUserId(user.getId()); + mockEPUserAppRolesRequest.setEpRequestIdDetail(mockEpUserAppRolesRequestDetailList); + mockEpRequestIdValList.add(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetail.setEpRequestIdData(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetailList.add(mockEpUserAppRolesRequestDetail); + + // Update Requests if any requests are pending + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + Mockito.when((List<EPUserAppRolesRequest>) dataAccessService.executeNamedQuery("userAppRolesRequestList", + params, null)).thenReturn(mockEpRequestIdValList); + mockEPUserAppRolesRequest.setUpdatedDate(new Date()); + mockEPUserAppRolesRequest.setRequestStatus("O"); + HashMap<String, Long> additionalUpdateParam = new HashMap<String, Long>(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEPUserAppRolesRequest, additionalUpdateParam); + List<EPUserAppRolesRequestDetail> mockGetEpUserAppRolesRequestDetailList = new ArrayList<EPUserAppRolesRequestDetail>(); + EPUserAppRolesRequestDetail mockGetEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + mockGetEpUserAppRolesRequestDetailList.add(mockGetEpUserAppRolesRequestDetail); + final Map<String, Long> epDetailParams = new HashMap<>(); + epDetailParams.put("reqId", mockEPUserAppRolesRequest.getId()); + + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams, null)) + .thenReturn(mockEpUserList); + + PowerMockito + .when(EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + PowerMockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + EPRole mockEPRole = new EPRole(); + mockEPRole.setActive(true); + mockEPRole.setAppId(2l); + mockEPRole.setAppRoleId(null); + mockEPRole.setId(10l); + mockEPRole.setAppRoleId(1l); + mockEPRole.setName("test1"); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setActive(true); + mockEPRole2.setAppId(2l); + mockEPRole2.setAppRoleId(null); + mockEPRole2.setId(160l); + mockEPRole2.setName("test2"); + mockEPRole2.setAppRoleId(16l); + EPRole mockEPRole3 = new EPRole(); + mockEPRole3.setActive(true); + mockEPRole3.setAppId(2l); + mockEPRole3.setAppRoleId(null); + mockEPRole3.setId(1100l); + mockEPRole3.setAppRoleId(100l); + mockEPRole3.setName("test3"); + Mockito.when(applicationsRestClientService.get(EPUser.class, mockApp.getId(), + String.format("/user/%s", user.getOrgUserId()), true)).thenReturn(user); + // Updates in EP DB + Query epsetAppWithUserRoleNonCentralizedGetUserQuery = Mockito.mock(Query.class); + Query epsetAppWithUserRoleNonCentralizedGetUserAppsQuery = Mockito.mock(Query.class); + Query epsetAppWithUserRoleNonCentralizedGetRolesQuery = Mockito.mock(Query.class); + Mockito.when(session.get(EPApp.class, mockApp.getId())).thenReturn(mockApp); + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epsetAppWithUserRoleNonCentralizedGetUserQuery); + Mockito.doReturn(mockEpUserList).when(epsetAppWithUserRoleNonCentralizedGetUserQuery).list(); + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEPRole); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=2 and role.active = 'Y' and userId=2")) + .thenReturn(epsetAppWithUserRoleNonCentralizedGetUserAppsQuery); + Mockito.doReturn(mockUserRolesList2).when(epsetAppWithUserRoleNonCentralizedGetUserAppsQuery).list(); + List<EPRole> mockEPRoles = new ArrayList<>(); + mockEPRoles.add(mockEPRole2); + mockEPRoles.add(mockEPRole3); + Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId=2")) + .thenReturn(epsetAppWithUserRoleNonCentralizedGetRolesQuery); + Mockito.doReturn(mockEPRoles).when(epsetAppWithUserRoleNonCentralizedGetRolesQuery).list(); + boolean expected = userRolesCommonServiceImpl.setAppWithUserRoleStateForUser(user, mockWithRolesForUser); + assertEquals(expected, true); + } + + @SuppressWarnings("unchecked") + @Test + public void setExternalRequestUserAppRoleMerdianCentralizedAppTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EcompPortalUtils.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(PortalConstants.class); + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setNameSpace("com.test.com"); + mockApp.setId(1l); + mockApp.setCentralAuth(true); + Mockito.when(EcompPortalUtils.checkIfRemoteCentralAccessAllowed()).thenReturn(true); + ExternalSystemUser externalSystemUser = new ExternalSystemUser(); + List<ExternalSystemRoleApproval> mockExternalSystemRoleApprovalList = new ArrayList<>(); + ExternalSystemRoleApproval mockExternalSystemRoleApproval = new ExternalSystemRoleApproval(); + mockExternalSystemRoleApproval.setRoleName("test1"); + ExternalSystemRoleApproval mockExternalSystemRoleApproval2 = new ExternalSystemRoleApproval(); + mockExternalSystemRoleApproval2.setRoleName("test2"); + mockExternalSystemRoleApprovalList.add(mockExternalSystemRoleApproval); + mockExternalSystemRoleApprovalList.add(mockExternalSystemRoleApproval2); + externalSystemUser.setApplicationName(mockApp.getMlAppName()); + externalSystemUser.setLoginId(user.getOrgUserId()); + externalSystemUser.setRoles(mockExternalSystemRoleApprovalList); + EPRole mockEPRole = new EPRole(); + mockEPRole.setActive(true); + mockEPRole.setAppId(null); + mockEPRole.setAppRoleId(null); + mockEPRole.setId(1l); + mockEPRole.setName("test1"); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setActive(true); + mockEPRole2.setAppId(null); + mockEPRole2.setAppRoleId(null); + mockEPRole2.setId(16l); + mockEPRole2.setName("test2"); + EPRole mockEPRole3 = new EPRole(); + mockEPRole3.setActive(true); + mockEPRole3.setAppId(null); + mockEPRole3.setAppRoleId(null); + mockEPRole3.setId(1000l); + mockEPRole3.setName("test3"); + + Mockito.when(epAppCommonServiceImpl.getAppDetail(mockApp.getMlAppName())).thenReturn(mockApp); + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams, null)) + .thenReturn(mockEpUserList); + + List<EPUserAppRolesRequest> mockMerdianEpRequestIdValList = new ArrayList<EPUserAppRolesRequest>(); + Set<EPUserAppRolesRequestDetail> mockEpUserAppRolesRequestDetailList = new TreeSet<>(); + EPUserAppRolesRequestDetail mockEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + EPUserAppRolesRequest mockEPUserAppRolesRequest = new EPUserAppRolesRequest(); + mockEPUserAppRolesRequest.setAppId(mockApp.getId()); + mockEPUserAppRolesRequest.setId(1l); + mockEPUserAppRolesRequest.setRequestStatus("P"); + mockEPUserAppRolesRequest.setUserId(user.getId()); + mockEPUserAppRolesRequest.setEpRequestIdDetail(mockEpUserAppRolesRequestDetailList); + mockMerdianEpRequestIdValList.add(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetail.setEpRequestIdData(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetailList.add(mockEpUserAppRolesRequestDetail); + + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + Mockito.when((List<EPUserAppRolesRequest>) dataAccessService.executeNamedQuery("userAppRolesRequestList", + params, null)).thenReturn(mockMerdianEpRequestIdValList); + RoleInAppForUser mockRoleInAppForUser1 = new RoleInAppForUser(); + mockRoleInAppForUser1.setIsApplied(true); + mockRoleInAppForUser1.setRoleId(1l); + mockRoleInAppForUser1.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(16l); + mockRoleInAppForUser2.setRoleName("test2"); + Mockito.when(epRoleServiceImpl.getAppRole(mockExternalSystemRoleApproval.getRoleName(), mockApp.getId())) + .thenReturn(mockEPRole); + Mockito.when(epRoleServiceImpl.getAppRole(mockExternalSystemRoleApproval2.getRoleName(), mockApp.getId())) + .thenReturn(mockEPRole2); + List<EcompUserAppRoles> mockEPuserAppList = getCurrentUserRoles(user, mockApp); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("userId", user.getId()); + params2.put("appId", mockApp.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getUserAppExistingRoles", params2, null)) + .thenReturn(mockEPuserAppList); + // Updates in External Auth System + List<EPUserAppRolesRequestDetail> mockGetEpUserAppRolesRequestDetailList = new ArrayList<EPUserAppRolesRequestDetail>(); + EPUserAppRolesRequestDetail mockGetEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + mockGetEpUserAppRolesRequestDetailList.add(mockGetEpUserAppRolesRequestDetail); + final Map<String, String> userParams2 = new HashMap<>(); + userParams2.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams2, null)) + .thenReturn(mockEpUserList); + PowerMockito + .when(EPCommonSystemProperties + .containsProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn(true); + PowerMockito.when(SystemProperties.getProperty(EPCommonSystemProperties.EXTERNAL_CENTRAL_ACCESS_USER_DOMAIN)) + .thenReturn("@test.com"); + HttpHeaders headers = new HttpHeaders(); + Mockito.when(EcompPortalUtils.base64encodeKeyForAAFBasicAuth()).thenReturn(headers); + JSONObject mockJsonObject1 = new JSONObject(); + JSONObject mockJsonObject2 = new JSONObject(); + JSONObject mockJsonObject3 = new JSONObject(); + mockJsonObject1.put("name", "com.test.com.test1"); + mockJsonObject2.put("name", "com.test.com.test2"); + List<JSONObject> mockJson = new ArrayList<>(); + mockJson.add(mockJsonObject1); + mockJson.add(mockJsonObject2); + mockJsonObject3.put("role", mockJson); + ResponseEntity<String> getResponse = new ResponseEntity<>(mockJsonObject3.toString(), HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.GET), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(getResponse); + Map<String, EPRole> mockEPRoleList = new HashMap<>(); + mockEPRoleList.put("test1", mockEPRole); + mockEPRoleList.put("test2", mockEPRole2); + mockEPRoleList.put("test3", mockEPRole3); + Mockito.when(externalAccessRolesServiceImpl.getCurrentRolesInDB(mockApp)).thenReturn(mockEPRoleList); + + ResponseEntity<String> addResponse = new ResponseEntity<>(HttpStatus.CREATED); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.POST), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(addResponse); + + ResponseEntity<String> deleteResponse = new ResponseEntity<>(HttpStatus.OK); + Mockito.when(template.exchange(Matchers.anyString(), Matchers.eq(HttpMethod.DELETE), + Matchers.<HttpEntity<String>>any(), Matchers.eq(String.class))).thenReturn(deleteResponse); + // Updated in EP DB + Query epsetExternalRequestUserAppRoleGetUserQuery = Mockito.mock(Query.class); + Query epsetExternalRequestUserAppRoleGetUserAppsQuery = Mockito.mock(Query.class); + Query epsetExternalRequestUserAppRoleGetRolesQuery = Mockito.mock(Query.class); + SQLQuery epsetAppWithUserRoleUpdateEPRoleQuery = Mockito.mock(SQLQuery.class); + Mockito.when(session.get(EPApp.class, mockApp.getId())).thenReturn(mockApp); + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epsetExternalRequestUserAppRoleGetUserQuery); + Mockito.doReturn(mockEpUserList).when(epsetExternalRequestUserAppRoleGetUserQuery).list(); + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEPRole); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=1 and role.active = 'Y' and userId=2")) + .thenReturn(epsetExternalRequestUserAppRoleGetUserAppsQuery); + Mockito.doReturn(mockUserRolesList2).when(epsetExternalRequestUserAppRoleGetUserAppsQuery).list(); + List<EPRole> mockEPRoles = new ArrayList<>(); + mockEPRoles.add(mockEPRole2); + mockEPRoles.add(mockEPRole3); + Mockito.when(session.createQuery("from org.onap.portalapp.portal.domain.EPRole where appId is null ")) + .thenReturn(epsetExternalRequestUserAppRoleGetRolesQuery); + Mockito.doReturn(mockEPRoles).when(epsetExternalRequestUserAppRoleGetRolesQuery).list(); + Mockito.when(session.createSQLQuery("update fn_role set app_id = null where app_id = 1 ")) + .thenReturn(epsetAppWithUserRoleUpdateEPRoleQuery); + + ExternalRequestFieldsValidator mockExternalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, + "Updated Successfully"); + ExternalRequestFieldsValidator externalRequestFieldsValidator = userRolesCommonServiceImpl + .setExternalRequestUserAppRole(externalSystemUser, "POST"); + assertTrue(mockExternalRequestFieldsValidator.equals(externalRequestFieldsValidator)); + } + + @SuppressWarnings("unchecked") + @Test + public void setExternalRequestUserAppRoleMerdianNonCentralizedAppTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + PowerMockito.mockStatic(EPCommonSystemProperties.class); + PowerMockito.mockStatic(PortalConstants.class); + EPUser user = mockUser.mockEPUser(); + user.setId(2l); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + ExternalSystemUser externalSystemUser = new ExternalSystemUser(); + List<ExternalSystemRoleApproval> mockExternalSystemRoleApprovalList = new ArrayList<>(); + ExternalSystemRoleApproval mockExternalSystemRoleApproval = new ExternalSystemRoleApproval(); + mockExternalSystemRoleApproval.setRoleName("test1"); + ExternalSystemRoleApproval mockExternalSystemRoleApproval2 = new ExternalSystemRoleApproval(); + mockExternalSystemRoleApproval2.setRoleName("test2"); + mockExternalSystemRoleApprovalList.add(mockExternalSystemRoleApproval); + mockExternalSystemRoleApprovalList.add(mockExternalSystemRoleApproval2); + externalSystemUser.setApplicationName(mockApp.getMlAppName()); + externalSystemUser.setLoginId(user.getOrgUserId()); + externalSystemUser.setRoles(mockExternalSystemRoleApprovalList); + + EPRole mockEPRole = new EPRole(); + mockEPRole.setActive(true); + mockEPRole.setAppId(2l); + mockEPRole.setAppRoleId(1l); + mockEPRole.setId(1000l); + mockEPRole.setName("test1"); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setActive(true); + mockEPRole2.setAppId(2l); + mockEPRole2.setAppRoleId(16l); + mockEPRole2.setId(160l); + mockEPRole2.setName("test2"); + EPRole mockEPRole3 = new EPRole(); + mockEPRole3.setActive(true); + mockEPRole3.setAppId(2l); + mockEPRole3.setAppRoleId(10l); + mockEPRole3.setId(100l); + mockEPRole3.setName("test3"); + + Mockito.when(epAppCommonServiceImpl.getAppDetail(mockApp.getMlAppName())).thenReturn(mockApp); + final Map<String, String> userParams = new HashMap<>(); + userParams.put("orgUserIdValue", user.getOrgUserId()); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("epUserAppId", userParams, null)) + .thenReturn(mockEpUserList); + + List<EPUserAppRolesRequest> mockMerdianEpRequestIdValList = new ArrayList<EPUserAppRolesRequest>(); + Set<EPUserAppRolesRequestDetail> mockEpUserAppRolesRequestDetailList = new TreeSet<>(); + EPUserAppRolesRequestDetail mockEpUserAppRolesRequestDetail = new EPUserAppRolesRequestDetail(); + mockEpUserAppRolesRequestDetail.setId(2l); + mockEpUserAppRolesRequestDetail.setReqType("P"); + mockEpUserAppRolesRequestDetail.setReqRoleId(16l); + EPUserAppRolesRequest mockEPUserAppRolesRequest = new EPUserAppRolesRequest(); + mockEPUserAppRolesRequest.setAppId(mockApp.getId()); + mockEPUserAppRolesRequest.setId(1l); + mockEPUserAppRolesRequest.setRequestStatus("P"); + mockEPUserAppRolesRequest.setUserId(user.getId()); + mockEPUserAppRolesRequest.setEpRequestIdDetail(mockEpUserAppRolesRequestDetailList); + mockMerdianEpRequestIdValList.add(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetail.setEpRequestIdData(mockEPUserAppRolesRequest); + mockEpUserAppRolesRequestDetailList.add(mockEpUserAppRolesRequestDetail); + + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + Mockito.when((List<EPUserAppRolesRequest>) dataAccessService.executeNamedQuery("userAppRolesRequestList", + params, null)).thenReturn(mockMerdianEpRequestIdValList); + RoleInAppForUser mockRoleInAppForUser1 = new RoleInAppForUser(); + mockRoleInAppForUser1.setIsApplied(true); + mockRoleInAppForUser1.setRoleId(1l); + mockRoleInAppForUser1.setRoleName("test1"); + RoleInAppForUser mockRoleInAppForUser2 = new RoleInAppForUser(); + mockRoleInAppForUser2.setIsApplied(true); + mockRoleInAppForUser2.setRoleId(16l); + mockRoleInAppForUser2.setRoleName("test2"); + Mockito.when(epRoleServiceImpl.getAppRole(mockExternalSystemRoleApproval.getRoleName(), mockApp.getId())) + .thenReturn(mockEPRole); + Mockito.when(epRoleServiceImpl.getAppRole(mockExternalSystemRoleApproval2.getRoleName(), mockApp.getId())) + .thenReturn(mockEPRole2); + List<EcompUserAppRoles> mockEPuserAppList = new ArrayList<>(); + EcompUserAppRoles mockEcompUserAppRoles = new EcompUserAppRoles(); + mockEcompUserAppRoles.setAppId(String.valueOf(mockApp.getId())); + mockEcompUserAppRoles.setRoleId(100l); + mockEcompUserAppRoles.setRoleName("test1"); + mockEcompUserAppRoles.setUserId(user.getId()); + mockEPuserAppList.add(mockEcompUserAppRoles); + final Map<String, Long> params2 = new HashMap<>(); + params2.put("userId", user.getId()); + params2.put("appId", mockApp.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getUserAppExistingRoles", params2, null)) + .thenReturn(mockEPuserAppList); + List<EcompRole> mockEcompRoleList = new ArrayList<>(); + EcompRole mockEcompRole = new EcompRole(); + mockEcompRole.setId(1l); + mockEcompRole.setName("test1"); + EcompRole mockEcompRole2 = new EcompRole(); + mockEcompRole2.setId(16l); + mockEcompRole2.setName("test2"); + mockEcompRoleList.add(mockEcompRole); + mockEcompRoleList.add(mockEcompRole2); + EcompRole[] mockEcompRoleArray = mockEcompRoleList.toArray(new EcompRole[mockEcompRoleList.size()]); + Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), "/roles")) + .thenReturn(mockEcompRoleArray); + + // SyncAppRoles + List<EPUserApp> mockUserRolesList = new ArrayList<>(); + EPUserApp mockEpUserApp = new EPUserApp(); + mockEpUserApp.setApp(mockApp); + mockEpUserApp.setRole(mockEPRole2); + mockEpUserApp.setUserId(user.getId()); + mockUserRolesList.add(mockEpUserApp); + List<FunctionalMenuRole> mockFunctionalMenuRolesList = new ArrayList<>(); + FunctionalMenuRole mockFunctionalMenuRole = new FunctionalMenuRole(); + mockFunctionalMenuRole.setAppId((int) (long) mockApp.getId()); + mockFunctionalMenuRole.setRoleId((int) (long) 15l); + mockFunctionalMenuRole.setMenuId(10l); + mockFunctionalMenuRole.setId(10); + mockFunctionalMenuRolesList.add(mockFunctionalMenuRole); + List<FunctionalMenuItem> mockFunctionalMenuItemList = new ArrayList<>(); + FunctionalMenuItem mockFunctionalMenuItem = new FunctionalMenuItem(); + List<Integer> mockRolesList = new ArrayList<>(); + Integer role1 = 1; + mockRolesList.add(role1); + mockFunctionalMenuItem.setRestrictedApp(false); + mockFunctionalMenuItem.setRoles(mockRolesList); + mockFunctionalMenuItem.setUrl("http://test.com"); + mockFunctionalMenuItemList.add(mockFunctionalMenuItem); + Query epRoleQuery = Mockito.mock(Query.class); + Query epUserAppsQuery = Mockito.mock(Query.class); + Query epFunctionalMenuQuery = Mockito.mock(Query.class); + Query epFunctionalMenuQuery2 = Mockito.mock(Query.class); + Query epFunctionalMenuItemQuery = Mockito.mock(Query.class); + Mockito.when(applicationsRestClientService.get(EcompRole[].class, mockApp.getId(), "/roles")) + .thenReturn(mockEcompRoleArray); + // syncAppRolesTest + Mockito.when(session.createQuery("from " + EPRole.class.getName() + " where appId=" + mockApp.getId())) + .thenReturn(epRoleQuery); + Mockito.doReturn(mockEcompRoleList).when(epRoleQuery).list(); + Mockito.when(session.createQuery( + "from " + EPUserApp.class.getName() + " where app.id=" + mockApp.getId() + " and role_id=" + 100l)) + .thenReturn(epUserAppsQuery); + Mockito.doReturn(mockUserRolesList).when(epUserAppsQuery).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where roleId=" + 100l)) + .thenReturn(epFunctionalMenuQuery); + Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuRole.class.getName() + " where menuId=" + 10l)) + .thenReturn(epFunctionalMenuQuery2); + Mockito.doReturn(mockFunctionalMenuRolesList).when(epFunctionalMenuQuery2).list(); + + Mockito.when(session.createQuery("from " + FunctionalMenuItem.class.getName() + " where menuId=" + 10l)) + .thenReturn(epFunctionalMenuItemQuery); + Mockito.doReturn(mockFunctionalMenuItemList).when(epFunctionalMenuItemQuery).list(); + + Mockito.when(applicationsRestClientService.get(EPUser.class, mockApp.getId(), + String.format("/user/%s", user.getOrgUserId()), true)).thenReturn(user); + // Updated in EP DB + Query epsetExternalRequestUserAppRoleGetUserQuery = Mockito.mock(Query.class); + Query epsetExternalRequestUserAppRoleGetUserAppsQuery = Mockito.mock(Query.class); + Query epsetExternalRequestUserAppRoleGetRolesQuery = Mockito.mock(Query.class); + Mockito.when(session.get(EPApp.class, mockApp.getId())).thenReturn(mockApp); + Mockito.when(session + .createQuery("from " + EPUser.class.getName() + " where orgUserId='" + user.getOrgUserId() + "'")) + .thenReturn(epsetExternalRequestUserAppRoleGetUserQuery); + Mockito.doReturn(mockEpUserList).when(epsetExternalRequestUserAppRoleGetUserQuery).list(); + List<EPUserApp> mockUserRolesList2 = new ArrayList<>(); + EPUserApp mockEpUserAppRoles = new EPUserApp(); + mockEpUserAppRoles.setApp(mockApp); + mockEpUserAppRoles.setRole(mockEPRole); + mockEpUserAppRoles.setUserId(user.getId()); + mockUserRolesList2.add(mockEpUserAppRoles); + Mockito.when(session.createQuery( + "from org.onap.portalapp.portal.domain.EPUserApp where app.id=2 and role.active = 'Y' and userId=2")) + .thenReturn(epsetExternalRequestUserAppRoleGetUserAppsQuery); + Mockito.doReturn(mockUserRolesList2).when(epsetExternalRequestUserAppRoleGetUserAppsQuery).list(); + List<EPRole> mockEPRoles = new ArrayList<>(); + mockEPRoles.add(mockEPRole2); + mockEPRoles.add(mockEPRole3); + Mockito.when(session.createQuery("from org.onap.portalapp.portal.domain.EPRole where appId=2")) + .thenReturn(epsetExternalRequestUserAppRoleGetRolesQuery); + Mockito.doReturn(mockEPRoles).when(epsetExternalRequestUserAppRoleGetRolesQuery).list(); + + ExternalRequestFieldsValidator mockExternalRequestFieldsValidator = new ExternalRequestFieldsValidator(true, + "Updated Successfully"); + ExternalRequestFieldsValidator externalRequestFieldsValidator = userRolesCommonServiceImpl + .setExternalRequestUserAppRole(externalSystemUser, "POST"); + assertTrue(mockExternalRequestFieldsValidator.equals(externalRequestFieldsValidator)); + } + + @SuppressWarnings("unchecked") + @Test + public void getUsersFromAppEndpointCentralizedAppTest() throws HTTPException { + EPApp mockApp = mockApp(); + mockApp.setId(1l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(true); + EPUser user = mockUser.mockEPUser(); + EPUser user2 = mockUser.mockEPUser(); + user2.setActive(true); + user2.setOrgUserId("guestT2"); + user2.setId(2l); + user2.setFirstName("Guest2"); + user2.setLastName("Test2"); + user.setId(1l); + user.setFirstName("Guest"); + user.setLastName("Test"); + EPRole mockEPRole1 = new EPRole(); + mockEPRole1.setId(1l); + mockEPRole1.setName("test1"); + mockEPRole1.setActive(true); + EPRole mockEPRole2 = new EPRole(); + mockEPRole2.setId(16l); + mockEPRole2.setName("test2"); + mockEPRole2.setActive(true); + SortedSet<EPUserApp> mockUserApps1 = new TreeSet<EPUserApp>(); + EPUserApp mockEPUserApp1 = new EPUserApp(); + mockEPUserApp1.setApp(mockApp); + mockEPUserApp1.setRole(mockEPRole1); + mockEPUserApp1.setUserId(1l); + mockUserApps1.add(mockEPUserApp1); + user.setEPUserApps(mockUserApps1); + SortedSet<EPUserApp> mockUserApps2 = new TreeSet<EPUserApp>(); + EPUserApp mockEPUserApp2 = new EPUserApp(); + mockEPUserApp2.setApp(mockApp); + mockEPUserApp2.setRole(mockEPRole2); + mockEPUserApp2.setUserId(2l); + mockUserApps2.add(mockEPUserApp2); + user2.setEPUserApps(mockUserApps2); + List<EPUser> mockEpUserList = new ArrayList<>(); + mockEpUserList.add(user); + mockEpUserList.add(user2); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<UserApplicationRoles> mockUserApplicationRolesList = new ArrayList<>(); + UserApplicationRoles mockUserApplicationRoles = new UserApplicationRoles(); + List<RemoteRole> mockRemoteRoleList = new ArrayList<>(); + RemoteRole mockRemoteRole = new RemoteRole(); + mockRemoteRole.setId(1l); + mockRemoteRole.setName("test1"); + mockRemoteRoleList.add(mockRemoteRole); + mockUserApplicationRoles.setAppId(mockApp.getId()); + mockUserApplicationRoles.setFirstName("Guest"); + mockUserApplicationRoles.setLastName("Test"); + mockUserApplicationRoles.setOrgUserId("guestT"); + mockUserApplicationRoles.setRoles(mockRemoteRoleList); + UserApplicationRoles mockUserApplicationRoles2 = new UserApplicationRoles(); + List<RemoteRole> mockRemoteRoleList2 = new ArrayList<>(); + RemoteRole mockRemoteRole2 = new RemoteRole(); + mockRemoteRole2.setId(16l); + mockRemoteRole2.setName("test2"); + mockRemoteRoleList2.add(mockRemoteRole2); + mockUserApplicationRoles2.setAppId(mockApp.getId()); + mockUserApplicationRoles2.setFirstName("Guest2"); + mockUserApplicationRoles2.setLastName("Test2"); + mockUserApplicationRoles2.setOrgUserId("guestT2"); + mockUserApplicationRoles2.setRoles(mockRemoteRoleList2); + mockUserApplicationRolesList.add(mockUserApplicationRoles); + mockUserApplicationRolesList.add(mockUserApplicationRoles2); + Mockito.when((List<EPUser>) dataAccessService.executeNamedQuery("getActiveUsers", null, null)) + .thenReturn(mockEpUserList); + assertEquals(userRolesCommonServiceImpl.getUsersFromAppEndpoint(1l).size(), + mockUserApplicationRolesList.size()); + } + + @Test + public void getUsersFromAppEndpointNonCentralizedAppTest() throws HTTPException, JsonProcessingException { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + Mockito.when(epAppCommonServiceImpl.getApp(mockApp.getId())).thenReturn(mockApp); + List<UserApplicationRoles> mockUserApplicationRolesNonCentralizedList = new ArrayList<>(); + UserApplicationRoles mockUserApplicationRoles = new UserApplicationRoles(); + List<RemoteRole> mockRemoteRoleList = new ArrayList<>(); + RemoteRole mockRemoteRole = new RemoteRole(); + mockRemoteRole.setId(1l); + mockRemoteRole.setName("test1"); + mockRemoteRoleList.add(mockRemoteRole); + mockUserApplicationRoles.setAppId(mockApp.getId()); + mockUserApplicationRoles.setFirstName("Guest"); + mockUserApplicationRoles.setLastName("Test"); + mockUserApplicationRoles.setOrgUserId("guestT"); + mockUserApplicationRoles.setRoles(mockRemoteRoleList); + UserApplicationRoles mockUserApplicationRoles2 = new UserApplicationRoles(); + List<RemoteRole> mockRemoteRoleList2 = new ArrayList<>(); + RemoteRole mockRemoteRole2 = new RemoteRole(); + mockRemoteRole2.setId(16l); + mockRemoteRole2.setName("test2"); + mockRemoteRoleList2.add(mockRemoteRole2); + mockUserApplicationRoles2.setAppId(mockApp.getId()); + mockUserApplicationRoles2.setFirstName("Guest2"); + mockUserApplicationRoles2.setLastName("Test2"); + mockUserApplicationRoles2.setOrgUserId("guestT2"); + mockUserApplicationRoles2.setRoles(mockRemoteRoleList2); + mockUserApplicationRolesNonCentralizedList.add(mockUserApplicationRoles); + mockUserApplicationRolesNonCentralizedList.add(mockUserApplicationRoles2); + RemoteUserWithRoles mockRemoteUserWithRoles1 = new RemoteUserWithRoles(); + mockRemoteUserWithRoles1.setFirstName("Guest1"); + mockRemoteUserWithRoles1.setLastName("Test1"); + mockRemoteUserWithRoles1.setOrgUserId("guestT"); + mockRemoteUserWithRoles1.setRoles(mockRemoteRoleList); + RemoteUserWithRoles mockRemoteUserWithRoles2 = new RemoteUserWithRoles(); + mockRemoteUserWithRoles2.setFirstName("Guest2"); + mockRemoteUserWithRoles2.setLastName("Test2"); + mockRemoteUserWithRoles2.setOrgUserId("guestT"); + mockRemoteUserWithRoles2.setRoles(mockRemoteRoleList2); + List<RemoteUserWithRoles> mockRemoteUserWithRolesList = new ArrayList<>(); + mockRemoteUserWithRolesList.add(mockRemoteUserWithRoles1); + mockRemoteUserWithRolesList.add(mockRemoteUserWithRoles2); + ObjectMapper mapper = new ObjectMapper(); + String mockGetRemoteUsersWithRoles = mapper.writeValueAsString(mockRemoteUserWithRolesList); + Mockito.when(applicationsRestClientService.getIncomingJsonString(mockApp.getId(), "/users")) + .thenReturn(mockGetRemoteUsersWithRoles); + List<UserApplicationRoles> userApplicationRolesNonCentralizedList = userRolesCommonServiceImpl + .getUsersFromAppEndpoint(2l); + assertEquals(mockUserApplicationRolesNonCentralizedList.size(), userApplicationRolesNonCentralizedList.size()); + } + + @SuppressWarnings("unchecked") + @Test + public void putUserAppRolesRequestTest() { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + AppWithRolesForUser appWithRolesForUser = new AppWithRolesForUser(); + List<RoleInAppForUser> mockRoleInAppForUserList = new ArrayList<>(); + RoleInAppForUser roleInAppForUser = new RoleInAppForUser(); + roleInAppForUser.setIsApplied(true); + roleInAppForUser.setRoleId(1l); + roleInAppForUser.setRoleName("test1"); + RoleInAppForUser roleInAppForUser2 = new RoleInAppForUser(); + roleInAppForUser2.setIsApplied(true); + roleInAppForUser2.setRoleId(1000l); + roleInAppForUser2.setRoleName("test3"); + mockRoleInAppForUserList.add(roleInAppForUser); + mockRoleInAppForUserList.add(roleInAppForUser2); + appWithRolesForUser.setAppId(mockApp.getId()); + appWithRolesForUser.setAppName(mockApp.getName()); + appWithRolesForUser.setOrgUserId(user.getOrgUserId()); + appWithRolesForUser.setAppRoles(mockRoleInAppForUserList); + List<EPUserAppRoles> epUserAppRolesList = new ArrayList<>(); + EPUserAppRoles appRole1 = new EPUserAppRoles(); + appRole1.setAppId(mockApp.getId()); + appRole1.setId(10l); + appRole1.setRoleId(roleInAppForUser.roleId); + epUserAppRolesList.add(appRole1); + List<EPUserAppRoles> epUserAppRolesList2 = new ArrayList<>(); + EPUserAppRoles appRole2 = new EPUserAppRoles(); + appRole2.setAppId(mockApp.getId()); + appRole2.setId(11l); + appRole2.setRoleId(roleInAppForUser2.roleId); + epUserAppRolesList2.add(appRole2); + EPUserAppRolesRequest mockEpAppRolesRequestData = new EPUserAppRolesRequest(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEpAppRolesRequestData, null); + final Map<String, Long> params = new HashMap<>(); + params.put("appId", appWithRolesForUser.appId); + params.put("appRoleId", roleInAppForUser.roleId); + Mockito.when((List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null)) + .thenReturn(epUserAppRolesList); + params.put("appRoleId", roleInAppForUser2.roleId); + Mockito.when((List<EPUserAppRoles>) dataAccessService.executeNamedQuery("appRoles", params, null)) + .thenReturn(epUserAppRolesList2); + EPUserAppRolesRequestDetail mockEPAppRoleDetail = new EPUserAppRolesRequestDetail(); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockEPAppRoleDetail, null); + FieldsValidator expected = new FieldsValidator(); + expected.setHttpStatusCode(Long.valueOf(HttpServletResponse.SC_OK)); + FieldsValidator actual = userRolesCommonServiceImpl.putUserAppRolesRequest(appWithRolesForUser, user); + assertEquals(expected, actual); + } + + @Test + public void importRolesFromRemoteApplicationTest() throws HTTPException { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + List<EPRole> expected = new ArrayList<>(); + EPRole epRole = new EPRole(); + epRole.setAppId(mockApp.getId()); + epRole.setActive(true); + epRole.setId(10l); + epRole.setName("test1"); + EPRole epRole2 = new EPRole(); + epRole2.setAppId(mockApp.getId()); + epRole2.setActive(true); + epRole2.setId(11l); + epRole2.setName("test2"); + expected.add(epRole); + expected.add(epRole2); + EPRole[] epRoleArray = expected.toArray(new EPRole[expected.size()]); + Mockito.when(applicationsRestClientService.get(EPRole[].class, mockApp.getId(), "/rolesFull")) + .thenReturn(epRoleArray); + Mockito.when(epRoleServiceImpl.getRole(mockApp.getId(), epRole.getId())).thenReturn(epRole); + Mockito.when(epRoleServiceImpl.getRole(mockApp.getId(), epRole2.getId())).thenReturn(epRole2); + List<EPRole> actual = userRolesCommonServiceImpl.importRolesFromRemoteApplication(mockApp.getId()); + assertEquals(expected.size(), actual.size()); + } + + @SuppressWarnings("deprecation") + @Test + public void getCachedAppRolesForUserTest() { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + List<EPUserApp> expected = new ArrayList<>(); + EPUserApp epUserApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setAppId(mockApp.getId()); + epRole.setActive(true); + epRole.setId(10l); + epRole.setName("test1"); + epUserApp.setApp(mockApp); + epUserApp.setRole(epRole); + epUserApp.setUserId(user.getId()); + expected.add(epUserApp); + String filter = " where user_id = " + Long.toString(user.getId()) + " and app_id = " + + Long.toString(mockApp.getId()); + Mockito.when(dataAccessService.getList(EPUserApp.class, filter, null, null)).thenReturn(expected); + List<EPUserApp> actual = userRolesCommonServiceImpl.getCachedAppRolesForUser(mockApp.getId(), user.getId()); + assertEquals(expected.size(), actual.size()); + } + + @SuppressWarnings("unchecked") + @Test + public void getUserAppCatalogRolesTest() { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + List<EPUserAppCatalogRoles> expected = new ArrayList<>(); + EPUserAppCatalogRoles epUserAppCatalogRoles = new EPUserAppCatalogRoles(); + epUserAppCatalogRoles.setAppId(mockApp.getId()); + epUserAppCatalogRoles.setId(2l); + epUserAppCatalogRoles.setRequestedRoleId(10l); + epUserAppCatalogRoles.setRequestStatus("S"); + epUserAppCatalogRoles.setRolename("test1"); + expected.add(epUserAppCatalogRoles); + Map<String, String> params = new HashMap<>(); + params.put("userid", user.getId().toString()); + params.put("appName", mockApp.getName()); + Mockito.when( + (List<EPUserAppCatalogRoles>) dataAccessService.executeNamedQuery("userAppCatalogRoles", params, null)) + .thenReturn(expected); + List<EPUserAppCatalogRoles> actual = userRolesCommonServiceImpl.getUserAppCatalogRoles(user, mockApp.getName()); + assertEquals(expected.size(), actual.size()); + } + + @Test + public void getExternalRequestAccessTest() { + ExternalSystemAccess expected = new ExternalSystemAccess("external_access_enable", false); + ExternalSystemAccess actual = userRolesCommonServiceImpl.getExternalRequestAccess(); + assertEquals(expected, actual); + } + + @Test + public void getEPUserAppListTest() { + EPApp mockApp = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + List<EPUserApp> expected = new ArrayList<>(); + EPUserApp epUserApp = new EPUserApp(); + EPRole epRole = new EPRole(); + epRole.setAppId(mockApp.getId()); + epRole.setActive(true); + epRole.setId(10l); + epRole.setName("test1"); + epUserApp.setApp(mockApp); + epUserApp.setRole(epRole); + epUserApp.setUserId(user.getId()); + expected.add(epUserApp); + final Map<String, Long> params = new HashMap<>(); + params.put("appId", mockApp.getId()); + params.put("userId", user.getId()); + params.put("roleId", epRole.getId()); + Mockito.when(dataAccessService.executeNamedQuery("getUserRoleOnUserIdAndRoleIdAndAppId", params, null)) + .thenReturn(expected); + List<EPUserApp> actual = userRolesCommonServiceImpl.getEPUserAppList(mockApp.getId(), user.getId(), + epRole.getId()); + assertEquals(expected.size(), actual.size()); + } + + @Test + public void updateRemoteUserProfileTest() { + EPApp mockApp = mockApp(); + EPApp mockApp2 = mockApp(); + mockApp.setId(2l); + mockApp.setEnabled(true); + mockApp.setCentralAuth(false); + EPUser user = mockUser.mockEPUser(); + List<EPApp> mockEpAppList = new ArrayList<>(); + mockEpAppList.add(mockApp); + mockEpAppList.add(mockApp2); + Mockito.when(searchServiceImpl.searchUserByUserId(user.getOrgUserId())).thenReturn(user); + Mockito.when(epAppCommonServiceImpl.getUserRemoteApps(user.getId().toString())).thenReturn(mockEpAppList); + String expected = "success"; + String actual = userRolesCommonServiceImpl.updateRemoteUserProfile(user.getOrgUserId(), mockApp.getId()); + assertEquals(expected, actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserServiceImplTest.java new file mode 100644 index 00000000..b8bb1652 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/UserServiceImplTest.java @@ -0,0 +1,178 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.net.HttpURLConnection; +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.json.simple.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPApp; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.utils.EPCommonSystemProperties; +import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.onboarding.util.CipherUtil; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; +import org.onap.portalsdk.core.util.SystemProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({ EcompPortalUtils.class, SystemProperties.class, PortalConstants.class, + EPCommonSystemProperties.class, Criterion.class, CipherUtil.class, Restrictions.class }) +public class UserServiceImplTest { + + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @InjectMocks + UserServiceImpl userServiceImpl= new UserServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + public EPApp mockApp() { + EPApp app = new EPApp(); + app.setName("Test"); + app.setImageUrl("test"); + app.setNameSpace("com.test.app"); + app.setCentralAuth(true); + app.setDescription("test"); + app.setNotes("test"); + app.setUrl("test"); + app.setId((long) 10); + app.setAppRestEndpoint("test"); + app.setAlternateUrl("test"); + app.setName("test"); + app.setMlAppName("test"); + app.setMlAppAdminId("test"); + app.setUsername("test"); + app.setAppPassword("test"); + app.setOpen(false); + app.setEnabled(true); + app.setUebKey("test"); + app.setUebSecret("test"); + app.setUebTopicName("test"); + app.setAppType(1); + return app; + } + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("unchecked") + @Test + public void getUserByUserIdExceptionTest() throws Exception { + PowerMockito.mockStatic(SystemProperties.class); + EPUser user = mockUser.mockEPUser(); + Mockito.when(SystemProperties.getProperty(SystemProperties.AUTHENTICATION_MECHANISM)).thenReturn("OIDC"); + Mockito.when(EPCommonSystemProperties.getProperty(EPCommonSystemProperties.AUTH_USER_SERVER)).thenReturn("http://www.test.com"); + HttpURLConnection connection = Mockito.mock(HttpURLConnection.class); + JSONObject response = new JSONObject(); + JSONObject userJson = new JSONObject(); + userJson.put("id", 1); + userJson.put("givenName", "Guest"); + userJson.put("familyName", "Test"); + userJson.put("email", "test@123.com"); + List<JSONObject> userListJson = new ArrayList<>(); + userListJson.add(userJson); + response.put("response", userListJson); + ByteArrayInputStream getBody = new ByteArrayInputStream(response.toString().getBytes("UTF-8")); + PowerMockito.when(connection.getInputStream()).thenReturn(getBody); + userServiceImpl.getUserByUserId(user.getOrgUserId()); + } + + @SuppressWarnings("unchecked") + @Test + public void saveNewUserTest() throws Exception { + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + List<EPUser> users = new ArrayList<>(); + Mockito.when(CipherUtil.encryptPKC(user.getLoginPwd())).thenReturn("xyz"); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("orgUserId",user.getLoginId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)).thenReturn(users); + String actual = userServiceImpl.saveNewUser(user, "No"); + assertEquals("success", actual); + } + + @SuppressWarnings("unchecked") + @Test + public void saveExistingUserTest() throws Exception { + PowerMockito.mockStatic(Restrictions.class); + PowerMockito.mockStatic(Criterion.class); + PowerMockito.mockStatic(CipherUtil.class); + EPUser user = mockUser.mockEPUser(); + user.setLoginPwd("xyz"); + List<EPUser> users = new ArrayList<>(); + users.add(user); + EPUser oldUser = mockUser.mockEPUser(); + oldUser.setLoginPwd("abc"); + List<EPUser> oldUsers = new ArrayList<>(); + oldUsers.add(oldUser); + Mockito.when(CipherUtil.encryptPKC(user.getLoginPwd())).thenReturn("xyz"); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion orgUserIdCriterion = Restrictions.eq("orgUserId",user.getLoginId()); + restrictionsList.add(orgUserIdCriterion); + Mockito.when((List<EPUser>) dataAccessService.getList(EPUser.class, null, restrictionsList, null)).thenReturn(oldUsers); + String actual = userServiceImpl.saveNewUser(user, "No"); + assertEquals("success", actual); + } + + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetParameterServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetParameterServiceImplTest.java new file mode 100644 index 00000000..ffaee13f --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetParameterServiceImplTest.java @@ -0,0 +1,129 @@ +/*- + * ============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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.service; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.WidgetCatalogParameter; +import org.onap.portalsdk.core.service.DataAccessService; +import org.onap.portalsdk.core.service.DataAccessServiceImpl; + +public class WidgetParameterServiceImplTest { + @Mock + DataAccessService dataAccessService = new DataAccessServiceImpl(); + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @InjectMocks + WidgetParameterServiceImpl widgetParameterServiceImpl = new WidgetParameterServiceImpl(); + + MockEPUser mockUser = new MockEPUser(); + + @SuppressWarnings("unchecked") + @Test + public void getUserParamByIdTest() { + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion widgetIdCrit = Restrictions.eq("widgetId", "1"); + restrictionsList.add(widgetIdCrit); + Criterion userIdCrit = Restrictions.eq("userId", "1"); + restrictionsList.add(userIdCrit); + Criterion paramIdCrit = Restrictions.eq("paramId", "1"); + restrictionsList.add(paramIdCrit); + List<WidgetCatalogParameter> mockWidgetCatParamsList = new ArrayList<>(); + Mockito.when((List<WidgetCatalogParameter>)dataAccessService + .getList(WidgetCatalogParameter.class, null, restrictionsList, null)).thenReturn(mockWidgetCatParamsList); + WidgetCatalogParameter widgetCatalogParameter = widgetParameterServiceImpl.getUserParamById(1l, 1l, 1l); + if(mockWidgetCatParamsList.isEmpty()) { + mockWidgetCatParamsList = null; + } + assertEquals(widgetCatalogParameter, mockWidgetCatParamsList); + } + + @Test + public void saveUserParameterTest(){ + WidgetCatalogParameter mockWidgetParameter = new WidgetCatalogParameter(); + WidgetCatalogParameter widgetParameter = new WidgetCatalogParameter(); + widgetParameter.setId(1l); + widgetParameter.setParamId(1l); + widgetParameter.setUser_value("test"); + widgetParameter.setWidgetId(1l); + widgetParameter.setUserId(1l); + Mockito.doNothing().when(dataAccessService).saveDomainObject(mockWidgetParameter, null); + widgetParameterServiceImpl.saveUserParameter(widgetParameter); + } + + @SuppressWarnings("unchecked") + @Test + public void getUserParameterByIdTest() { + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion paramIdCrit = Restrictions.eq("paramId", 1); + restrictionsList.add(paramIdCrit); + List<WidgetCatalogParameter> mockWidgetCatalogParameter = new ArrayList<>(); + Mockito.when((List<WidgetCatalogParameter>) dataAccessService + .getList(WidgetCatalogParameter.class, null, restrictionsList, null)).thenReturn(mockWidgetCatalogParameter); + List<WidgetCatalogParameter> list = widgetParameterServiceImpl.getUserParameterById(1l); + assertEquals(list, mockWidgetCatalogParameter); + } + + @Test + public void deleteUserParameterById() { + Map<String, String> params = new HashMap<String, String>(); + params.put("paramId", Long.toString(1)); + Mockito.when(dataAccessService.executeNamedQuery("deleteWidgetCatalogParameter", params, null)).thenReturn(null); + Mockito.when(dataAccessService.executeNamedQuery("deleteMicroserviceParameterById", params, null)).thenReturn(null); + widgetParameterServiceImpl.deleteUserParameterById(1l); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetServiceImplTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetServiceImplTest.java new file mode 100644 index 00000000..2d016207 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/service/WidgetServiceImplTest.java @@ -0,0 +1,259 @@ +/* +* ============LICENSE_START======================================================= +* ONAP PORTAL +* ================================================================================ +* Copyright 2018 TechMahindra +*================================================================================= +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* ============LICENSE_END========================================================= +*/ +package org.onap.portalapp.portal.service; + +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.domain.EPUserApp; +import org.onap.portalapp.portal.domain.Widget; +import org.onap.portalapp.portal.framework.MockitoTestSuite; +import org.onap.portalapp.portal.transport.FieldsValidator; +import org.onap.portalapp.portal.transport.OnboardingWidget; +import org.onap.portalsdk.core.service.DataAccessService; + +public class WidgetServiceImplTest { + + @Mock + DataAccessService dataAccessService; + @Mock + AdminRolesService adminRolesService; + @Mock + SessionFactory sessionFactory; + @Mock + Session session; + + @Mock + Transaction transaction; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + Mockito.when(session.beginTransaction()).thenReturn(transaction); + } + + @InjectMocks + WidgetServiceImpl widgetServiceImpl = new WidgetServiceImpl(); + + + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + NullPointerException nullPointerException = new NullPointerException(); + MockEPUser mockUser = new MockEPUser(); + + Long ACCOUNT_ADMIN_ROLE_ID = 99l; + Long LONG_ECOMP_APP_ID = 1l; + + + @Test + public void getOnboardingWidgetsTest_isSuperAdmin() { + EPUser user = mockUser.mockEPUser(); + List<OnboardingWidget> onboardingWidgets = new ArrayList<>(); + OnboardingWidget widget = new OnboardingWidget(); + onboardingWidgets.add(widget); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + String sql = "SELECT widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL" + + "from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID"+ " validAppsFilter "; + + widgetServiceImpl.getOnboardingWidgets(user, true); + } + + @Test + public void getOnboardingWidgetsTest_isAccountAdmin() { + EPUser user = mockUser.mockEPUser(); + List<OnboardingWidget> onboardingWidgets = new ArrayList<>(); + OnboardingWidget widget = new OnboardingWidget(); + onboardingWidgets.add(widget); + Mockito.when(adminRolesService.isSuperAdmin(null)).thenReturn(false); + Mockito.when(adminRolesService.isAccountAdmin(user)).thenReturn(true); + String sql = "SELECT widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL" + + " from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID" + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + 1l + + " AND FN_USER_ROLE.ROLE_ID = " + 99l + "validAppsFilter"; + widgetServiceImpl.getOnboardingWidgets(user, true); + } + + @Test + public void getOnboardingWidgetsTest_isUser() { + EPUser user = mockUser.mockEPUser(); + List<OnboardingWidget> onboardingWidgets = new ArrayList<>(); + OnboardingWidget widget = new OnboardingWidget(); + onboardingWidgets.add(widget); + Mockito.when(adminRolesService.isUser(user)).thenReturn(true); + Mockito.when(adminRolesService.isAccountAdmin(null)).thenReturn(false); + String sql = "SELECT DISTINCT widget.WIDGET_ID, widget.WDG_NAME, widget.APP_ID, app.APP_NAME, widget.WDG_WIDTH, widget.WDG_HEIGHT, widget.WDG_URL\"\r\n" + + " + \" from FN_WIDGET widget join FN_APP app ON widget.APP_ID = app.APP_ID" + + " join FN_USER_ROLE ON FN_USER_ROLE.APP_ID = app.APP_ID where FN_USER_ROLE.USER_ID = " + + 99l + "validAppsFilter"; + widgetServiceImpl.getOnboardingWidgets(user, false); + } + + + @Test + public void setOnboardingWidgetTest() { + EPUser user = mockUser.mockEPUser(); + OnboardingWidget widget = new OnboardingWidget(); + widget.name = "test"; + widget.appId = 1l; + widget.url = "demo"; + FieldsValidator fieldValidator = new FieldsValidator(); + fieldValidator.setHttpStatusCode(400l); + widgetServiceImpl.setOnboardingWidget(user, widget); + } + + @Test + public void setOnboardingWidgetTest_updateOrSaveWidget() { + EPUser user = mockUser.mockEPUser(); + OnboardingWidget widget = new OnboardingWidget(); + Mockito.when(adminRolesService.isSuperAdmin(null)).thenReturn(false); + widget.name = "test"; + widget.appId = 9l; + widget.url = "demo"; + widget.width = 1; + widget.height = 1; + FieldsValidator fieldValidator = new FieldsValidator(); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion userIdCriterion = Restrictions.eq("userId",1l); + Criterion roleIDCriterion = Restrictions.eq("role.id", 99l); + Criterion appIDCriterion = Restrictions.eq("app.id", 2l); + restrictionsList.add(Restrictions.and(userIdCriterion, roleIDCriterion,appIDCriterion)); + List<EPUserApp> userRoles = new ArrayList<>(); + EPUserApp app = new EPUserApp(); + userRoles.add(app); + Mockito.when((List<EPUserApp>) dataAccessService.getList(EPUserApp.class, null, restrictionsList, null)) + .thenReturn(userRoles); + fieldValidator.setHttpStatusCode(403l); + widgetServiceImpl.setOnboardingWidget(user, widget); + } + + @Test + public void setOnboardingWidgetTest_updateOrSaveWidget_isSuperAdmin() { + FieldsValidator fieldValidator = new FieldsValidator(); + EPUser user = mockUser.mockEPUser(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + user.setId(1l); + OnboardingWidget onboardingWidget = new OnboardingWidget(); + onboardingWidget.name="test"; + onboardingWidget.url="demo"; + onboardingWidget.id = 2l; + onboardingWidget.appId = 9l; + onboardingWidget.width = 1; + onboardingWidget.height = 1; + Widget widget = new Widget(); + Mockito.when(dataAccessService.getDomainObject(Widget.class, 2l, null)).thenReturn(widget); + widget.setId(1l); + + fieldValidator.setHttpStatusCode(404l); + widgetServiceImpl.setOnboardingWidget(user, onboardingWidget); + } + + @Test + public void setOnboardingWidgetTest_applyOnboardingWidget() { + FieldsValidator fieldValidator = new FieldsValidator(); + EPUser user = mockUser.mockEPUser(); + fieldValidator.setHttpStatusCode(200l); + OnboardingWidget onboardingWidget = new OnboardingWidget(); + onboardingWidget.name="test"; + onboardingWidget.url="demo"; + onboardingWidget.id = 2l; + onboardingWidget.appId = 9l; + onboardingWidget.width = 1; + onboardingWidget.height = 1; + Widget widget = new Widget(); + widget.setAppId(onboardingWidget.appId); + widget.setName(onboardingWidget.name); + widget.setWidth(onboardingWidget.width); + widget.setHeight(onboardingWidget.height); + widget.setUrl("demo"); + widgetServiceImpl.setOnboardingWidget(user, onboardingWidget); + } + + @Test + public void setOnboardingWidgetTest_validateOnboardingWidget() { + EPUser user = mockUser.mockEPUser(); + user.setId(1l); + FieldsValidator fieldsValidator = new FieldsValidator(); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + OnboardingWidget onboardingWidget = new OnboardingWidget(); + onboardingWidget.name="test"; + onboardingWidget.url="demo"; + onboardingWidget.appId = 9l; + onboardingWidget.width = 1; + onboardingWidget.height = 1; + onboardingWidget.id = null; + List<Widget> listWidget = new ArrayList<>(); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion urlCriterion = Restrictions.eq("url", onboardingWidget.url); + Criterion nameCriterion = Restrictions.eq("name", onboardingWidget.name); + restrictionsList.add(Restrictions.or(urlCriterion, nameCriterion)); + Mockito.when((List<Widget>) dataAccessService.getList(Widget.class, null, restrictionsList, null)) + .thenReturn(listWidget); + Widget widget = new Widget(); + widget.setName("test"); + widget.setAppId(9l); + boolean dublicatedName = true; + boolean dublicatedUrl= true; + fieldsValidator.addProblematicFieldName("demo"); + fieldsValidator.addProblematicFieldName("test"); + fieldsValidator.setHttpStatusCode(409l); + widgetServiceImpl.setOnboardingWidget(user, onboardingWidget); + } + + @Test + public void deleteOnboardingWidgetTest() { + EPUser user = mockUser.mockEPUser(); + OnboardingWidget onboardingWidget = new OnboardingWidget(); + FieldsValidator fieldValidator = new FieldsValidator(); + Widget widget = new Widget(); + Mockito.when(dataAccessService.getDomainObject(Widget.class, 1l, null)).thenReturn(widget); + widget.setId(1l); + List<Criterion> restrictionsList = new ArrayList<Criterion>(); + Criterion userIdCriterion = Restrictions.eq("userId",1l); + Criterion roleIDCriterion = Restrictions.eq("role.id", 99l); + Criterion appIDCriterion = Restrictions.eq("app.id", 2l); + restrictionsList.add(Restrictions.and(userIdCriterion, roleIDCriterion,appIDCriterion)); + List<EPUserApp> userRoles = new ArrayList<>(); + EPUserApp app = new EPUserApp(); + userRoles.add(app); + Mockito.when((List<EPUserApp>) dataAccessService.getList(EPUserApp.class, null, restrictionsList, null)) + .thenReturn(userRoles); + Mockito.when(adminRolesService.isSuperAdmin(user)).thenReturn(true); + fieldValidator.setHttpStatusCode(403l); + widgetServiceImpl.deleteOnboardingWidget(user, 1l); + } + +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/ueb/EPUebHelperTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/ueb/EPUebHelperTest.java new file mode 100644 index 00000000..226d9709 --- /dev/null +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/ueb/EPUebHelperTest.java @@ -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============================================ + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.portalapp.portal.ueb; + +import static org.junit.Assert.assertFalse; + +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.portalapp.portal.domain.EcompApp; +import org.onap.portalapp.portal.service.EPAppCommonServiceImpl; +import org.onap.portalapp.portal.utils.PortalConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiConstants; +import org.onap.portalsdk.core.onboarding.util.PortalApiProperties; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.att.nsa.apiClient.http.HttpClient; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({PortalApiProperties.class, HttpClient.class, URL.class, PortalConstants.class}) +public class EPUebHelperTest { + + @Mock + EPAppCommonServiceImpl epAppCommonServiceImpl = new EPAppCommonServiceImpl(); + + @Mock + SessionFactory sessionFactory; + + @Mock + Session session; + + @Mock + Transaction transaction; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + Mockito.when(sessionFactory.openSession()).thenReturn(session); + } + + @InjectMocks + EPUebHelper epUebHelper = new EPUebHelper(); + + @Test + public void refreshPublisherForPortalListTest() { + List<EcompApp> ecompApps = new ArrayList<>(); + EcompApp ecompApp = new EcompApp(); + ecompApp.setCentralAuth(true); + ecompApp.setId(1l); + ecompApp.setName("test"); + ecompApp.setEnabled(true); + ecompApp.setUebTopicName("ECOMP-PORTAL-INBOX"); + ecompApps.add(ecompApp); + Mockito.when(epAppCommonServiceImpl.getEcompAppAppsFullList()).thenReturn(ecompApps); + epUebHelper.refreshPublisherList(); + } + + @Test + public void refreshPublisherForPartnersListTest() { + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(PortalApiProperties.class); + List<EcompApp> ecompApps = new ArrayList<>(); + EcompApp ecompApp = new EcompApp(); + ecompApp.setCentralAuth(true); + ecompApp.setId(2l); + ecompApp.setName("test"); + ecompApp.setEnabled(true); + ecompApp.setUebTopicName("Test"); + ecompApps.add(ecompApp); + Mockito.when(epAppCommonServiceImpl.getEcompAppAppsFullList()).thenReturn(ecompApps); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.ECOMP_PORTAL_INBOX_NAME)).thenReturn("ecomp_portal_inbox_name"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_INBOUND_MAILBOX_NAME)).thenReturn("ueb_app_mailbox_name"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_KEY)).thenReturn("ueb_app_key"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_SECRET)).thenReturn("ueb_app_secret"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_APP_CONSUMER_GROUP_NAME)).thenReturn("ueb_app_consumer_group_name"); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST)).thenReturn("ueb_url_list"); + epUebHelper.refreshPublisherList(); + } + + @Test + public void refreshPublisherForExceptionListTest() { + List<EcompApp> ecompApps = new ArrayList<>(); + EcompApp ecompApp = new EcompApp(); + ecompApp.setCentralAuth(true); + ecompApp.setId(2l); + ecompApp.setName("test"); + ecompApp.setEnabled(true); + ecompApp.setUebTopicName("Test"); + ecompApps.add(ecompApp); + Mockito.doThrow(new NullPointerException()).when(epAppCommonServiceImpl).getEcompAppAppsFullList(); + epUebHelper.refreshPublisherList(); + } + + @Test + public void checkAvailabilityConectionRefusedTest() throws Exception { + PowerMockito.mockStatic(PortalConstants.class); + PowerMockito.mockStatic(PortalApiProperties.class); + Mockito.when(PortalApiProperties.getProperty(PortalApiConstants.UEB_URL_LIST)).thenReturn("localhost"); + URL u = PowerMockito.mock(URL.class); + String url = "http://localhost:3904/topics/null"; + PowerMockito.whenNew(URL.class).withArguments(url).thenReturn(u); + HttpURLConnection huc = PowerMockito.mock(HttpURLConnection.class); + PowerMockito.when(u.openConnection()).thenReturn(huc); + PowerMockito.when(huc.getResponseCode()).thenReturn(200); + boolean actual = epUebHelper.checkAvailability(); + assertFalse(actual); + } +} diff --git a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java index efc1dab1..2af02c32 100644 --- a/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java +++ b/ecomp-portal-BE-common/src/test/java/org/onap/portalapp/portal/utils/EcompPortalUtilsTest.java @@ -39,11 +39,26 @@ package org.onap.portalapp.portal.utils; import static org.junit.Assert.assertEquals; +import java.util.ArrayList; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + import org.junit.Test; -import org.onap.portalapp.portal.utils.EcompPortalUtils; +import org.onap.portalapp.portal.core.MockEPUser; +import org.onap.portalapp.portal.domain.EPUser; +import org.onap.portalapp.portal.framework.MockitoTestSuite; public class EcompPortalUtilsTest { + MockitoTestSuite mockitoTestSuite = new MockitoTestSuite(); + + HttpServletRequest mockedRequest = mockitoTestSuite.getMockedRequest(); + HttpServletResponse mockedResponse = mockitoTestSuite.getMockedResponse(); + MockEPUser mockUser = new MockEPUser(); + + @Test public void legitimateAttuidSuccessTest() { assertEquals(true, EcompPortalUtils.legitimateUserId("mm016f")); @@ -53,4 +68,36 @@ public class EcompPortalUtilsTest { public void legitimateAttuidFailureTest() { assertEquals(false, EcompPortalUtils.legitimateUserId("1#@23456")); } + + + @Test + public void parsingByRegularExpressionTest() { + List<String> expected = new ArrayList<>(); + expected.add("test"); + expected.add("123"); + assertEquals(expected,EcompPortalUtils.parsingByRegularExpression("test 123"," ")); + } + + @Test + public void jsonErrorMessageResponseTest() { + String expected = "{\"error\":{\"code\":" + 200 + "," + "\"message\":\"" + "test" + "\"}}"; + assertEquals(expected,EcompPortalUtils.jsonErrorMessageResponse(200, "test")); + } + + @Test + public void jsonMessageResponseTest() { + String expected = "{\"message\":\"test\"}"; + assertEquals(expected,EcompPortalUtils.jsonMessageResponse("test")); + } + + @Test + public void logAndSerializeObjectTest() { + EcompPortalUtils.logAndSerializeObject("test", "test", EcompPortalUtils.class); + } + + @Test + public void setBadPermissionsForEmptyUserTest() { + EcompPortalUtils.setBadPermissions(new EPUser(), mockedResponse, "test"); + } + } |