Java Code Examples for cn.hutool.core.util.StrUtil#equals()

The following examples show how to use cn.hutool.core.util.StrUtil#equals() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CloudUserDetailsServiceImpl.java    From smaker with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 构建userdetails
 *
 * @param result 用户信息
 * @return
 */
private UserDetails getUserDetails(SmakerResult<UserInfo> result) {
	if (result == null || result.getData() == null) {
		throw new UsernameNotFoundException("用户不存在");
	}

	UserInfo info = result.getData();
	Set<String> dbAuthsSet = new HashSet<>();
	if (ArrayUtil.isNotEmpty(info.getRoles())) {
		// 获取角色
		Arrays.stream(info.getRoles()).forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role));
		// 获取资源
		dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));

	}
	Collection<? extends GrantedAuthority> authorities
		= AuthorityUtils.createAuthorityList(dbAuthsSet.toArray(new String[0]));
	SysUser user = info.getSysUser();

	// 构造security用户
	return new CloudUser(user.getUserId(), user.getDeptId(), user.getUsername(), SecurityConstants.BCRYPT + user.getPassword(),
		StrUtil.equals(user.getLockFlag(), CommonConstants.STATUS_NORMAL), true, true, true, authorities);
}
 
Example 2
Source File: AttachmentController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 跳转选择附件页面
 *
 * @param model model
 * @param page  page 当前页码
 *
 * @return 模板路径admin/widget/_attachment-select
 */
@GetMapping(value = "/select")
public String selectAttachment(Model model,
                               @RequestParam(value = "page", defaultValue = "0") Integer page,
                               @RequestParam(value = "id", defaultValue = "none") String id,
                               @RequestParam(value = "type", defaultValue = "normal") String type) {
    final Sort sort = new Sort(Sort.Direction.DESC, "attachId");
    final Pageable pageable = PageRequest.of(page, 18, sort);
    final Page<Attachment> attachments = attachmentService.findAll(pageable);
    model.addAttribute("attachments", attachments);
    model.addAttribute("id", id);
    if (StrUtil.equals(type, PostTypeEnum.POST_TYPE_POST.getDesc())) {
        return "admin/widget/_attachment-select-post";
    }
    return "admin/widget/_attachment-select";
}
 
Example 3
Source File: SysUserController.java    From pre with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 修改密码
 *
 * @return
 */
@SysOperaLog(descrption = "修改密码")
@PutMapping("updatePass")
@PreAuthorize("hasAuthority('sys:user:updatePass')")
public R updatePass(@RequestParam String oldPass, @RequestParam String newPass) {
    // 校验密码流程
    SysUser sysUser = userService.findSecurityUserByUser(new SysUser().setUsername(SecurityUtil.getUser().getUsername()));
    if (!PreUtil.validatePass(oldPass, sysUser.getPassword())) {
        throw new PreBaseException("原密码错误");
    }
    if (StrUtil.equals(oldPass, newPass)) {
        throw new PreBaseException("新密码不能与旧密码相同");
    }
    // 修改密码流程
    SysUser user = new SysUser();
    user.setUserId(sysUser.getUserId());
    user.setPassword(PreUtil.encode(newPass));
    return R.ok(userService.updateUserInfo(user));
}
 
Example 4
Source File: BackupController.java    From blog-sharon with Apache License 2.0 6 votes vote down vote up
/**
 * 渲染备份页面
 *
 * @param model model
 * @return 模板路径admin/admin_backup
 */
@GetMapping
public String backup(@RequestParam(value = "type", defaultValue = "resources") String type, Model model) {
    List<BackupDto> backups = null;
    if (StrUtil.equals(type, BackupTypeEnum.RESOURCES.getDesc())) {
        backups = HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc());
    } else if (StrUtil.equals(type, BackupTypeEnum.DATABASES.getDesc())) {
        backups = HaloUtils.getBackUps(BackupTypeEnum.DATABASES.getDesc());
    } else if (StrUtil.equals(type, BackupTypeEnum.POSTS.getDesc())) {
        backups = HaloUtils.getBackUps(BackupTypeEnum.POSTS.getDesc());
    } else {
        backups = new ArrayList<>();
    }
    model.addAttribute("backups", backups);
    model.addAttribute("type", type);
    return "admin/admin_backup";
}
 
