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

The following examples show how to use cn.hutool.core.util.StrUtil#isBlank() . 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: OcrUtils.java    From tools-ocr with GNU Lesser General Public License v3.0 7 votes vote down vote up
private static String extractSogouResult(String html) {
    if (StrUtil.isBlank(html)) {
        return "";
    }
    JSONObject jsonObject = JSONUtil.parseObj(html);
    if (jsonObject.getInt("success", 0) != 1) {
        return "";
    }
    JSONArray jsonArray = jsonObject.getJSONArray("result");
    List<TextBlock> textBlocks = new ArrayList<>();
    boolean isEng;
    for (int i = 0; i < jsonArray.size(); i++) {
        JSONObject jObj = jsonArray.getJSONObject(i);
        TextBlock textBlock = new TextBlock();
        textBlock.setText(jObj.getStr("content").trim());
        //noinspection SuspiciousToArrayCall
        String[] frames = jObj.getJSONArray("frame").toArray(new String[0]);
        textBlock.setTopLeft(CommUtils.frameToPoint(frames[0]));
        textBlock.setTopRight(CommUtils.frameToPoint(frames[1]));
        textBlock.setBottomRight(CommUtils.frameToPoint(frames[2]));
        textBlock.setBottomLeft(CommUtils.frameToPoint(frames[3]));
        textBlocks.add(textBlock);
    }
    isEng = jsonObject.getStr("lang", "zh-Chs").equals("zh-Chs");
    return CommUtils.combineTextBlocks(textBlocks, isEng);
}
 
Example 2
Source File: LinuxProjectCommander.java    From Jpom with MIT License 6 votes vote down vote up
@Override
public String buildCommand(ProjectInfoModel projectInfoModel, ProjectInfoModel.JavaCopyItem javaCopyItem) {
    String path = ProjectInfoModel.getClassPathLib(projectInfoModel);
    if (StrUtil.isBlank(path)) {
        return null;
    }
    String tag = javaCopyItem == null ? projectInfoModel.getId() : javaCopyItem.getTagId();
    return String.format("nohup %s %s %s" +
                    " %s  %s  %s >> %s 2>&1 &",
            getRunJavaPath(projectInfoModel, false),
            javaCopyItem == null ? projectInfoModel.getJvm() : javaCopyItem.getJvm(),
            JvmUtil.getJpomPidTag(tag, projectInfoModel.allLib()),
            path,
            projectInfoModel.getMainClass(),
            javaCopyItem == null ? projectInfoModel.getArgs() : javaCopyItem.getArgs(),
            projectInfoModel.getAbsoluteLog(javaCopyItem));
}
 
Example 3
Source File: PostController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 将所有文章推送到百度
 *
 * @param baiduToken baiduToken
 * @return JsonResult
 */
@GetMapping(value = "/pushAllToBaidu")
@ResponseBody
public JsonResult pushAllToBaidu(@RequestParam("baiduToken") String baiduToken) {
    if (StrUtil.isBlank(baiduToken)) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.post.no-baidu-token"));
    }
    final String blogUrl = HaloConst.OPTIONS.get(BlogPropertiesEnum.BLOG_URL.getProp());
    final List<Post> posts = postService.findAll(PostTypeEnum.POST_TYPE_POST.getDesc());
    final StringBuilder urls = new StringBuilder();
    for (Post post : posts) {
        urls.append(blogUrl);
        urls.append("/archives/");
        urls.append(post.getPostUrl());
        urls.append("\n");
    }
    final String result = HaloUtils.baiduPost(blogUrl, baiduToken, urls.toString());
    if (StrUtil.isEmpty(result)) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.post.push-to-baidu-failed"));
    }
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.post.push-to-baidu-success"));
}
 
Example 4
Source File: YxMiniPayService.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
/**
 * 小程序支付
 *
 * @param orderId
 * @param openId   小程序openid
 * @param body
 * @param totalFee
 * @return
 * @throws WxPayException
 */
