cn.hutool.core.util.IdUtil Java Examples

The following examples show how to use cn.hutool.core.util.IdUtil. 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: SmsController.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
/**
 * 保存消息信息
 */
@ApiOperation(value = "保存消息信息", notes = "保存消息信息")
@PostMapping("/save")
@RequiresPermissions("sms/sms/save")
public CommonResult save(@Valid @RequestBody SysSms sysSms) {
    try {
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        long id = snowflake.nextId();
        sysSms.setId(id);
        sysSms.setCreateTime(new Date());
        sysSms.setCreateUser(ShiroUtil.getUser().getId());
        sysSms.setUpdateTime(new Date());
        sysSms.setUpdateUser(ShiroUtil.getUser().getId());
        smsService.save(sysSms);
        return CommonResult.success("添加成功");
    } catch (Exception e) {
        e.printStackTrace();
        return CommonResult.failed("运行异常,请联系管理员");
    }
}
 
Example #2
Source File: FileUtil.java    From eladmin with Apache License 2.0 6 votes vote down vote up
/**
 * 导出excel
 */
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
    String tempPath = SYS_TEM_DIR + IdUtil.fastSimpleUUID() + ".xlsx";
    File file = new File(tempPath);
    BigExcelWriter writer = ExcelUtil.getBigWriter(file);
    // 一次性写出内容,使用默认样式,强制输出标题
    writer.write(list, true);
    //response为HttpServletResponse对象
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
    response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");
    ServletOutputStream out = response.getOutputStream();
    // 终止后删除临时文件
    file.deleteOnExit();
    writer.flush(out, true);
    //此处记得关闭输出Servlet流
    IoUtil.close(out);
}
 
Example #3
Source File: TokenProvider.java    From eladmin with Apache License 2.0 6 votes vote down vote up
/**
 * 创建Token 设置永不过期,
 * Token 的时间有效性转到Redis 维护
 *
 * @param authentication /
 * @return /
 */
public String createToken(Authentication authentication) {
    /*
     * 获取权限列表
     */
    String authorities = authentication.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority)
            .collect(Collectors.joining(","));

    return jwtBuilder
            // 加入ID确保生成的 Token 都不一致
            .setId(IdUtil.simpleUUID())
            .claim(AUTHORITIES_KEY, authorities)
            .setSubject(authentication.getName())
            .compact();
}
 
Example #4
Source File: SshInstallAgentController.java    From Jpom with MIT License 6 votes vote down vote up
private String getAuthorize(SshModel sshModel, NodeModel nodeModel, String path) {
    File saveFile = null;
    try {
        String tempFilePath = ServerConfigBean.getInstance().getUserTempPath().getAbsolutePath();
        //  获取远程的授权信息
        String normalize = FileUtil.normalize(StrUtil.format("{}/{}/{}", path, ConfigBean.DATA, ConfigBean.AUTHORIZE));
        saveFile = FileUtil.file(tempFilePath, IdUtil.fastSimpleUUID() + ConfigBean.AUTHORIZE);
        sshService.download(sshModel, normalize, saveFile);
        //
        String json = FileUtil.readString(saveFile, CharsetUtil.CHARSET_UTF_8);
        AgentAutoUser autoUser = JSONObject.parseObject(json, AgentAutoUser.class);
        nodeModel.setLoginPwd(autoUser.getAgentPwd());
        nodeModel.setLoginName(autoUser.getAgentName());
    } catch (Exception e) {
        DefaultSystemLog.getLog().error("拉取授权信息失败", e);
        return JsonMessage.getString(500, "获取授权信息失败", e);
    } finally {
        FileUtil.del(saveFile);
    }
    return null;
}
 
Example #5
Source File: FileUtil.java    From eladmin with Apache License 2.0 6 votes vote down vote up
/**
 * MultipartFile转File
 */
