Search in sources :

Example 1 with RoleNotFoundException

use of javax.management.relation.RoleNotFoundException in project Qualitis by WeBankFinTech.

the class ProjectBatchServiceImpl method uploadProjectsReal.

private GeneralResponse<?> uploadProjectsReal(InputStream fileInputStream, String fileName, String userName, boolean aomp) throws IOException, UnExpectedRequestException, PermissionDeniedRequestException, RoleNotFoundException {
    String suffixName = fileName.substring(fileName.lastIndexOf('.'));
    if (!suffixName.equals(SUPPORT_EXCEL_SUFFIX_NAME)) {
        throw new UnExpectedRequestException("{&DO_NOT_SUPPORT_SUFFIX_NAME}: [" + suffixName + "]. {&ONLY_SUPPORT} [" + SUPPORT_EXCEL_SUFFIX_NAME + "]", 422);
    }
    if (userName == null) {
        return new GeneralResponse<>("401", "{&PLEASE_LOGIN}", null);
    }
    User user = userDao.findByUsername(userName);
    Long userId = user.getId();
    // Read file and create project
    ExcelProjectListener listener = readExcel(fileInputStream);
    // Check if excel file is empty
    if (listener.getExcelProjectContent().isEmpty() && listener.getExcelRuleContent().isEmpty() && listener.getExcelCustomRuleContent().isEmpty() && listener.getExcelMultiRuleContent().isEmpty() && listener.getTemplateFileExcelContent().isEmpty() && listener.getExcelMetricContent().isEmpty()) {
        throw new UnExpectedRequestException("{&FILE_CAN_NOT_BE_EMPTY_OR_FILE_CAN_NOT_BE_RECOGNIZED}", 422);
    }
    for (ExcelProject excelProject : listener.getExcelProjectContent()) {
        Project project = projectDao.findByNameAndCreateUser(excelProject.getProjectName(), userName);
        if (project != null) {
            if (!aomp) {
                LOGGER.info("hint for user to decide to override or not.");
            }
            // Means update project.
            LOGGER.info("Start to update project[name={}] with upload project file.", project.getName());
            ModifyProjectDetailRequest request = convertExcelProjectToModifyProjectRequest(excelProject, project, userName);
            projectService.modifyProjectDetail(request, false);
        } else {
            // Check excel project arguments is valid or not
            AddProjectRequest request = convertExcelProjectToAddProjectRequest(excelProject);
            projectService.addProject(request, userId);
        }
    }
    for (ExcelRuleMetric excelRuleMetric : listener.getExcelMetricContent()) {
        RuleMetric ruleMetric = ruleMetricDao.findByName(excelRuleMetric.getName());
        if (ruleMetric != null) {
            if (!aomp) {
                LOGGER.info("hint for user to decide to override or not.");
            }
            LOGGER.info("Start to update rule metric[name={}] with upload rule metric file.", ruleMetric.getName());
            modifyRuleMetric(excelRuleMetric, ruleMetric, userName);
        } else {
            addRuleMetric(excelRuleMetric, userName);
        }
    }
    // Create rules according to excel sheet
    Map<String, Map<String, List<ExcelTemplateRuleByProject>>> excelTemplateRulePartitionedByProject = listener.getExcelRuleContent();
    Map<String, Map<String, List<ExcelCustomRuleByProject>>> excelCustomRulePartitionedByProject = listener.getExcelCustomRuleContent();
    Map<String, Map<String, List<ExcelMultiTemplateRuleByProject>>> excelMultiTemplateRulePartitionedByProject = listener.getExcelMultiRuleContent();
    Map<String, Map<String, List<ExcelTemplateFileRuleByProject>>> excelTemplateFileRulePartitionedByProject = listener.getTemplateFileExcelContent();
    Set<String> allProjects = new HashSet<>();
    allProjects.addAll(excelTemplateRulePartitionedByProject.keySet());
    allProjects.addAll(excelCustomRulePartitionedByProject.keySet());
    allProjects.addAll(excelMultiTemplateRulePartitionedByProject.keySet());
    allProjects.addAll(excelTemplateFileRulePartitionedByProject.keySet());
    for (String projectName : allProjects) {
        try {
            Project projectInDb = projectDao.findByNameAndCreateUser(projectName, userName);
            if (projectInDb == null) {
                throw new UnExpectedRequestException("{&PROJECT}: [" + projectName + "] {&DOES_NOT_EXIST}");
            }
            ruleBatchService.getAndSaveRule(excelTemplateRulePartitionedByProject.get(projectName), excelCustomRulePartitionedByProject.get(projectName), excelMultiTemplateRulePartitionedByProject.get(projectName), excelTemplateFileRulePartitionedByProject.get(projectName), projectInDb, userName, aomp);
        } catch (Exception e) {
            throw new UnExpectedRequestException(e.getMessage());
        }
    }
    fileInputStream.close();
    return new GeneralResponse<>("200", "{&SUCCEED_TO_UPLOAD_FILE}", null);
}
Also used : RuleMetric(com.webank.wedatasphere.qualitis.entity.RuleMetric) UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) ExcelMultiTemplateRuleByProject(com.webank.wedatasphere.qualitis.project.excel.ExcelMultiTemplateRuleByProject) RuleMetricDepartmentUser(com.webank.wedatasphere.qualitis.entity.RuleMetricDepartmentUser) User(com.webank.wedatasphere.qualitis.entity.User) AddProjectRequest(com.webank.wedatasphere.qualitis.project.request.AddProjectRequest) ExcelCustomRuleByProject(com.webank.wedatasphere.qualitis.project.excel.ExcelCustomRuleByProject) ModifyProjectDetailRequest(com.webank.wedatasphere.qualitis.project.request.ModifyProjectDetailRequest) PermissionDeniedRequestException(com.webank.wedatasphere.qualitis.exception.PermissionDeniedRequestException) ZipException(net.lingala.zip4j.exception.ZipException) RoleNotFoundException(javax.management.relation.RoleNotFoundException) UnExpectedRequestException(com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException) IOException(java.io.IOException) WriteExcelException(com.webank.wedatasphere.qualitis.rule.exception.WriteExcelException) GeneralResponse(com.webank.wedatasphere.qualitis.response.GeneralResponse) ExcelMultiTemplateRuleByProject(com.webank.wedatasphere.qualitis.project.excel.ExcelMultiTemplateRuleByProject) ExcelCustomRuleByProject(com.webank.wedatasphere.qualitis.project.excel.ExcelCustomRuleByProject) ExcelTemplateRuleByProject(com.webank.wedatasphere.qualitis.project.excel.ExcelTemplateRuleByProject) Project(com.webank.wedatasphere.qualitis.project.entity.Project) ExcelProjectListener(com.webank.wedatasphere.qualitis.project.excel.ExcelProjectListener) ExcelTemplateRuleByProject(com.webank.wedatasphere.qualitis.project.excel.ExcelTemplateRuleByProject)