public WxPayMpOrderResult wxPay(String orderId, String openId, String body,
                                Integer totalFee,String attach) throws WxPayException {

    String apiUrl = redisHandler.getVal(ShopKeyUtils.getApiUrl());
    if (StrUtil.isBlank(apiUrl)) throw new ErrorRequestException("请配置api地址");

    WxPayService wxPayService = WxPayConfiguration.getWxAppPayService();
    WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();

    orderRequest.setTradeType("JSAPI");
    orderRequest.setOpenid(openId);
    orderRequest.setBody(body);
    orderRequest.setOutTradeNo(orderId);
    orderRequest.setTotalFee(totalFee);
    orderRequest.setSpbillCreateIp("127.0.0.1");
    orderRequest.setNotifyUrl(apiUrl + "/api/wechat/notify");
    orderRequest.setAttach(attach);


    WxPayMpOrderResult orderResult = wxPayService.createOrder(orderRequest);

    return orderResult;

}
 
Example 5
Source File: ZooLockAspect.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 环绕操作
 *
 * @param point 切入点
 * @return 原方法返回值
 * @throws Throwable 异常信息
 */
@Around("doLock()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    Object[] args = point.getArgs();
    ZooLock zooLock = method.getAnnotation(ZooLock.class);
    if (StrUtil.isBlank(zooLock.key())) {
        throw new RuntimeException("分布式锁键不能为空");
    }
    String lockKey = buildLockKey(zooLock, method, args);
    InterProcessMutex lock = new InterProcessMutex(zkClient, lockKey);
    try {
        // 假设上锁成功,以后拿到的都是 false
        if (lock.acquire(zooLock.timeout(), zooLock.timeUnit())) {
            return point.proceed();
        } else {
            throw new RuntimeException("请勿重复提交");
        }
    } finally {
        lock.release();
    }
}
 
Example 6
Source File: YamiUserServiceImpl.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 获取前端登陆的用户信息
 *
 * @param app
 * @param bizUserId openId
 * @return UserDetails
 * @throws UsernameNotFoundExceptionBase
 */
@Override
public YamiUser loadUserByAppIdAndBizUserId(App app, String bizUserId) {

	String cacheKey = app.value() + StrUtil.COLON + bizUserId;

	User user = userMapper.getUserByBizUserId(app.value(), bizUserId);
	if (user == null) {
		throw new UsernameNotFoundExceptionBase("无法获取用户信息");
	}
	String name = StrUtil.isBlank(user.getRealName()) ? user.getNickName() : user.getRealName();
	YamiUser yamiUser = new YamiUser(user.getUserId(), bizUserId, app.value(), user.getStatus() == 1);
	yamiUser.setName(name);
	yamiUser.setPic(user.getPic());

	return yamiUser;
}
 
Example 7
Source File: SysUserController.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 修改用户
 */
@SysLog("修改用户")
@PutMapping
@PreAuthorize("@pms.hasPermission('sys:user:update')")
public ResponseEntity<String> update(@Valid @RequestBody SysUser user){
	String password = user.getPassword();

	SysUser dbUser = sysUserService.getSysUserById(user.getUserId());

	if (!Objects.equals(dbUser.getShopId(), SecurityUtils.getSysUser().getShopId())) {
		throw new YamiShopBindException("没有权限修改该用户信息");
	}
	SysUser dbUserNameInfo = sysUserService.getByUserName(user.getUsername());

	if (dbUserNameInfo != null && !Objects.equals(dbUserNameInfo.getUserId(),user.getUserId())) {
		return ResponseEntity.badRequest().body("该用户已存在");
	}
	if (StrUtil.isBlank(password)) {
		user.setPassword(null);
	}else {
		user.setPassword(passwordEncoder.encode(user.getPassword()));
	}
	sysUserService.updateUserAndUserRole(user);
	return ResponseEntity.ok().build();
}
 
Example 8
Source File: YxPayService.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
/**
 * 微信公众号支付
 *
 * @param orderId
 * @param openId   公众号openid
 * @param body
 * @param totalFee
 * @return
 * @throws WxPayException
 */
public WxPayMpOrderResult wxPay(String orderId, String openId, String body,
                                Integer totalFee,String attach) throws WxPayException {

    String apiUrl = redisHandler.getVal(ShopKeyUtils.getApiUrl());
    if (StrUtil.isBlank(apiUrl)) throw new ErrorRequestException("请配置api地址");

    WxPayService wxPayService = WxPayConfiguration.getPayService();
    WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();

    orderRequest.setTradeType("JSAPI");
    orderRequest.setOpenid(openId);
    orderRequest.setBody(body);
    orderRequest.setOutTradeNo(orderId);
    orderRequest.setTotalFee(totalFee);
    orderRequest.setSpbillCreateIp("127.0.0.1");
    orderRequest.setNotifyUrl(apiUrl + "/api/wechat/notify");
    orderRequest.setAttach(attach);


    WxPayMpOrderResult orderResult = wxPayService.createOrder(orderRequest);

    return orderResult;

}
 