public static File toFile(MultipartFile multipartFile) {
    // 获取文件名
    String fileName = multipartFile.getOriginalFilename();
    // 获取文件后缀
    String prefix = "." + getExtensionName(fileName);
    File file = null;
    try {
        // 用uuid作为文件名,防止生成的临时文件重复
        file = File.createTempFile(IdUtil.simpleUUID(), prefix);
        // MultipartFile to File
        multipartFile.transferTo(file);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
    return file;
}
 
Example #6
Source File: QuartzJobServiceImpl.java    From eladmin with Apache License 2.0 6 votes vote down vote up
@Async
@Override
@Transactional(rollbackFor = Exception.class)
public void executionSubJob(String[] tasks) throws InterruptedException {
    for (String id : tasks) {
        QuartzJob quartzJob = findById(Long.parseLong(id));
        // 执行任务
        String uuid = IdUtil.simpleUUID();
        quartzJob.setUuid(uuid);
        // 执行任务
        execution(quartzJob);
        // 获取执行状态,如果执行失败则停止后面的子任务执行
        Boolean result = (Boolean) redisUtils.get(uuid);
        while (result == null) {
            // 休眠5秒,再次获取子任务执行情况
            Thread.sleep(5000);
            result = (Boolean) redisUtils.get(uuid);
        }
        if(!result){
            redisUtils.del(uuid);
            break;
        }
    }
}
 
Example #7
Source File: SshService.java    From Jpom with MIT License 6 votes vote down vote up
public static Session getSession(SshModel sshModel) {
    if (sshModel.getConnectType() == SshModel.ConnectType.PASS) {
        return JschUtil.openSession(sshModel.getHost(), sshModel.getPort(), sshModel.getUser(), sshModel.getPassword());
    }
    if (sshModel.getConnectType() == SshModel.ConnectType.PUBKEY) {
        File tempPath = ServerConfigBean.getInstance().getTempPath();
        String sshFile = StrUtil.emptyToDefault(sshModel.getId(), IdUtil.fastSimpleUUID());
        File ssh = FileUtil.file(tempPath, "ssh", sshFile);
        FileUtil.writeString(sshModel.getPrivateKey(), ssh, CharsetUtil.UTF_8);
        byte[] pas = null;
        if (StrUtil.isNotEmpty(sshModel.getPassword())) {
            pas = sshModel.getPassword().getBytes();
        }
        return JschUtil.openSession(sshModel.getHost(), sshModel.getPort(), sshModel.getUser(), FileUtil.getAbsolutePath(ssh), pas);
    }
    throw new IllegalArgumentException("不支持的模式");
}
 
Example #8
Source File: AttachFileServiceImpl.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public String uploadFile(byte[] bytes,String originalName) throws QiniuException {
	String extName = FileUtil.extName(originalName);
	String fileName =DateUtil.format(new Date(), NORM_MONTH_PATTERN)+ IdUtil.simpleUUID() + "." + extName;


	AttachFile attachFile = new AttachFile();
	attachFile.setFilePath(fileName);
	attachFile.setFileSize(bytes.length);
	attachFile.setFileType(extName);
	attachFile.setUploadTime(new Date());
	attachFileMapper.insert(attachFile);

	String upToken = auth.uploadToken(qiniu.getBucket(),fileName);
    Response response = uploadManager.put(bytes, fileName, upToken);
    Json.parseObject(response.bodyString(),  DefaultPutRet.class);
	return fileName;
}
 
Example #9
Source File: LoginController.java    From Shiro-Action with MIT License 6 votes vote down vote up
@PostMapping("/register")
@ResponseBody
public ResultBean register(User user) {
    userService.checkUserNameExistOnCreate(user.getUsername());
    String activeCode = IdUtil.fastSimpleUUID();
    user.setActiveCode(activeCode);
    user.setStatus("0");

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String url = request.getScheme() + "://"
            + request.getServerName()
            + ":"
            + request.getServerPort()
            + "/active/"
            + activeCode;
    Context context = new Context();
    context.setVariable("url", url);
    String mailContent = templateEngine.process("mail/registerTemplate", context);
    new Thread(() ->
            mailService.sendHTMLMail(user.getEmail(), "Shiro-Action 激活邮件", mailContent))
            .start();

    // 注册后默认的角色, 根据自己数据库的角色表 ID 设置
    Integer[] initRoleIds = {2};
    return ResultBean.success(userService.add(user, initRoleIds));
}
 
Example #10
Source File: GoodsSkuServiceImpl.java    From spring-cloud-shop with MIT License 6 votes vote down vote up
@Override
public Response<Long> create(GoodsSkuSaveRequest request) {
    GoodsSku sku = this.convert(request);
    sku.setCreateTime(DateUtils.dateTime());
    sku.setUpdateTime(DateUtils.dateTime());
    sku.setDeleteStatus(Boolean.FALSE);
    // 处理编码
    sku.setSkuCode(SKU_PREFIX + IdUtil.createSnowflake(1, 1).nextId());
    this.baseMapper.insert(sku);
    // 处理图片集
    if (CollectionUtils.isNotEmpty(request.getImages())) {

        GoodsSkuImage skuImage = new GoodsSkuImage();
        skuImage.setGoodsId(request.getGoodsId());
        skuImage.setSkuId(sku.getId());
        skuImage.setImages(JSON.toJSONString(request.getImages()));
        skuImage.setCreateUser(request.getCreateUser());
        skuImage.setUpdateUser(request.getUpdateUser());
        skuImage.setCreateTime(DateUtils.dateTime());
        skuImage.setUpdateTime(DateUtils.dateTime());
        skuImage.setDeleteStatus(Boolean.FALSE);
        goodsSkuImageMapper.insert(skuImage);
    }

    return new Response<>(sku.getId());
}
 
Example #11
Source File: AgentService.java    From runscore with Apache License 2.0 6 votes vote down vote up
/**
 * 生成邀请码
 * 
 * @param param
 * @return
 */
@ParamValid
@Transactional
public String generateInviteCode(GenerateInviteCodeParam param) {
	RegisterSetting setting = inviteRegisterSettingRepo.findTopByOrderByLatelyUpdateTime();
	if (setting == null || !setting.getInviteRegisterEnabled()) {
		throw new BizException(BizError.邀请注册功能已关闭);
	}

	String code = IdUtil.fastSimpleUUID().substring(0, 6);
	while (inviteCodeRepo.findTopByCodeAndPeriodOfValidityGreaterThanEqual(code, new Date()) != null) {
		code = IdUtil.fastSimpleUUID().substring(0, 6);
	}
	InviteCode newInviteCode = param.convertToPo(code, setting.getInviteCodeEffectiveDuration());
	inviteCodeRepo.save(newInviteCode);
	return newInviteCode.getId();
}
 
Example #12
Source File: SysLoginController.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
/**
 * 获取验证码
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/sys/captcha")
public CommonResult captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
    SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
    String verCode = specCaptcha.text().toLowerCase();
    String key = IdUtil.fastUUID();
    // 存入redis并设置过期时间为30分钟
    redisService.set(key,verCode,30*60);
    // 将key和base64返回给前端
    ConcurrentMap<String,Object> dataMap=new ConcurrentHashMap<>();
    dataMap.put("key",key);
    dataMap.put("image",specCaptcha.toBase64());
    return CommonResult.success(dataMap);
}
 
Example #13
Source File: FileUtils.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
/**
 * MultipartFile转File
 */
public static File toFile(MultipartFile multipartFile){
    // 获取文件名
    String fileName = multipartFile.getOriginalFilename();
    // 获取文件后缀
    String prefix="."+getExtensionName(fileName);
    File file = null;
    try {
        // 用uuid作为文件名,防止生成的临时文件重复
        file = File.createTempFile(IdUtil.simpleUUID(), prefix);
        // MultipartFile to File
        multipartFile.transferTo(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file;
}
 
Example #14
Source File: FileUtils.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
/**
 * 导出excel
 */
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
    String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
    File file = new File(tempPath);
    BigExcelWriter writer= ExcelUtil.getBigWriter(file);
    // 一次性写出内容,使用默认样式,强制输出标题
    writer.write(list, true);
    //response为HttpServletResponse对象
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
    response.setHeader("Content-Disposition","attachment;filename=file.xlsx");
    ServletOutputStream out=response.getOutputStream();
    // 终止后删除临时文件
    file.deleteOnExit();
    writer.flush(out, true);
    //此处记得关闭输出Servlet流
    IoUtil.close(out);
}
 
Example #15
Source File: AuthController.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
@AnonymousAccess
@ApiOperation("获取验证码")
@GetMapping(value = "/code")
public ResponseEntity<Object> getCode(){
    // 算术类型 https://gitee.com/whvse/EasyCaptcha
    ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
    // 几位数运算,默认是两位
    captcha.setLen(2);
    // 获取运算的结果
    String result ="";
    try {
        result = new Double(Double.parseDouble(captcha.text())).intValue()+"";
    }catch (Exception e){
        result = captcha.text();
    }
    String uuid = properties.getCodeKey() + IdUtil.simpleUUID();
    // 保存
    redisUtils.set(uuid, result, expiration, TimeUnit.MINUTES);
    // 验证码信息
    Map<String,Object> imgResult = new HashMap<String,Object>(2){{
        put("img", captcha.toBase64());
        put("uuid", uuid);
    }};
    return ResponseEntity.ok(imgResult);
}
 
Example #16
Source File: AuthController.java    From sk-admin with Apache License 2.0 6 votes vote down vote up
@AnonymousAccess
@ApiOperation("获取验证码")
@GetMapping(value = "/code")
public ResponseEntity<Object> getCode() {
    // 算术类型 https://gitee.com/whvse/EasyCaptcha
    ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
    // 几位数运算,默认是两位
    captcha.setLen(2);
    // 获取运算的结果
    String result = captcha.text();
    String uuid = properties.getCodeKey() + IdUtil.simpleUUID();
    // 保存
    redisUtils.set(uuid, result, expiration, TimeUnit.MINUTES);
    // 验证码信息
    Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
        put("img", captcha.toBase64());
        put("uuid", uuid);
    }};
    return ResponseEntity.ok(imgResult);
}
 