Example 5
Source File: BackupController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 渲染备份页面
 *
 * @param model model
 *
 * @return 模板路径admin/admin_backup
 */
@GetMapping
public String backup(@RequestParam(value = "type", defaultValue = "resources") String type, Model model) {
    List<BackupDto> backups = null;
    if (StrUtil.equals(type, BackupTypeEnum.RESOURCES.getDesc())) {
        backups = HaloUtils.getBackUps(BackupTypeEnum.RESOURCES.getDesc());
    } else if (StrUtil.equals(type, BackupTypeEnum.DATABASES.getDesc())) {
        backups = HaloUtils.getBackUps(BackupTypeEnum.DATABASES.getDesc());
    } else if (StrUtil.equals(type, BackupTypeEnum.POSTS.getDesc())) {
        backups = HaloUtils.getBackUps(BackupTypeEnum.POSTS.getDesc());
    } else {
        backups = new ArrayList<>();
    }
    model.addAttribute("backups", backups);
    model.addAttribute("type", type);
    return "admin/admin_backup";
}
 
Example 6
Source File: RoleModel.java    From Jpom with MIT License 6 votes vote down vote up
private Set<String> forTreeList(List<TreeLevel> treeLevels, ClassFeature classFeature, String dataId, String parentDataId) {
        Set<String> dataIds = new HashSet<>();
        if (treeLevels == null || treeLevels.isEmpty()) {
            return dataIds;
        }
        for (TreeLevel treeLevel : treeLevels) {
            ClassFeature nowFeature = ClassFeature.valueOf(treeLevel.getClassFeature());
            if (nowFeature == classFeature && (dataId == null || StrUtil.equals(parentDataId, dataId))) {
                // 是同一个功能
//                System.out.println(dataId + "  " + parentDataId);
                dataIds.add(treeLevel.getData());
            }
            if (nowFeature != classFeature) {
                List<TreeLevel> children = treeLevel.getChildren();
                Set<String> strings = forTreeList(children, classFeature, dataId, treeLevel.getData());
                if (!strings.isEmpty()) {
                    return strings;
                }
            }
        }
        return dataIds;
    }
 
Example 7
Source File: StartedListener.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 加载主题设置
 */
private void loadActiveTheme() throws TemplateModelException {
    String themeValue = optionsService.findOneOption(BlogPropertiesEnum.THEME.getProp());
    if (StrUtil.isNotEmpty(themeValue) && !StrUtil.equals(themeValue, null)) {
        BaseController.THEME = themeValue;
    } else {
        //以防万一
        BaseController.THEME = "anatole";
    }
    configuration.setSharedVariable("themeName", BaseController.THEME);
}
 
Example 8
Source File: ValidateCodeGatewayFilter.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
@Override
public GatewayFilter apply(Object config) {
	return (exchange, chain) -> {
		ServerHttpRequest request = exchange.getRequest();

		// 不是登录请求,直接向下执行
		if (!StrUtil.containsAnyIgnoreCase(request.getURI().getPath()
			, OAUTH_TOKEN_URL)) {
			return chain.filter(exchange);
		}

		// 刷新token,直接向下执行
		String grantType = request.getQueryParams().getFirst("grant_type");
		if (StrUtil.equals(REFRESH_TOKEN, grantType)) {
			return chain.filter(exchange);
		}

		// 终端设置不校验, 直接向下执行
		try {
			//校验验证码
			checkCode(request);
		} catch (Exception e) {
			ServerHttpResponse response = exchange.getResponse();
			response.setStatusCode(HttpStatus.PRECONDITION_REQUIRED);
			try {
				Map map= new HashMap<>();
				map.put("code",-1);
				map.put("msg","失败");
				return response.writeWith(Mono.just(response.bufferFactory()
					.wrap(objectMapper.writeValueAsBytes(map))));
			} catch (JsonProcessingException e1) {
				log.error("对象输出异常", e1);
			}
		}

		return chain.filter(exchange);
	};
}
 
Example 9
Source File: FrontPageController.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 渲染自定义页面
 *
 * @param postUrl 页面路径
 * @param model   model
 * @return 模板路径/themes/{theme}/post
 */