Example 2 with RoleNotFoundException

use of javax.management.relation.RoleNotFoundException in project Qualitis by WeBankFinTech.

the class RuleNodeServiceImpl method importRuleGroup.

@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = { RuntimeException.class, UnExpectedRequestException.class })
public GeneralResponse<RuleResponse> importRuleGroup(RuleNodeRequests ruleNodeRequests) throws UnExpectedRequestException, IOException, PermissionDeniedRequestException {
    // Project, rule group.
    Project projectInDb = projectDao.findById(ruleNodeRequests.getNewProjectId());
    ObjectMapper objectMapper = new ObjectMapper();
    RuleGroup ruleGroup = objectMapper.readValue(ruleNodeRequests.getRuleNodeRequests().iterator().next().getRuleGroupObject(), RuleGroup.class);
    RuleGroup ruleGroupInDb = ruleGroupDao.saveRuleGroup(new RuleGroup(ruleGroup.getRuleGroupName(), projectInDb.getId()));
    if (DEV_CENTER.equals(localConfig.getCenter())) {
        CopyRuleRequest copyRuleRequest = new CopyRuleRequest();
        copyRuleRequest.setSourceRuleGroupId(ruleGroup.getId());
        copyRuleRequest.setCreateUser(projectInDb.getCreateUser());
        copyRuleRequest.setTargetRuleGroupId(ruleGroupInDb.getId());
        copyRuleRequest.setTargetProjectId(ruleNodeRequests.getNewProjectId());
        copyRuleByRuleGroupId(copyRuleRequest);
        return new GeneralResponse<>("200", "{&IMPORT_RULE_SUCCESSFULLY}", new RuleResponse(ruleGroupInDb.getId()));
    }
    if (projectInDb != null) {
        LOGGER.info("Project info : {}", projectInDb.toString());
    } else {
        // For special case:
        // A project already exists in DSS. when creating a workflow in this project and publish it, Qualitis service cannot find the project.
        // Because Qualitis did not run when this project had been created in DSS.
        LOGGER.info("Start to create workflow project. Project[id = {}] is not exist.", ruleNodeRequests.getNewProjectId());
        String userName = ruleNodeRequests.getUserName();
        User currentUser = userDao.findByUsername(userName);
        if (currentUser == null) {
            LOGGER.info("Start to create user. User name is {}", userName);
            try {
                userService.autoAddUser(userName);
                currentUser = userDao.findByUsername(userName);
            } catch (RoleNotFoundException e) {
                LOGGER.error("Role cannot be found. Exception: {}", e);
            }
        }
        Project newProject = projectService.addProjectReal(currentUser.getId(), currentUser.getUserName() + "_project_" + UUID.randomUUID().toString(), currentUser.getUserName() + "_项目_" + UUID.randomUUID().toString(), "Auto created.");
        newProject.setProjectType(ProjectTypeEnum.WORKFLOW_PROJECT.getCode());
        projectInDb = projectDao.saveProject(newProject);
        LOGGER.info("Succeed to create project. New project: {}", projectInDb.toString());
    }
    for (RuleNodeRequest request : ruleNodeRequests.getRuleNodeRequests()) {
        importRule(request, projectInDb, ruleGroupInDb, objectMapper);
    }
    return new GeneralResponse<>("200", "{&IMPORT_RULE_SUCCESSFULLY}", new RuleResponse(ruleGroupInDb.getId()));
}
Also used : GeneralResponse(com.webank.wedatasphere.qualitis.response.GeneralResponse) Project(com.webank.wedatasphere.qualitis.project.entity.Project) ExcelMultiTemplateRuleByProject(com.webank.wedatasphere.qualitis.project.excel.ExcelMultiTemplateRuleByProject) ExcelTemplateFileRuleByProject(com.webank.wedatasphere.qualitis.project.excel.ExcelTemplateFileRuleByProject) User(com.webank.wedatasphere.qualitis.entity.User) RuleNodeRequest(com.webank.wedatasphere.qualitis.rule.request.RuleNodeRequest) RuleResponse(com.webank.wedatasphere.qualitis.rule.response.RuleResponse) RoleNotFoundException(javax.management.relation.RoleNotFoundException) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) RuleGroup(com.webank.wedatasphere.qualitis.rule.entity.RuleGroup) CopyRuleRequest(com.webank.wedatasphere.qualitis.rule.request.CopyRuleRequest) Transactional(org.springframework.transaction.annotation.Transactional)