Example #17
Source File: ExecutorJobHandler.java    From datax-web with MIT License 6 votes vote down vote up
private String generateTemJsonFile(String jobJson) {
    String tmpFilePath;
    String dataXHomePath = SystemUtils.getDataXHomePath();
    if (StringUtils.isNotEmpty(dataXHomePath)) {
        jsonPath = dataXHomePath + DEFAULT_JSON;
    }
    if (!FileUtil.exist(jsonPath)) {
        FileUtil.mkdir(jsonPath);
    }
    tmpFilePath = jsonPath + "jobTmp-" + IdUtil.simpleUUID() + ".conf";
    // 根据json写入到临时本地文件
    try (PrintWriter writer = new PrintWriter(tmpFilePath, "UTF-8")) {
        writer.println(jobJson);
    } catch (FileNotFoundException | UnsupportedEncodingException e) {
        JobLogger.log("JSON 临时文件写入异常:" + e.getMessage());
    }
    return tmpFilePath;
}
 
Example #18
Source File: FileUtil.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
/**
 * 导出excel
 */
public static void downloadExcel(List<Map<String, Object>> list, HttpServletResponse response) throws IOException {
    String tempPath =System.getProperty("java.io.tmpdir") + IdUtil.fastSimpleUUID() + ".xlsx";
    File file = new File(tempPath);
    BigExcelWriter writer= ExcelUtil.getBigWriter(file);
    // 一次性写出内容,使用默认样式,强制输出标题
    writer.write(list, true);
    //response为HttpServletResponse对象
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
    response.setHeader("Content-Disposition","attachment;filename=file.xlsx");
    ServletOutputStream out=response.getOutputStream();
    // 终止后删除临时文件
    file.deleteOnExit();
    writer.flush(out, true);
    //此处记得关闭输出Servlet流
    IoUtil.close(out);
}
 
