cn.hutool.core.util.RandomUtil Java Examples

The following examples show how to use cn.hutool.core.util.RandomUtil. 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: TranTestService.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
public void testSingleFail() {

    User user = new User();
    user.setAccount(RandomUtil.randomString(5));
    user.setPassword(RandomUtil.randomString(5));
    user.setCreateTime(new Date());
    user.setUpdateTime(new Date());
    user.setCreateUser(1L);
    user.setUpdateUser(1L);
    gunsDbService.save(user);

    User user2 = new User();
    user2.setAccount(RandomUtil.randomString(5));
    user2.setPassword(RandomUtil.randomString(5));
    user2.setCreateTime(new Date());
    user2.setUpdateTime(new Date());
    user2.setCreateUser(1L);
    user2.setUpdateUser(1L);
    gunsDbService.save(user2);

    int i = 1 / 0;
}
 
Example #2
Source File: UserBasicInfoController.java    From Jpom with MIT License 6 votes vote down vote up
/**
 * 发送邮箱验证
 *
 * @param email 邮箱
 * @return msg
 */
@RequestMapping(value = "sendCode.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
public String sendCode(@ValidatorItem(value = ValidatorRule.EMAIL, msg = "邮箱格式不正确") String email) {
    MailAccountModel config = systemMailConfigService.getConfig();
    if (config == null) {
        return JsonMessage.getString(405, "管理员还没有配置系统邮箱");
    }
    int randomInt = RandomUtil.randomInt(1000, 9999);
    try {
        EmailUtil.send(email, "Jpom 验证码", "验证码是:" + randomInt);
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("发送失败", e);
        return JsonMessage.getString(500, "发送邮件失败:" + e.getMessage());
    }
    CACHE.put(email, randomInt);
    return JsonMessage.getString(200, "发送成功");
}
 
Example #3
Source File: SimpleCaptcha.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Image createImage(String code) {
	// 图像buffer
	final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	final ThreadLocalRandom random = RandomUtil.getRandom();
	final Graphics2D g = ImageUtil.createGraphics(image, new Color(249,249,249));

	// 干扰线
	drawInterfere(g, random);

	// 创建字体
	g.setFont(this.font);
	final FontMetrics metrics = g.getFontMetrics();
	int minY = metrics.getAscent() - metrics.getLeading() - metrics.getDescent();
	// 文字
	final int len = this.generator.getLength();
	int charWidth = width / len;
	for (int i = 0; i < len; i++) {
		// 产生随机的颜色值,让输出的每个字符的颜色值都将不同。
		g.setColor(ImageUtil.randomColor(random));
		g.drawString(String.valueOf(code.charAt(i)), i * charWidth, RandomUtil.randomInt(minY, this.height));
	}

	return image;
}
 
Example #4
Source File: BuildTriggerController.java    From Jpom with MIT License 6 votes vote down vote up
@RequestMapping(value = "trigger.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
@Feature(method = MethodFeature.EDIT)
public String trigger(String id) {
    BuildModel item = buildService.getItem(id);
    //
    if (StrUtil.isEmpty(item.getTriggerToken())) {
        item.setTriggerToken(RandomUtil.randomString(10));
        buildService.updateItem(item);
    }
    setAttribute("item", item);
    //
    String contextPath = getRequest().getContextPath();
    String url = ServerOpenApi.BUILD_TRIGGER_BUILD.
            replace("{id}", item.getId()).
            replace("{token}", item.getTriggerToken());
    String triggerBuildUrl = String.format("/%s/%s", contextPath, url);
    setAttribute("triggerBuildUrl", FileUtil.normalize(triggerBuildUrl));
    return "build/trigger";
}
 
Example #5
Source File: VerificationCodeServiceImpl.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(VerificationCode code) {
    EmailVo emailVo;
    String content;
    VerificationCode verificationCode = verificationCodeDao.findByScenesAndTypeAndValueAndStatusIsTrue(code.getScenes(), code.getType(), code.getValue());
    // 如果不存在有效的验证码,就创建一个新的
    TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
    Template template = engine.getTemplate("email/email.ftl");
    if (verificationCode == null) {
        code.setCode(RandomUtil.randomNumbers(6));
        content = template.render(Dict.create().set("code", code.getCode()));
        emailVo = new EmailVo(Collections.singletonList(code.getValue()), "eladmin后台管理系统", content);
        timedDestruction(verificationCodeDao.save(code));
        // 存在就再次发送原来的验证码
    } else {
        content = template.render(Dict.create().set("code", verificationCode.getCode()));
        emailVo = new EmailVo(Collections.singletonList(verificationCode.getValue()), "eladmin后台管理系统", content);
    }
    return emailVo;
}
 
Example #6
Source File: MobileService.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
 * 发送短信
 *
 * @param mobile     mobile
 * @return ResponseBean
 * @author tangyi
 * @date 2019/07/02 09:36:52
 */
public ResponseBean<Boolean> sendSms(String mobile) {
    String key = CommonConstant.DEFAULT_CODE_KEY + LoginTypeEnum.SMS.getType() + "@" + mobile;
    // TODO 校验时间
    String code = RandomUtil.randomNumbers(Integer.parseInt(CommonConstant.CODE_SIZE));
    log.debug("Generate validate code success: {}, {}", mobile, code);
    redisTemplate.opsForValue().set(key, code, SecurityConstant.DEFAULT_SMS_EXPIRE, TimeUnit.SECONDS);
    // 调用消息中心服务,发送短信验证码
    SmsDto smsDto = new SmsDto();
    smsDto.setReceiver(mobile);
    smsDto.setContent(String.format(SmsConstant.SMS_TEMPLATE, code));
    ResponseBean<?> result = mscServiceClient.sendSms(smsDto);
    if (!ResponseUtil.isSuccess(result))
        throw new ServiceException("Send validate code error: " + result.getMsg());
    log.info("Send validate result: {}", result.getData());
    return new ResponseBean<>(Boolean.TRUE, code);
}
 
Example #7
Source File: OrderController.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 消费消息失败
 */
@GetMapping("/consumeError")
public String consumeError() {
    Order order = new Order();
    order.setOrderId(IdGenerator.getId());
    order.setOrderNo(RandomUtil.randomString(4));

    Message message = MessageBuilder
            .withPayload(order)
            .setHeader("orderId", order.getOrderId())
            .setHeader("consumeError", "1")
            .build();
    //发送半消息
    source.output().send(message);
    return "消费消息失败";
}
 
Example #8
Source File: ValidateCodeServiceImpl.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 发送验证码
 * <p>
 * 1. 先去redis 查询是否 60S内已经发送
 * 2. 未发送: 判断手机号是否存 ? false :产生4位数字  手机号-验证码
 * 3. 发往消息中心-》发送信息
 * 4. 保存redis
 *
 * @param mobile 手机号
 * @return true、false
 */
@Override
public Result sendSmsCode(String mobile) {
    Object tempCode = redisRepository.get(buildKey(mobile));
    if (tempCode != null) {
        log.error("用户:{}验证码未失效{}", mobile, tempCode);
        return Result.failed("验证码未失效,请失效后再次申请");
    }

    SysUser user = userService.findByMobile(mobile);
    if (user == null) {
        log.error("根据用户手机号{}查询用户为空", mobile);
        return Result.failed("手机号不存在");
    }

    String code = RandomUtil.randomNumbers(4);
    log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
    redisRepository.setExpire(buildKey(mobile), code, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
    return Result.succeed("true");
}
 
Example #9
Source File: OrderController.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 发送消息失败
 */
@GetMapping("/produceError")
public String produceError() {
    Order order = new Order();
    order.setOrderId(IdGenerator.getId());
    order.setOrderNo(RandomUtil.randomString(4));

    Message message = MessageBuilder
            .withPayload(order)
            .setHeader("orderId", order.getOrderId())
            .setHeader("produceError", "1")
            .build();
    //发送半消息
    source.output().send(message);
    return "发送消息失败";
}
 
Example #10
Source File: SysUserServiceTenantTest.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 构建实体
 */
private SysUser initEntity(){
    SysUser sysUser=new SysUser();
    sysUser.setId(RandomUtil.randomLong());
    sysUser.setCreateTime(DateUtil.date());
    sysUser.setUpdateTime(DateUtil.date());
    sysUser.setCreateUser("sys");
    sysUser.setUpdateUser("sys");
    sysUser.setDeleteFlag(1);
    sysUser.setDisableFlag(1);
    sysUser.setPosCode("pos");
    sysUser.setAvatar("avatar");
    sysUser.setEmail(RandomUtil.randomNumber()+"@qq.com");
    sysUser.setPassword("123456");
    sysUser.setUserName("root");
    sysUser.setRealName("fwcloud");
    sysUser.setDeptCode("dept");
    sysUser.setUserPhone(String.valueOf(RandomUtil.randomNumber()));
    sysUser.setTenantCode("FWCLOUD");

    return sysUser;
}
 
Example #11
Source File: SysUserServiceTest.java    From fw-spring-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 构建实体
 */
private SysUser initEntity(){
    SysUser sysUser=new SysUser();
    sysUser.setId(RandomUtil.randomLong());
    sysUser.setCreateTime(DateUtil.date());
    sysUser.setUpdateTime(DateUtil.date());
    sysUser.setCreateUser("sys");
    sysUser.setUpdateUser("sys");
    sysUser.setDeleteFlag(1);
    sysUser.setDisableFlag(1);
    sysUser.setPosCode("pos");
    sysUser.setAvatar("avatar");
    sysUser.setEmail(RandomUtil.randomNumber()+"@qq.com");
    sysUser.setPassword("123456");
    sysUser.setUserName("root");
    sysUser.setRealName("fwcloud");
    sysUser.setDeptCode("dept");
    sysUser.setUserPhone(String.valueOf(RandomUtil.randomNumber()));
    return sysUser;
}
 
Example #12
Source File: LoginController.java    From jeecg-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 后台生成图形验证码 :有效
 * @param response
 * @param key
 */
@ApiOperation("获取验证码")
@GetMapping(value = "/randomImage/{key}")
public Result<String> randomImage(HttpServletResponse response,@PathVariable String key){
	Result<String> res = new Result<String>();
	try {
		String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
		String lowerCaseCode = code.toLowerCase();
		String realKey = MD5Util.MD5Encode(lowerCaseCode+key, "utf-8");
		redisUtil.set(realKey, lowerCaseCode, 60);
		String base64 = RandImageUtil.generate(code);
		res.setSuccess(true);
		res.setResult(base64);
	} catch (Exception e) {
		res.error500("获取验证码出错"+e.getMessage());
		e.printStackTrace();
	}
	return res;
}
 
Example #13
Source File: VerificationCodeController.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 通用的发送验证码功能
 * <p>
 * 一个系统可能有很多地方需要发送验证码(注册、找回密码等),每增加一个场景,VerificationCodeType 就需要增加一个枚举值
 *
 * @param data
 * @return
 */
@ApiOperation(value = "发送验证码", notes = "发送验证码")
@PostMapping(value = "/send")
public R<Boolean> send(@Validated @RequestBody VerificationCodeDTO data) {
    String code = RandomUtil.randomNumbers(6);

    SmsTask smsTask = SmsTask.builder().build();
    smsTask.setSourceType(SourceType.SERVICE);
    JSONObject param = new JSONObject();
    param.put("1", code);
    smsTask.setTemplateParams(param.toString());
    smsTask.setReceiver(data.getMobile());
    smsTaskService.saveTask(smsTask, TemplateCodeType.ZUIHOU_COMMON);

    String key = CacheKey.buildTenantKey(CacheKey.REGISTER_USER, data.getType().name(), data.getMobile());
    cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
    return R.success();
}
 
Example #14
Source File: LoginController.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
/**
 * 获取校验码
 */
@ApiOperation("获取验证码")
@GetMapping(value = "/getCheckCode")
public Result<Map<String,String>> getCheckCode(){
	Result<Map<String,String>> result = new Result<Map<String,String>>();
	Map<String,String> map = new HashMap<String,String>();
	try {
		String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
		String key = MD5Util.MD5Encode(code+System.currentTimeMillis(), "utf-8");
		redisUtil.set(key, code, 60);
		map.put("key", key);
		map.put("code",code);
		result.setResult(map);
		result.setSuccess(true);
	} catch (Exception e) {
		e.printStackTrace();
		result.setSuccess(false);
	}
	return result;
}
 
Example #15
Source File: VerificationCodeServiceImpl.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(VerificationCode code) {
    EmailVo emailVo;
    String content;
    VerificationCode verificationCode = this.getOne(new QueryWrapper<VerificationCode>()
            .eq("scenes",code.getScenes()).eq("type",code.getType()).eq("value",code.getValue()));
    // 如果不存在有效的验证码,就创建一个新的
    TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
    Template template = engine.getTemplate("email/email.ftl");
    if(verificationCode == null){
        code.setCode(RandomUtil.randomNumbers (6));
        content = template.render(Dict.create().set("code",code.getCode()));
        emailVo = new EmailVo(Collections.singletonList(code.getValue()),"yshop后台管理系统",content);
        this.save(code);
        timedDestruction(code);
    // 存在就再次发送原来的验证码
    } else {
        content = template.render(Dict.create().set("code",verificationCode.getCode()));
        emailVo = new EmailVo(Collections.singletonList(verificationCode.getValue()),"yshop后台管理系统",content);
    }
    return emailVo;
}
 
Example #16
Source File: LoginController.java    From teaching with Apache License 2.0 6 votes vote down vote up
/**
 * 获取校验码
 */
@ApiOperation("获取验证码")
@GetMapping(value = "/getCheckCode")
public Result<Map<String,String>> getCheckCode(){
	Result<Map<String,String>> result = new Result<Map<String,String>>();
	Map<String,String> map = new HashMap<String,String>();
	try {
		String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
		String key = MD5Util.MD5Encode(code+System.currentTimeMillis(), "utf-8");
		redisUtil.set(key, code, 60);
		map.put("key", key);
		//update-begin-author:taoyan date:20200210 for:TASK #3391 【bug】安全问题,返回验证码不安全
		String encode = java.util.Base64.getEncoder().encodeToString(code.getBytes("UTF-8"));
		map.put("code",encode);
		//update-end-author:taoyan date:20200210 for:TASK #3391 【bug】安全问题,返回验证码不安全
		result.setResult(map);
		result.setSuccess(true);
	} catch (Exception e) {
		e.printStackTrace();
		result.setSuccess(false);
	}
	return result;
}
 
Example #17
Source File: LoginController.java    From teaching with Apache License 2.0 6 votes vote down vote up
/**
 * 后台生成图形验证码
 * @param response
 * @param key
 */
@ApiOperation("获取验证码2")
@GetMapping(value = "/randomImage/{key}")
public Result<String> randomImage(HttpServletResponse response,@PathVariable String key){
	Result<String> res = new Result<String>();
	try {
		String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
		String lowerCaseCode = code.toLowerCase();
		String realKey = MD5Util.MD5Encode(lowerCaseCode+key, "utf-8");
		redisUtil.set(realKey, lowerCaseCode, 60);
		String base64 = RandImageUtil.generate(code);
		res.setSuccess(true);
		res.setResult(base64);
	} catch (Exception e) {
		res.error500("获取验证码出错"+e.getMessage());
		e.printStackTrace();
	}
	return res;
}
 
Example #18
Source File: UserController.java    From Taroco with Apache License 2.0 6 votes vote down vote up
/**
 * 发送手机验证码
 *
 * @param mobile
 * @return
 */
@RequestMapping("/smsCode/{mobile}")
@ResponseBody
public ResponseEntity<Response> smsCode(@Pattern (regexp = MOBILE_REG, message = "请输入正确的手机号")
                                        @PathVariable String mobile) {
    Object tempCode = redisRepository.get(CacheConstants.DEFAULT_CODE_KEY + mobile);
    if (tempCode != null) {
        log.error("用户:{}验证码未失效{}", mobile, tempCode);
        return ResponseEntity.ok(Response.failure("验证码: " + tempCode + " 未失效,请失效后再次申请"));
    }
    if (userTransferService.findUserByMobile(mobile) == null) {
        log.error("根据用户手机号:{}, 查询用户为空", mobile);
        return ResponseEntity.ok(Response.failure("手机号不存在"));
    }
    String code = RandomUtil.randomNumbers(6);
    log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
    redisRepository.setExpire(CacheConstants.DEFAULT_CODE_KEY + mobile, code, CacheConstants.DEFAULT_EXPIRE_SECONDS);
    return ResponseEntity.ok(Response.success(code));
}
 
Example #19
Source File: SysUserServiceImpl.java    From Taroco with Apache License 2.0 6 votes vote down vote up
/**
 * 发送验证码
 * <p>
 * 1. 先去redis 查询是否 60S内已经发送
 * 2. 未发送: 判断手机号是否存 ? false :产生6位数字  手机号-验证码
 * 3. 发往消息中心-》发送信息
 * 4. 保存redis
 *
 * @param mobile 手机号
 * @return true、false
 */
@Override
public Response sendSmsCode(String mobile) {
    Object tempCode = redisRepository.get(CacheConstants.DEFAULT_CODE_KEY + mobile);
    if (tempCode != null) {
        log.error("用户:{}验证码未失效{}", mobile, tempCode);
        return Response.failure("验证码: " + tempCode + "未失效,请失效后再次申请");
    }

    SysUser params = new SysUser();
    params.setPhone(mobile);
    List<SysUser> userList = this.list(new QueryWrapper<>(params));

    if (CollectionUtils.isEmpty(userList)) {
        log.error("根据用户手机号:{}, 查询用户为空", mobile);
        return Response.failure("手机号不存在");
    }

    String code = RandomUtil.randomNumbers(6);
    log.info("短信发送请求消息中心 -> 手机号:{} -> 验证码:{}", mobile, code);
    redisRepository.setExpire(CacheConstants.DEFAULT_CODE_KEY + mobile, code, SecurityConstants.DEFAULT_IMAGE_EXPIRE);
    return Response.success(code);
}
 
Example #20
Source File: VerifyServiceImpl.java    From eladmin with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(String email, String key) {
    EmailVo emailVo;
    String content;
    String redisKey = key + email;
    // 如果不存在有效的验证码,就创建一个新的
    TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("template", TemplateConfig.ResourceMode.CLASSPATH));
    Template template = engine.getTemplate("email/email.ftl");
    Object oldCode =  redisUtils.get(redisKey);
    if(oldCode == null){
        String code = RandomUtil.randomNumbers (6);
        // 存入缓存
        if(!redisUtils.set(redisKey, code, expiration)){
            throw new BadRequestException("服务异常,请联系网站负责人");
        }
        content = template.render(Dict.create().set("code",code));
        emailVo = new EmailVo(Collections.singletonList(email),"EL-ADMIN后台管理系统",content);
    // 存在就再次发送原来的验证码
    } else {
        content = template.render(Dict.create().set("code",oldCode));
        emailVo = new EmailVo(Collections.singletonList(email),"EL-ADMIN后台管理系统",content);
    }
    return emailVo;
}
 
Example #21
Source File: VerificationCodeController.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
/**
 * 通用的发送验证码功能
 * <p>
 * 一个系统可能有很多地方需要发送验证码(注册、找回密码等),每增加一个场景,VerificationCodeType 就需要增加一个枚举值
 *
 * @param data
 * @return
 */
@ApiOperation(value = "发送验证码", notes = "发送验证码")
@PostMapping(value = "/send")
public R<Boolean> send(@Validated @RequestBody VerificationCodeDTO data) {
    String code = RandomUtil.randomNumbers(6);

    SmsTask smsTask = SmsTask.builder().build();
    smsTask.setSourceType(SourceType.SERVICE);
    JSONObject param = new JSONObject();
    param.put("1", code);
    smsTask.setTemplateParams(param.toString());
    smsTask.setReceiver(data.getMobile());
    smsTaskService.saveTask(smsTask, TemplateCodeType.ZUIHOU_COMMON);

    String key = CacheKey.buildTenantKey(CacheKey.REGISTER_USER, data.getType().name(), data.getMobile());
    cacheRepository.setExpire(key, code, CacheRepository.DEF_TIMEOUT_5M);
    return R.success();
}
 
Example #22
Source File: OrderTest.java    From java-tutorial with MIT License 6 votes vote down vote up
@Test
public void TestOrderType() throws IllegalAccessException {
    OrderDTO order = new OrderDTO();
    order.setOrderId(RandomUtil.randomNumbers(8));
    order.setOrderType(2);
    order.setPrice(127300.46f);
    order.setOrderDate(DateUtil.parseDate("2019-08-08 12:12"));

    String result = orderService.handleOrder(order);
    System.out.println(order.toString());
    System.out.println(result);

    System.out.println("\n===========================================================================\n");

    order.setOrderId(RandomUtil.randomNumbers(8));
    order.setOrderType(1);
    order.setPrice(145500.46f);
    order.setOrderDate(DateUtil.parseDate("2019-09-09 12:12"));

    result = orderService.handleOrder(order);
    System.out.println(order.toString());
    System.out.println(result);

}
 
Example #23
Source File: LoginController.java    From jeecg-boot with Apache License 2.0 6 votes vote down vote up
/**
 * 后台生成图形验证码 :有效
 * @param response
 * @param key
 */
@ApiOperation("获取验证码")
@GetMapping(value = "/randomImage/{key}")
public Result<String> randomImage(HttpServletResponse response,@PathVariable String key){
	Result<String> res = new Result<String>();
	try {
		String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
		String lowerCaseCode = code.toLowerCase();
		String realKey = MD5Util.MD5Encode(lowerCaseCode+key, "utf-8");
		redisUtil.set(realKey, lowerCaseCode, 60);
		String base64 = RandImageUtil.generate(code);
		res.setSuccess(true);
		res.setResult(base64);
	} catch (Exception e) {
		res.error500("获取验证码出错"+e.getMessage());
		e.printStackTrace();
	}
	return res;
}
 
Example #24
Source File: SMSServiceImpl.java    From spring-cloud-shop with MIT License 6 votes vote down vote up
/**
 * 根据短信渠道获取真实发送的短信内容
 *
 * @param smsCodeEnums 短信渠道枚举
 * @param content      短信模板内容
 * @param phone        手机号码
 * @return 短信发送内容
 */
private String getContent(SMSCodeEnums smsCodeEnums, String content, String phone) {

    switch (smsCodeEnums) {
        case LOGIN_SMS:
            String code = RandomUtil.randomString(RandomUtil.BASE_NUMBER, 6);
            shopRedisTemplate.opsForValue().set("sms:login:code" + phone, code, 10 * 60);
            content = String.format(content, code);
            break;
        case REGISTER_SMS:
            break;
        case FORGET_SMS:
            break;
        case INITIAL_CIPHER_SMS:
            break;
    }
    return content;
}
 
Example #25
Source File: WeiXinPayTestController.java    From springbootexamples with Apache License 2.0 6 votes vote down vote up
/**
    * 获取沙箱环境验签秘钥API
    * https://pay.weixin.qq.com/wiki/doc/api/micropay.php?chapter=23_1
    * @return
    * @throws Exception
    */
@RequestMapping("/getSignKey")
   public Map<String, Object> getSignKey() throws Exception {
	
       Map<String, String> requestData = new HashMap<>();
       requestData.put("appid", weiXinPayProperties.getAppid());
       requestData.put("mch_id", weiXinPayProperties.getMchId());
       requestData.put("nonce_str", RandomUtil.randomString(15));
       String sign = WeiXinUtil.generateSign(requestData,weiXinPayProperties.getKey());//生成签名
       requestData.put("sign", sign);
       
       String mapToXmlStr = XmlUtil.mapToXmlStr(requestData, "xml");
       //调用微信统一下单Api 将xml的String信息作为参数
 		HttpHeaders headers = new HttpHeaders();
 		headers.setContentType(MediaType.APPLICATION_XML);
 		HttpEntity<String> formEntity = new HttpEntity<>(mapToXmlStr, headers);
       
 		ResponseEntity<String> postForEntity = restTemplate.postForEntity(GETSIGNKEYURL, formEntity, String.class);
 		String returnXmlString = postForEntity.getBody();

 		Map<String, Object> responseMap = XmlUtil.xmlToMap(returnXmlString);

       return responseMap;
   }
 
Example #26
Source File: ToolTagDirective.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
    final DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);

    if (params.containsKey(HaloConst.METHOD_KEY)) {
        String method = params.get(HaloConst.METHOD_KEY).toString();
        switch (method) {
            case "rainbowPage":
                int page = Integer.parseInt(params.get("page").toString());
                int total = Integer.parseInt(params.get("total").toString());
                int display = Integer.parseInt(params.get("display").toString());
                env.setVariable("numbers", builder.build().wrap(PageUtil.rainbow(page, total, display)));
                break;
            case "random":
                int min = Integer.parseInt(params.get("min").toString());
                int max = Integer.parseInt(params.get("max").toString());
                env.setVariable("number", builder.build().wrap(RandomUtil.randomInt(min, max)));
                break;
            default:
                break;
        }
    }
    body.render(env.getOut());
}
 