@GetMapping(value = "/p/{postUrl}")
public String getPage(@PathVariable(value = "postUrl") String postUrl,
                      @RequestParam(value = "cp", defaultValue = "1") Integer cp,
                      Model model) {
    Post post = postService.findByPostUrl(postUrl, PostTypeEnum.POST_TYPE_PAGE.getDesc());
    if (null == post) {
        return this.renderNotFound();
    }
    List<Comment> comments = null;
    if (StrUtil.equals(HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NEED_CHECK.getProp()), TrueFalseEnum.TRUE.getDesc()) || HaloConst.OPTIONS.get(BlogPropertiesEnum.NEW_COMMENT_NEED_CHECK.getProp()) == null) {
        comments = commentService.findCommentsByPostAndCommentStatus(post, CommentStatusEnum.PUBLISHED.getCode());
    } else {
        comments = commentService.findCommentsByPostAndCommentStatusNot(post, CommentStatusEnum.RECYCLE.getCode());
    }
    //默认显示10条
    Integer size = 10;
    //获取每页评论条数
    if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_COMMENTS.getProp()))) {
        size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_COMMENTS.getProp()));
    }
    //评论分页
    ListPage<Comment> commentsPage = new ListPage<Comment>(CommentUtil.getComments(comments), cp, size);
    int[] rainbow = PageUtil.rainbow(cp, commentsPage.getTotalPage(), 3);
    model.addAttribute("is_page", true);
    model.addAttribute("post", post);
    model.addAttribute("comments", commentsPage);
    model.addAttribute("commentsCount", comments.size());
    model.addAttribute("rainbow", rainbow);
    postService.cacheViews(post.getPostId());

    //如果设置了自定义模板,则渲染自定义模板
    if (StrUtil.isNotEmpty(post.getCustomTpl())) {
        return this.render(post.getCustomTpl());
    }
    return this.render("page");
}
 
Example 10
Source File: PostController.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 处理删除文章的请求
 *
 * @param postId 文章编号
 * @return 重定向到/admin/posts
 */
@GetMapping(value = "/remove")
public String removePost(@RequestParam("postId") Long postId, @RequestParam("postType") String postType) {
    try {
        final Optional<Post> post = postService.findByPostId(postId);
        postService.remove(postId);
        logsService.save(LogsRecord.REMOVE_POST, post.get().getPostTitle(), request);
    } catch (Exception e) {
        log.error("Delete article failed: {}", e.getMessage());
    }
    if (StrUtil.equals(PostTypeEnum.POST_TYPE_POST.getDesc(), postType)) {
        return "redirect:/admin/posts?status=2";
    }
    return "redirect:/admin/page";
}
 
Example 11
Source File: InstallController.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 渲染安装页面
 *
 * @param model model
 *
 * @return 模板路径
 */
@GetMapping
public String install(Model model) {
    try {
        if (StrUtil.equals(TrueFalseEnum.TRUE.getDesc(), HaloConst.OPTIONS.get(BlogPropertiesEnum.IS_INSTALL.getProp()))) {
            model.addAttribute("isInstall", true);
        } else {
            model.addAttribute("isInstall", false);
        }
    } catch (Exception e) {
        log.error(e.getMessage());
    }
    return "common/install";
}
 
Example 12
Source File: PostController.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 处理删除文章的请求
 *
 * @param postId 文章编号
 * @return 重定向到/admin/posts
 */
@GetMapping(value = "/remove")
public String removePost(@RequestParam("postId") Long postId, @RequestParam("postType") String postType) {
    try {
        Optional<Post> post = postService.findByPostId(postId);
        postService.remove(postId);
        logsService.save(LogsRecord.REMOVE_POST, post.get().getPostTitle(), request);
    } catch (Exception e) {
        log.error("Delete article failed: {}", e.getMessage());
    }
    if (StrUtil.equals(PostTypeEnum.POST_TYPE_POST.getDesc(), postType)) {
        return "redirect:/admin/posts?status=2";
    }
    return "redirect:/admin/page";
}
 
Example 13
Source File: InstallInterceptor.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
    if (StrUtil.equals(TrueFalseEnum.TRUE.getDesc(), HaloConst.OPTIONS.get(BlogPropertiesEnum.IS_INSTALL.getProp()))) {
        return true;
    }
    response.sendRedirect("/install");
    return false;
}
 