Example #19
Source File: FileUtil.java    From yshopmall with Apache License 2.0 6 votes vote down vote up
/**
 * MultipartFile转File
 */
public static File toFile(MultipartFile multipartFile){
    // 获取文件名
    String fileName = multipartFile.getOriginalFilename();
    // 获取文件后缀
    String prefix="."+getExtensionName(fileName);
    File file = null;
    try {
        // 用uuid作为文件名,防止生成的临时文件重复
        file = File.createTempFile(IdUtil.simpleUUID(), prefix);
        // MultipartFile to File
        multipartFile.transferTo(file);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return file;
}
 
Example #20
Source File: UserServiceTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 测试Mybatis-Plus 批量新增
 */
@Test
public void testSaveList() {
    List<User> userList = Lists.newArrayList();
    for (int i = 4; i < 14; i++) {
        String salt = IdUtil.fastSimpleUUID();
        User user = User.builder().name("testSave" + i).password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave" + i + "@xkcoding.com").phoneNumber("1730000000" + i).status(1).lastLoginTime(new DateTime()).build();
        userList.add(user);
    }
    boolean batch = userService.saveBatch(userList);
    Assert.assertTrue(batch);
    List<Long> ids = userList.stream().map(User::getId).collect(Collectors.toList());
    log.debug("【userList#ids】= {}", ids);
}
 
Example #21
Source File: AttachmentServiceImpl.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
@Override
public AttachmentDTO upload(MultipartFile multipartFile, String tenant, Long id, String bizType, String bizId, Boolean isSingle) {
    //根据业务类型来判断是否生成业务id
    if (StringUtils.isNotEmpty(bizType) && StringUtils.isEmpty(bizId)) {
        DatabaseProperties.Id idPro = databaseProperties.getId();
        bizId = IdUtil.getSnowflake(idPro.getWorkerId(), idPro.getDataCenterId()).nextIdStr();
    }
    File file = fileStrategy.upload(multipartFile);

    Attachment attachment = BeanPlusUtil.toBean(file, Attachment.class);

    attachment.setBizId(bizId);
    attachment.setBizType(bizType);
    setDate(attachment);

    if (isSingle) {
        super.remove(Wraps.<Attachment>lbQ().eq(Attachment::getBizId, bizId).eq(Attachment::getBizType, bizType));
    }

    if (id != null && id > 0) {
        //当前端传递了文件id时,修改这条记录
        attachment.setId(id);
        super.updateById(attachment);
    } else {
        super.save(attachment);
    }

    AttachmentDTO dto = BeanPlusUtil.toBean(attachment, AttachmentDTO.class);
    dto.setDownloadUrlByBizId(fileProperties.getDownByBizId(bizId));
    dto.setDownloadUrlById(fileProperties.getDownById(attachment.getId()));
    dto.setDownloadUrlByUrl(fileProperties.getDownByUrl(attachment.getUrl(), attachment.getSubmittedFileName()));
    return dto;
}
 
Example #22
Source File: UserServiceTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@Test
public void saveUserList() {
    List<User> users = Lists.newArrayList();
    for (int i = 5; i < 15; i++) {
        String salt = IdUtil.fastSimpleUUID();
        User user = User.builder().name("testSave" + i).password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave" + i + "@xkcoding.com").phoneNumber("1730000000" + i).status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build();
        users.add(user);
    }
    userService.saveUserList(users);
    Assert.assertTrue(userService.getUserList().size() > 2);
}
 
Example #23
Source File: UserDaoTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 测试保存
 */
@Test
public void testSave() {
    String salt = IdUtil.fastSimpleUUID();
    User testSave3 = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("[email protected]").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).build();
    userDao.save(testSave3);

    Assert.assertNotNull(testSave3.getId());
    Optional<User> byId = userDao.findById(testSave3.getId());
    Assert.assertTrue(byId.isPresent());
    log.debug("【byId】= {}", byId.get());
}
 