Example 9
Source File: SysUserServiceImpl.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Transactional
@Override
public Result updatePassword(Long id, String oldPassword, String newPassword) {
    SysUser sysUser = baseMapper.selectById(id);
    if (StrUtil.isNotBlank(oldPassword)) {
        if (!passwordEncoder.matches(oldPassword, sysUser.getPassword())) {
            return Result.failed("旧密码错误");
        }
    }
    if (StrUtil.isBlank(newPassword)) {
        newPassword = CommonConstant.DEF_USER_PASSWORD;
    }
    SysUser user = new SysUser();
    user.setId(id);
    user.setPassword(passwordEncoder.encode(newPassword));
    baseMapper.updateById(user);
    return Result.succeed("修改成功");
}
 
Example 10
Source File: SettingController.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/sms/{serviceName}", method = RequestMethod.GET)
@ApiOperation(value = "查看短信配置")
public Result<SmsSetting> sms(@PathVariable String serviceName) {

    Setting setting = new Setting();
    if (serviceName.equals(SettingConstant.ALI_SMS)) {
        setting = settingService.get(SettingConstant.ALI_SMS);
    }
    if (setting == null || StrUtil.isBlank(setting.getValue())) {
        return new ResultUtil<SmsSetting>().setData(null);
    }
    SmsSetting smsSetting = new Gson().fromJson(setting.getValue(), SmsSetting.class);
    smsSetting.setSecretKey("**********");

    Setting code = settingService.get(CommonUtil.getSmsTemplate(smsSetting.getType()));
    smsSetting.setTemplateCode(code.getValue());
    return new ResultUtil<SmsSetting>().setData(smsSetting);
}
 
Example 11
Source File: UserController.java    From datax-web with MIT License 6 votes vote down vote up
@PostMapping(value = "/update")
@ApiOperation("更新用户信息")
public ReturnT<String> update(@RequestBody JobUser jobUser) {
    if (StringUtils.hasText(jobUser.getPassword())) {
        String pwd = jobUser.getPassword().trim();
        if (StrUtil.isBlank(pwd)) {
            return new ReturnT<>(FAIL_CODE, I18nUtil.getString("system_no_blank") + "密码");
        }

        if (!(pwd.length() >= 4 && pwd.length() <= 20)) {
            return new ReturnT<>(FAIL_CODE, I18nUtil.getString("system_length_limit") + "[4-20]");
        }
        jobUser.setPassword(bCryptPasswordEncoder.encode(pwd));
    } else {
        return new ReturnT<>(FAIL_CODE, I18nUtil.getString("system_no_blank") + "密码");
    }
    // write
    jobUserMapper.update(jobUser);
    return ReturnT.SUCCESS;
}
 
Example 12
Source File: StoreCategoryController.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Log("新增商品分类")
@ApiOperation(value = "新增商品分类")
@PostMapping(value = "/yxStoreCategory")
@CacheEvict(cacheNames = ShopConstants.YSHOP_REDIS_INDEX_KEY,allEntries = true)
@PreAuthorize("@el.check('admin','YXSTORECATEGORY_ALL','YXSTORECATEGORY_CREATE')")
public ResponseEntity create(@Validated @RequestBody YxStoreCategory resources){

    if(resources.getPid() > 0 && StrUtil.isBlank(resources.getPic())) {
        throw new BadRequestException("子分类图片必传");
    }


    boolean checkResult = yxStoreCategoryService.checkCategory(resources.getPid());

    if(!checkResult) throw new BadRequestException("分类最多能添加2级哦");


    resources.setAddTime(OrderUtil.getSecondTimestampTwo());
    return new ResponseEntity(yxStoreCategoryService.save(resources),HttpStatus.CREATED);
}
 
Example 13
Source File: ImgJsonSerializer.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    if (StrUtil.isBlank(value)) {
        gen.writeString(StrUtil.EMPTY);
        return;
    }
    String[] imgs = value.split(StrUtil.COMMA);
    StringBuilder sb = new StringBuilder();
    for (String img : imgs) {
        sb.append(qiniu.getResourcesUrl()).append(img).append(StrUtil.COMMA);
    }
    sb.deleteCharAt(sb.length()-1);
    gen.writeString(sb.toString());
}
 
