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);
}
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()));
}
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());
}
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());
}
}
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);
}
Aggregations