Example #24
Source File: ColumnInitSystemStrategy.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 我*,这种方式太脑残了,但想不出更好的方式初始化数据,希望各位大神有好的初始化方法记得跟我说声!!!
 * 写这段代码写得想去si ~~~
 * <p>
 * 不能用 SCHEMA 模式的初始化脚本方法: 因为id 会重复,租户编码会重复!
 *
 * @param tenant 待初始化租户编码
 * @return
 */
@Override
public boolean init(String tenant) {
    // 初始化数据
    //1, 生成并关联 ID TENANT
    DatabaseProperties.Id id = databaseProperties.getId();
    Snowflake snowflake = IdUtil.getSnowflake(id.getWorkerId(), id.getDataCenterId());

    BaseContextHandler.setTenant(tenant);

    // 菜单 资源 角色 角色_资源 字典 参数
    List<Menu> menuList = new ArrayList<>();
    Map<String, Long> menuMap = new HashMap<>();
    boolean menuFlag = initMenu(snowflake, menuList, menuMap);

    List<Resource> resourceList = new ArrayList<>();
    boolean resourceFlag = initResource(resourceList, menuMap);

    // 角色
    Long roleId = snowflake.nextId();
    boolean roleFlag = initRole(roleId);

    // 资源权限
    boolean roleAuthorityFlag = initRoleAuthority(menuList, resourceList, roleId);

    // 字典
    initDict();

    //参数
    initParameter();

    initApplication();

    return menuFlag && resourceFlag && roleFlag && roleAuthorityFlag;
}
 