Example #27
Source File: EmailServiceImpl.java    From albedo with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public EmailVo sendEmail(String email, String key) {
	EmailVo emailVo;
	String content;
	String redisKey = key + email;
	// 如果不存在有效的验证码,就创建一个新的
	TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));
	Template template = engine.getTemplate("email/email.ftl");
	Object oldCode = RedisUtil.getCacheString(redisKey);
	if (oldCode == null) {
		String code = RandomUtil.randomNumbers(6);

		// 存入缓存
		RedisUtil.setCacheString(redisKey, code, CommonConstants.DEFAULT_IMAGE_EXPIRE, TimeUnit.SECONDS);

		content = template.render(Dict.create().set("code", code));
		emailVo = new EmailVo(Collections.singletonList(email), "Albedo后台管理系统", content);
		// 存在就再次发送原来的验证码
	} else {
		content = template.render(Dict.create().set("code", oldCode));
		emailVo = new EmailVo(Collections.singletonList(email), "Albedo后台管理系统", content);
	}
	return emailVo;
}
 
Example #28
Source File: TranTestService.java    From Guns with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Transactional(rollbackFor = Exception.class)
public void testSingleSuccess() {

    User user = new User();
    user.setAccount(RandomUtil.randomString(5));
    user.setPassword(RandomUtil.randomString(5));
    user.setCreateTime(new Date());
    user.setUpdateTime(new Date());
    user.setCreateUser(1L);
    user.setUpdateUser(1L);
    gunsDbService.save(user);

    User user2 = new User();
    user2.setAccount(RandomUtil.randomString(5));
    user2.setPassword(RandomUtil.randomString(5));
    user2.setCreateTime(new Date());
    user2.setUpdateTime(new Date());
    user2.setCreateUser(1L);
    user2.setUpdateUser(1L);
    gunsDbService.save(user2);
}
 