Example 3 with RoleNotFoundException

use of javax.management.relation.RoleNotFoundException in project Qualitis by WeBankFinTech.

the class UserServiceImpl method autoAddUser.

@Override
@Transactional(rollbackFor = { Exception.class })
public void autoAddUser(String username) throws RoleNotFoundException {
    User newUser = new User();
    String password = username;
    String passwordEncoded = Sha256Encoder.encode(password);
    newUser.setUserName(username);
    newUser.setPassword(passwordEncoded);
    User savedUser = userDao.saveUser(newUser);
    Role role = roleDao.findByRoleName("PROJECTOR");
    if (role == null) {
        throw new RoleNotFoundException();
    }
    UserRole userRole = new UserRole();
    userRole.setId(UuidGenerator.generate());
    userRole.setRole(role);
    userRole.setUser(savedUser);
    userRoleDao.saveUserRole(userRole);
    LOGGER.info("Succeed to save user_role. uuid: {}, user_id: {}, role_id: {}", userRole.getId(), savedUser.getId(), role.getId());
}
Also used : Role(com.webank.wedatasphere.qualitis.entity.Role) UserRole(com.webank.wedatasphere.qualitis.entity.UserRole) User(com.webank.wedatasphere.qualitis.entity.User) UserRole(com.webank.wedatasphere.qualitis.entity.UserRole) RoleNotFoundException(javax.management.relation.RoleNotFoundException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with RoleNotFoundException

use of javax.management.relation.RoleNotFoundException in project JavaSpringBoot by jeunefeu.

the class BlogUserServiceImpl method saveNewBlogUser.

@Override
public BlogUser saveNewBlogUser(BlogUser blogUser) throws RoleNotFoundException {
    // for testing debugging purposes
    System.err.println("saveNewBlogUser: " + blogUser);
    // Encode plaintext password with password encoder
    // blogUser.setPassword(PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(blogUser.getPassword()).substring(8));
    // explicit bcrypt encoder so better approach ?
    blogUser.setPassword(this.bcryptEncoder.encode(blogUser.getPassword()));
    // set account to enabled by default
    blogUser.setEnabled(true);
    // Set default Authority/Role to new blog user
    Optional<Authority> optionalAuthority = this.authorityRepository.findByAuthority(DEFAULT_ROLE);
    // for testing debugging purposes
    System.err.println("optionalAuthority: " + optionalAuthority);
    if (optionalAuthority.isPresent()) {
        Authority authority = optionalAuthority.get();
        Collection<Authority> authorities = Collections.singletonList(authority);
        blogUser.setAuthorities(authorities);
        // for testing debugging purposes
        System.err.println("blogUser after Roles: " + blogUser);
        // return blogUserRepository.save(blogUser);
        return this.blogUserRepository.saveAndFlush(blogUser);
    } else {
        throw new RoleNotFoundException("Default role not found for blog user with username " + blogUser.getUsername());
    }
}
Also used : Authority(org.martynas.blogapp.model.Authority) RoleNotFoundException(javax.management.relation.RoleNotFoundException)

Example 5 with RoleNotFoundException

use of javax.management.relation.RoleNotFoundException in project Qualitis by WeBankFinTech.

the class Filter1AuthorizationFilter method doFilter.

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    String requestUrl = request.getRequestURI();
    // Pass if file upload url accepted
    AntPathMatcher matcher = new AntPathMatcher();
    for (String uploadUrl : uploadUrlList) {
        if (matcher.match(uploadUrl, requestUrl)) {
            filterChain.doFilter(request, response);
            return;
        }
    }
    BodyReaderHttpServletRequestWrapper requestWrapper = new BodyReaderHttpServletRequestWrapper(request);
    printReceiveLog(requestWrapper);
    if (NOT_FILTER_METHOD.equals(requestWrapper.getMethod())) {
        filterChain.doFilter(requestWrapper, response);
        return;
    }
    HttpSession session = requestWrapper.getSession();
    if (!permitUrlList.contains(requestUrl)) {
        Object permissionObj = session.getAttribute("permissions");
        Object user = session.getAttribute("user");
        if (null == permissionObj || null == user) {
            String username = request.getRemoteUser();
            if (username == null) {
                // Redirect to login page
                LOGGER.info("Can not get username from sso, it will redirect to local login page");
                writeRedirectHome(response);
            } else {
                // 查询数据库,看用户是否存在
                User userInDb = userDao.findByUsername(username);
                if (userInDb != null) {
                    // 放入session
                    loginService.addToSession(username, request);
                    ((HttpServletResponse) response).sendRedirect(frontEndConfig.getHomePage());
                } else {
                    // 自动创建用户
                    LOGGER.warn("user: {}, do not exist, trying to create user", username);
                    try {
                        userService.autoAddUser(username);
                        loginService.addToSession(username, request);
                        ((HttpServletResponse) response).sendRedirect(frontEndConfig.getHomePage());
                    } catch (RoleNotFoundException e) {
                        LOGGER.error("Failed to auto add user, cause by: Failed to get role [PROJECTOR]", e);
                    }
                }
            }
            return;
        }
        List<Permission> permissions = (List<Permission>) permissionObj;
        String method = requestWrapper.getMethod();
        if (!checkPermission(requestUrl, method, permissions)) {
            writeForbidden("no permissions", response);
            LOGGER.warn("User: {} failed to access url: {}, caused by: No permissions", user, requestWrapper.getRequestURI());
            return;
        }
    }
    Object user = session.getAttribute("user");
    LOGGER.info("User: {} succeed to access url: {}", user, requestWrapper.getRequestURI());
    filterChain.doFilter(requestWrapper, response);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) User(com.webank.wedatasphere.qualitis.entity.User) HttpSession(javax.servlet.http.HttpSession) Permission(com.webank.wedatasphere.qualitis.entity.Permission) HttpServletResponse(javax.servlet.http.HttpServletResponse) RoleNotFoundException(javax.management.relation.RoleNotFoundException) ArrayList(java.util.ArrayList) List(java.util.List) AntPathMatcher(org.springframework.util.AntPathMatcher)