Example #25
Source File: StaticPageServiceImpl.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
@Nullable
private List<StaticPageFile> listStaticPageFileTree(@NonNull Path topPath) {
    Assert.notNull(topPath, "Top path must not be null");

    if (!Files.isDirectory(topPath)) {
        return null;
    }

    try (Stream<Path> pathStream = Files.list(topPath)) {
        List<StaticPageFile> staticPageFiles = new LinkedList<>();

        pathStream.forEach(path -> {
            StaticPageFile staticPageFile = new StaticPageFile();
            staticPageFile.setId(IdUtil.fastSimpleUUID());
            staticPageFile.setName(path.getFileName().toString());
            staticPageFile.setIsFile(Files.isRegularFile(path));
            if (Files.isDirectory(path)) {
                staticPageFile.setChildren(listStaticPageFileTree(path));
            }

            staticPageFiles.add(staticPageFile);
        });

        staticPageFiles.sort(new StaticPageFile());
        return staticPageFiles;
    } catch (IOException e) {
        throw new ServiceException("Failed to list sub files", e);
    }
}
 
Example #26
Source File: UserDaoTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 初始化10条数据
 */
private void initData() {
    List<User> userList = Lists.newArrayList();
    for (int i = 0; i < 10; i++) {
        String salt = IdUtil.fastSimpleUUID();
        int index = 3 + i;
        User user = User.builder().name("testSave" + index).password(SecureUtil.md5("123456" + salt)).salt(salt).email("testSave" + index + "@xkcoding.com").phoneNumber("1730000000" + index).status(1).lastLoginTime(new DateTime()).build();
        userList.add(user);
    }
    userDao.saveAll(userList);
}
 
Example #27
Source File: UserMapperTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 测试保存
 */
@Test
public void saveUser() {
    String salt = IdUtil.fastSimpleUUID();
    User user = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("[email protected]").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build();
    int i = userMapper.saveUser(user);
    Assert.assertEquals(1, i);
}
 
Example #28
Source File: UserServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 保存用户
 *
 * @param user 用户实体
 * @return 保存成功 {@code true} 保存失败 {@code false}
 */
@Override
public Boolean save(User user) {
	String rawPass = user.getPassword();
	String salt = IdUtil.simpleUUID();
	String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt);
	user.setPassword(pass);
	user.setSalt(salt);
	return userDao.insert(user) > 0;
}
 
Example #29
Source File: UserServiceImpl.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 更新用户
 *
 * @param user 用户实体
 * @param id   主键id
 * @return 更新成功 {@code true} 更新失败 {@code false}
 */
@Override
public Boolean update(User user, Long id) {
	User exist = getUser(id);
	if (StrUtil.isNotBlank(user.getPassword())) {
		String rawPass = user.getPassword();
		String salt = IdUtil.simpleUUID();
		String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt);
		user.setPassword(pass);
		user.setSalt(salt);
	}
	BeanUtil.copyProperties(user, exist, CopyOptions.create().setIgnoreNullValue(true));
	exist.setLastUpdateTime(new DateTime());
	return userDao.update(exist, id) > 0;
}
 
Example #30
Source File: UserMapperTest.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 测试保存
 */
@Test
public void saveUser() {
    String salt = IdUtil.fastSimpleUUID();
    User user = User.builder().name("testSave3").password(SecureUtil.md5("123456" + salt)).salt(salt).email("[email protected]").phoneNumber("17300000003").status(1).lastLoginTime(new DateTime()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build();
    int i = userMapper.saveUser(user);
    Assert.assertEquals(1, i);
}