Example #29
Source File: PageController.java    From SENS with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 发表页面
 *
 * @param post post
 */
@PostMapping(value = "/save")
@ResponseBody
public JsonResult pushPage(@ModelAttribute Post post) {
    String msg = localeMessageUtil.getMessage("code.admin.common.save-success");
    //发表用户
    User loginUser = getLoginUser();
    post.setUserId(loginUser.getId());
    post.setPostType(PostTypeEnum.POST_TYPE_PAGE.getValue());
    //当没有选择文章缩略图的时候,自动分配一张内置的缩略图
    if (StringUtils.equals(post.getPostThumbnail(), BlogPropertiesEnum.DEFAULT_THUMBNAIL.getProp())) {
        post.setPostThumbnail("/static/images/thumbnail/img_" + RandomUtil.randomInt(0, 14) + ".jpg");
    }
    postService.insertOrUpdate(post);
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), msg);
}
 
Example #30
Source File: PageController.java    From blog-sharon with Apache License 2.0 5 votes vote down vote up
/**
 * 发表页面
 *
 * @param post    post
 * @param session session
 */
@PostMapping(value = "/new/push")
@ResponseBody
public JsonResult pushPage(@ModelAttribute Post post, HttpSession session) {
    String msg = localeMessageUtil.getMessage("code.admin.common.save-success");
    try {
        //发表用户
        User user = (User) session.getAttribute(HaloConst.USER_SESSION_KEY);
        post.setUser(user);
        post.setPostType(PostTypeEnum.POST_TYPE_PAGE.getDesc());
        if (null != post.getPostId()) {
            Post oldPost = postService.findByPostId(post.getPostId()).get();
            if (null == post.getPostDate()) {
                post.setPostDate(DateUtil.date());
            }
            post.setPostViews(oldPost.getPostViews());
            msg = localeMessageUtil.getMessage("code.admin.common.update-success");
        } else {
            post.setPostDate(DateUtil.date());
        }
        post.setPostUpdate(DateUtil.date());
        post.setPostContent(MarkdownUtils.renderMarkdown(post.getPostContentMd()));
        //当没有选择文章缩略图的时候,自动分配一张内置的缩略图
        if (StrUtil.equals(post.getPostThumbnail(), BlogPropertiesEnum.DEFAULT_THUMBNAIL.getProp())) {
            post.setPostThumbnail("/static/halo-frontend/images/thumbnail/thumbnail-" + RandomUtil.randomInt(1, 10) + ".jpg");
        }
        postService.save(post);
        logsService.save(LogsRecord.PUSH_PAGE, post.getPostTitle(), request);
        return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), msg);
    } catch (Exception e) {
        log.error("Save page failed: {}", e.getMessage());
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.save-failed"));
    }
}