Aggregations

RoleNotFoundException (javax.management.relation.RoleNotFoundException)7 User (com.webank.wedatasphere.qualitis.entity.User)6 Project (com.webank.wedatasphere.qualitis.project.entity.Project)3 GeneralResponse (com.webank.wedatasphere.qualitis.response.GeneralResponse)3 Role (com.webank.wedatasphere.qualitis.entity.Role)2 UserRole (com.webank.wedatasphere.qualitis.entity.UserRole)2 PermissionDeniedRequestException (com.webank.wedatasphere.qualitis.exception.PermissionDeniedRequestException)2 UnExpectedRequestException (com.webank.wedatasphere.qualitis.exception.UnExpectedRequestException)2 ExcelMultiTemplateRuleByProject (com.webank.wedatasphere.qualitis.project.excel.ExcelMultiTemplateRuleByProject)2 AddProjectRequest (com.webank.wedatasphere.qualitis.project.request.AddProjectRequest)2 ModifyProjectDetailRequest (com.webank.wedatasphere.qualitis.project.request.ModifyProjectDetailRequest)2 ArrayList (java.util.ArrayList)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpSession (javax.servlet.http.HttpSession)2 Transactional (org.springframework.transaction.annotation.Transactional)2 RoleDao (com.webank.wedatasphere.qualitis.dao.RoleDao)1 UserDao (com.webank.wedatasphere.qualitis.dao.UserDao)1 UserRoleDao (com.webank.wedatasphere.qualitis.dao.UserRoleDao)1 Permission (com.webank.wedatasphere.qualitis.entity.Permission)1 RuleMetric (com.webank.wedatasphere.qualitis.entity.RuleMetric)1