Example 14
Source File: RechargeService.java    From runscore with Apache License 2.0 5 votes vote down vote up
@ParamValid
@Transactional
public RechargeOrderVO generateRechargeOrder(RechargeOrderParam param) {
	PayChannel payChannel = payChannelRepo.getOne(param.getPayChannelId());
	if (payChannel.getPayType().getBankCardFlag()) {
		if (param.getDepositTime() == null) {
			throw new BizException(BizError.存款时间不能为空);
		}
		if (StrUtil.isBlank(param.getDepositor())) {
			throw new BizException(BizError.存款人姓名不能为空);
		}
	}

	Integer orderEffectiveDuration = Constant.充值订单默认有效时长;
	RechargeSetting rechargeSetting = rechargeSettingRepo.findTopByOrderByLatelyUpdateTime();
	if (rechargeSetting != null) {
		orderEffectiveDuration = rechargeSetting.getOrderEffectiveDuration();
	}
	RechargeOrder rechargeOrder = param.convertToPo(orderEffectiveDuration);
	if (payChannel.getPayType().getBankCardFlag()) {
		// 银行卡入款的充值订单不设有效时间
		rechargeOrder.setUsefulTime(null);
	} else {
		PayPlatformService payPlatformService = SpringUtils.getBean(payChannel.getPayPlatformCode());
		String payUrl = payPlatformService.startPay(rechargeOrder.getOrderNo(), rechargeOrder.getRechargeAmount(),
				payChannel.getPayPlatformChannelCode());
		rechargeOrder.setPayUrl(payUrl);
	}
	rechargeOrderRepo.save(rechargeOrder);
	return RechargeOrderVO.convertFor(rechargeOrder);
}
 
Example 15
Source File: XssWrapper.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 对参数中特殊字符进行过滤
 */
@Override
public String getParameter(String name) {
    String value = super.getParameter(name);
    if (StrUtil.isBlank(value)) {
        return value;
    }
    return cleanXSS(value);
}
 
Example 16
Source File: ValidateCodeServiceImpl.java    From fw-spring-cloud with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(ServletWebRequest request) {
	String imageRes = redisTemplate.opsForValue().get(SESSION_KEY);
	ImageCode codeInSession = JSONUtil.toBean(imageRes, ImageCode.class);
	String codeInRequest;
	try {
		codeInRequest = ServletRequestUtils.getStringParameter(request.getRequest(),
				"imageCode");
	} catch (ServletRequestBindingException e) {
		throw new ValidateCodeException("获取验证码的值失败");
	}

	if (StrUtil.isBlank(codeInRequest)) {
		throw new ValidateCodeException("验证码的值不能为空");
	}

	if (codeInSession == null) {
		throw new ValidateCodeException("验证码不存在");
	}

	if (codeInSession.isExpried()) {
		redisTemplate.delete(SESSION_KEY);
		throw new ValidateCodeException("验证码已过期");
	}

	if (!StrUtil.equals(codeInSession.getCode(), codeInRequest)) {
		throw new ValidateCodeException("验证码不匹配");
	}

	redisTemplate.delete(SESSION_KEY);
}
 
Example 17
Source File: SettingController.java    From sk-admin with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/email", method = RequestMethod.GET)
@ApiOperation(value = "查看email配置")
public Result<EmailSetting> email() {

    Setting setting = settingService.get(SettingConstant.EMAIL_SETTING);
    if (setting == null || StrUtil.isBlank(setting.getValue())) {
        return new ResultUtil<EmailSetting>().setData(null);
    }
    EmailSetting emailSetting = new Gson().fromJson(setting.getValue(), EmailSetting.class);
    emailSetting.setPassword("**********");
    return new ResultUtil<EmailSetting>().setData(emailSetting);
}
 
Example 18
Source File: FrontOthersController.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 获取文章rss
 *
 * @return rss
 */