Example 14
Source File: LocaleInterceptor.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    final Object attribute = request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
    if (null != attribute) {
        return true;
    }
    if (StrUtil.equals(LocaleEnum.EN_US.getValue(), HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_LOCALE.getProp()))) {
        request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("en", "US"));
    } else {
        request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("zh", "CN"));
    }
    return true;
}
 
Example 15
Source File: ValidateCodeFilter.java    From Taroco with Apache License 2.0 5 votes vote down vote up
/**
 * 检查code
 *
 * @param httpServletRequest request
 * @throws ValidateCodeException 验证码校验异常
 */
private void checkCode(HttpServletRequest httpServletRequest) throws ValidateCodeException {
    final String code = httpServletRequest.getParameter("code");
    if (StrUtil.isBlank(code)) {
        throw new ValidateCodeException("请输入验证码");
    }

    String randomStr = httpServletRequest.getParameter("randomStr");
    if (StrUtil.isBlank(randomStr)) {
        randomStr = httpServletRequest.getParameter("mobile");
    }

    final String key = CacheConstants.DEFAULT_CODE_KEY + randomStr;
    if (!redisRepository.exists(key)) {
        throw new ValidateCodeException(EXPIRED_CAPTCHA_ERROR);
    }

    final Object codeObj = redisRepository.get(key);

    if (codeObj == null) {
        throw new ValidateCodeException(EXPIRED_CAPTCHA_ERROR);
    }

    final String saveCode = codeObj.toString();
    if (StrUtil.isBlank(saveCode)) {
        redisRepository.del(key);
        throw new ValidateCodeException(EXPIRED_CAPTCHA_ERROR);
    }

    if (!StrUtil.equals(saveCode, code)) {
        redisRepository.del(key);
        throw new ValidateCodeException("验证码错误,请重新输入");
    }

    redisRepository.del(key);
}
 
Example 16
Source File: HaloUtils.java    From stone with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取备份文件信息
 *
 * @param dir dir
 *
 * @return List
 */
public static List<BackupDto> getBackUps(String dir) {
    final StrBuilder srcPathStr = new StrBuilder(System.getProperties().getProperty("user.home"));
    srcPathStr.append("/halo/backup/");
    srcPathStr.append(dir);
    final File srcPath = new File(srcPathStr.toString());
    final File[] files = srcPath.listFiles();
    final List<BackupDto> backupDtos = new ArrayList<>();
    BackupDto backupDto = null;
    // 遍历文件
    if (null != files) {
        for (File file : files) {
            if (file.isFile()) {
                if (StrUtil.equals(file.getName(), ".DS_Store")) {
                    continue;
                }
                backupDto = new BackupDto();
                backupDto.setFileName(file.getName());
                backupDto.setCreateAt(getCreateTime(file.getAbsolutePath()));
                backupDto.setFileType(FileUtil.getType(file));
                backupDto.setFileSize(parseSize(file.length()));
                backupDto.setBackupType(dir);
                backupDtos.add(backupDto);
            }
        }
    }
    return backupDtos;
}
 
Example 17
Source File: BuildService.java    From Jpom with MIT License 5 votes vote down vote up
public boolean checkNodeProjectId(String nodeId, String projectId) {
    List<BuildModel> list = list();
    if (list == null || list.isEmpty()) {
        return false;
    }
    for (BuildModel buildModel : list) {
        if (buildModel.getReleaseMethod() == BuildModel.ReleaseMethod.Project.getCode()) {
            String releaseMethodDataId = buildModel.getReleaseMethodDataId();
            if (StrUtil.equals(releaseMethodDataId, nodeId + ":" + projectId)) {
                return true;
            }
        }
    }
    return false;
}
 
Example 18
Source File: JpomManifest.java    From Jpom with MIT License 4 votes vote down vote up
/**
 * 检查是否为jpom包
 *
 * @param path    路径
 * @param clsName 类名
 * @return 结果消息
 */