@GetMapping(value = {"feed", "feed.xml", "atom", "atom.xml"}, produces = "application/xml;charset=UTF-8")
@ResponseBody
public String feed() {
    String rssPosts = HaloConst.OPTIONS.get(BlogPropertiesEnum.RSS_POSTS.getProp());
    if (StrUtil.isBlank(rssPosts)) {
        rssPosts = "20";
    }
    //获取文章列表并根据时间排序
    Sort sort = new Sort(Sort.Direction.DESC, "postDate");
    Pageable pageable = PageRequest.of(0, Integer.parseInt(rssPosts), sort);
    Page<Post> postsPage = postService.findPostByStatus(0, PostTypeEnum.POST_TYPE_POST.getDesc(), pageable);
    List<Post> posts = postsPage.getContent();
    return postService.buildRss(posts);
}
 
Example 19
Source File: ProjectCaseStepsController.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 修改测试用例步骤管理
 */
@GetMapping("/edit/{caseId}")
public String edit(@PathVariable("caseId") Integer caseId, ModelMap mmap)
{
	ProjectCase projectCase=projectCaseService.selectProjectCaseById(caseId);
	ProjectCaseSteps projectCaseSteps = new ProjectCaseSteps();
	projectCaseSteps.setCaseId(caseId);
	List<ProjectCaseSteps> stepsList=projectCaseStepsService.selectProjectCaseStepsList(projectCaseSteps);
	
	if(stepsList.size()==0){
		projectCaseSteps.setAction("");
		projectCaseSteps.setExpectedResult("");
		projectCaseSteps.setExtend("");
		projectCaseSteps.setProjectId(projectCase.getProjectId());
		projectCaseSteps.setStepId(0);
		projectCaseSteps.setStepOperation("");
		projectCaseSteps.setStepParameters("");
		projectCaseSteps.setStepPath("");
		projectCaseSteps.setStepSerialNumber(1);
		projectCaseSteps.setStepType(projectCase.getCaseType());
		stepsList.add(projectCaseSteps);
	}
	
	for(ProjectCaseSteps steps:stepsList){
		if(StrUtil.isBlank(steps.getStepRemark())){
			steps.setStepRemark("备注");
		}
		if(StrUtil.isBlank(steps.getExtend())){
			steps.setExtend("");
		}
		if(StrUtil.isBlank(steps.getAction())){
			steps.setAction("");
		}
		if(StrUtil.isBlank(steps.getStepParameters())){
			steps.setStepParameters("");
		}
	}
	
	mmap.put("stepsList", stepsList);
	mmap.put("projectCase", projectCase);
    return "testmanagmt/projectCase/projectCaseSteps";
}
 
Example 20
Source File: LoginAuthenticationFilter.java    From mall4j with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
    if (!ServletUtil.METHOD_POST.equals(request.getMethod())) {
        throw new AuthenticationServiceException(
                "Authentication method not supported: " + request.getMethod());
    }
    String requestBody = getStringFromStream(request);

    if (StrUtil.isBlank(requestBody)) {
        throw new AuthenticationServiceException("无法获取输入信息");
    }
    AdminAuthenticationToken adminAuthenticationToken  =  Json.parseObject(requestBody, AdminAuthenticationToken.class);


    String username = adminAuthenticationToken.getPrincipal() == null?"NONE_PROVIDED":adminAuthenticationToken.getName();


    String kaptchaKey = SecurityConstants.SPRING_SECURITY_RESTFUL_IMAGE_CODE + adminAuthenticationToken.getSessionUUID();

    String kaptcha = RedisUtil.get(kaptchaKey);

    RedisUtil.del(kaptchaKey);

    if(StrUtil.isBlank(adminAuthenticationToken.getImageCode()) || !adminAuthenticationToken.getImageCode().equalsIgnoreCase(kaptcha)){
        throw new ImageCodeNotMatchExceptionBase("验证码有误");
    }

    UserDetails user;
    try {
        user = yamiUserDetailsService.loadUserByUsername(username);
    } catch (UsernameNotFoundExceptionBase var6) {
        throw new UsernameNotFoundExceptionBase("账号或密码不正确");
    }

    String encodedPassword = user.getPassword();
    String rawPassword = adminAuthenticationToken.getCredentials().toString();

    // 密码不正确
    if (!passwordEncoder.matches(rawPassword,encodedPassword)){
        throw new BadCredentialsExceptionBase("账号或密码不正确");
    }

    if (!user.isEnabled()) {
        throw new UsernameNotFoundExceptionBase("账号已被锁定,请联系管理员");
    }
    AdminAuthenticationToken result = new AdminAuthenticationToken(user, adminAuthenticationToken.getCredentials());
    result.setDetails(adminAuthenticationToken.getDetails());
    return result;
}