public static JsonMessage checkJpomJar(String path, Class clsName) {
    String version;
    File jarFile = new File(path);
    try (JarFile jarFile1 = new JarFile(jarFile)) {
        Manifest manifest = jarFile1.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        String mainClass = attributes.getValue(Attributes.Name.MAIN_CLASS);
        if (mainClass == null) {
            return new JsonMessage(405, "清单文件中没有找到对应的MainClass属性");
        }
        JarClassLoader jarClassLoader = JarClassLoader.load(jarFile);
        try {
            jarClassLoader.loadClass(mainClass);
        } catch (ClassNotFoundException notFound) {
            return new JsonMessage(405, "中没有找到对应的MainClass:" + mainClass);
        }
        ZipEntry entry = jarFile1.getEntry(StrUtil.format("BOOT-INF/classes/{}.class",
                StrUtil.replace(clsName.getName(), ".", "/")));
        if (entry == null) {
            return new JsonMessage(405, "此包不是Jpom【" + JpomApplication.getAppType().name() + "】包");
        }
        version = attributes.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
        if (StrUtil.isEmpty(version)) {
            return new JsonMessage(405, "此包没有版本号");
        }
        String timeStamp = attributes.getValue("Jpom-Timestamp");
        if (StrUtil.isEmpty(timeStamp)) {
            return new JsonMessage(405, "此包没有版本号");
        }
        timeStamp = parseJpomTime(timeStamp);
        if (StrUtil.equals(version, JpomManifest.getInstance().getVersion()) &&
                StrUtil.equals(timeStamp, JpomManifest.getInstance().getTimeStamp())) {
            return new JsonMessage(405, "新包和正在运行的包一致");
        }
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("解析jar", e);
        return new JsonMessage(500, " 解析错误:" + e.getMessage());
    }
    return new JsonMessage(200, version);
}
 
Example 19
Source File: AdminController.java    From stone with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 验证登录信息
 *
 * @param loginName 登录名:邮箱/用户名
 * @param loginPwd  loginPwd 密码
 * @param session   session session
 *
 * @return JsonResult JsonResult
 */
@PostMapping(value = "/getLogin")
@ResponseBody
public JsonResult getLogin(@ModelAttribute("loginName") String loginName,
                           @ModelAttribute("loginPwd") String loginPwd,
                           HttpSession session) {
    //已注册账号,单用户,只有一个
    final User aUser = userService.findUser();
    //首先判断是否已经被禁用已经是否已经过了10分钟
    Date loginLast = DateUtil.date();
    if (null != aUser.getLoginLast()) {
        loginLast = aUser.getLoginLast();
    }
    final Long between = DateUtil.between(loginLast, DateUtil.date(), DateUnit.MINUTE);
    if (StrUtil.equals(aUser.getLoginEnable(), TrueFalseEnum.FALSE.getDesc()) && (between < CommonParamsEnum.TEN.getValue())) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.disabled"));
    }
    //验证用户名和密码
    User user = null;
    if (Validator.isEmail(loginName)) {
        user = userService.userLoginByEmail(loginName, SecureUtil.md5(loginPwd));
    } else {
        user = userService.userLoginByName(loginName, SecureUtil.md5(loginPwd));
    }
    userService.updateUserLoginLast(DateUtil.date());
    //判断User对象是否相等
    if (ObjectUtil.equal(aUser, user)) {
        session.setAttribute(HaloConst.USER_SESSION_KEY, aUser);
        //重置用户的登录状态为正常
        userService.updateUserNormal();
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_SUCCESS, request);
        log.info("User {} login succeeded.", aUser.getUserDisplayName());
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.login.success"));
    } else {
        //更新失败次数
        final Integer errorCount = userService.updateUserLoginError();
        //超过五次禁用账户
        if (errorCount >= CommonParamsEnum.FIVE.getValue()) {
            userService.updateUserLoginEnable(TrueFalseEnum.FALSE.getDesc());
        }
        logsService.save(LogsRecord.LOGIN, LogsRecord.LOGIN_ERROR + "[" + HtmlUtil.escape(loginName) + "," + HtmlUtil.escape(loginPwd) + "]", request);
        final Object[] args = {(5 - errorCount)};
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.login.failed", args));
    }
}
 
Example 20
Source File: AgentAuthorize.java    From Jpom with MIT License 2 votes vote down vote up
/**
 * 判断授权是否正确
 *
 * @param authorize 授权
 * @return true 正确
 */
public boolean checkAuthorize(String authorize) {
    return StrUtil.equals(authorize, this.authorize);
}