下面列出了怎么用cn.hutool.core.util.IdUtil的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
/**
* 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;
}
/**
* 导出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);
}
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;
}
/**
* 生成邀请码
*
* @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();
}
@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;
}
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;
}
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("不支持的模式");
}
/**
* 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;
}
/**
* 导出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);
}
@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);
}
/**
* 保存消息信息
*/
@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("运行异常,请联系管理员");
}
}
/**
* 创建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();
}
@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;
}
}
}
/**
* 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;
}
/**
* 导出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);
}
@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));
}
@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());
}
public String createToken(Authentication authentication) {
String authorities = authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.joining(","));
return Jwts.builder()
.setSubject(authentication.getName())
.claim(AUTHORITIES_KEY, authorities)
.signWith(key, SignatureAlgorithm.HS512)
// 加入ID确保生成的 Token 都不一致
.setId(IdUtil.simpleUUID())
.compact();
}
public int insertErpSFamilyMember(ErpStudent item) {
List<ErpSFamilyMember> list = item.getErpSFamilyMemberList();
for(ErpSFamilyMember sFamilyMember: list) {
sFamilyMember.setId(IdUtil.simpleUUID());
sFamilyMember.setStudId(item.getId());
}
if(list.size() > 0) {
return sFamilyMemberService.insertList(list);
}
return 0;
}
/**
* 测试通用Mapper - 保存
*/
@Test
public void testInsert() {
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()).createTime(new DateTime()).lastUpdateTime(new DateTime()).build();
userMapper.insertUseGeneratedKeys(testSave3);
Assert.assertNotNull(testSave3.getId());
log.debug("【测试主键回写#testSave3.getId()】= {}", testSave3.getId());
}
public BaseRequest(ReqType reqType, IProtocol protocol) {
Objects.requireNonNull(reqType, "请求对象枚举值不能为空");
// Objects.requireNonNull(protocol, "协议对象不能为空");
setId(IdUtil.objectId());
setProtocol(protocol);
setReqType(reqType);
paramMap = new HashMap();
isNeedAdapterOperation = false;
isNeedSend = false;
isNeedRepeatSend = true;
}
private TransportOrderModel(String vehicleName, String finalPosition, String finalLocation, String finalOperation, List<String> pointPaths,
List<LocationOperation> locationOperationList) {
this.id = IdUtil.objectId();
this.vehicleName = vehicleName;
this.finalPosition = finalPosition;
this.finalLocation = finalLocation;
this.finalOperation = finalOperation;
this.pointPaths = pointPaths;
if (null != pointPaths) {
this.pointPathStr = CollectionUtil.join(pointPaths.iterator(), ",");
}
this.locationOperationList = locationOperationList;
}
@Override
public Object run() {
//链路追踪id
String traceId = IdUtil.fastSimpleUUID();
MDC.put(CommonConstant.LOG_TRACE_ID, traceId);
RequestContext ctx = RequestContext.getCurrentContext();
ctx.addZuulRequestHeader(CommonConstant.TRACE_ID_HEADER, traceId);
return null;
}
@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();
user = userService.saveUser(user);
Assert.assertTrue(ObjectUtil.isNotNull(user.getId()));
log.debug("【user】= {}", user);
}
@Override
@Transactional(rollbackFor = Exception.class)
@RedisLock(lockName = "insertUser", key = "#appConnect.appId + ':' + #appConnect.bizUserId")
@Caching(evict = {
@CacheEvict(cacheNames = "yami_user", key = "#appConnect.appId + ':' + #appConnect.bizUserId"),
@CacheEvict(cacheNames = "AppConnect", key = "#appConnect.appId + ':' + #appConnect.bizUserId")
})
public void insertUserIfNecessary(AppConnect appConnect) {
// 进入锁后再重新判断一遍用户是否创建
AppConnect dbAppConnect = appConnectMapper.getByBizUserId(appConnect.getBizUserId(), appConnect.getAppId());
if(dbAppConnect != null) {
return;
}
String bizUnionId = appConnect.getBizUnionid();
String userId = null;
User user;
if (StrUtil.isNotBlank(bizUnionId)) {
userId = appConnectMapper.getUserIdByUnionId(bizUnionId);
}
if (StrUtil.isBlank(userId)) {
userId = IdUtil.simpleUUID();
Date now = new Date();
user = new User();
user.setUserId(userId);
user.setModifyTime(now);
user.setUserRegtime(now);
user.setStatus(1);
user.setNickName(EmojiUtil.toAlias(StrUtil.isBlank(appConnect.getNickName()) ? "" : appConnect.getNickName()));
user.setPic(appConnect.getImageUrl());
userMapper.insert(user);
} else {
user = userMapper.selectById(userId);
}
appConnect.setUserId(user.getUserId());
appConnectMapper.insert(appConnect);
}
/**
* 保存用户
*
* @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;
}
@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String update(JdkInfoModel model) {
String path = model.getPath();
if (StrUtil.isEmpty(path)) {
return JsonMessage.getString(400, "请填写jdk路径");
}
String newPath = FileUtil.normalize(path);
File file = FileUtil.file(newPath);
//去除bin
if ("bin".equals(file.getName())) {
newPath = file.getParentFile().getAbsolutePath();
}
if (!FileUtils.isJdkPath(newPath)) {
return JsonMessage.getString(400, "路径错误,该路径不是jdk路径");
}
model.setPath(newPath);
String id = model.getId();
String jdkVersion = FileUtils.getJdkVersion(newPath);
model.setVersion(jdkVersion);
String name = model.getName();
if (StrUtil.isEmpty(name)) {
model.setName(jdkVersion);
}
if (StrUtil.isEmpty(id)) {
model.setId(IdUtil.fastSimpleUUID());
jdkInfoService.addItem(model);
return JsonMessage.getString(200, "添加成功");
}
jdkInfoService.updateItem(model);
return JsonMessage.getString(200, "修改成功");
}
/**
* 使用中的jdk
*
* @return JdkInfoModel
*/
private JdkInfoModel getDefaultJdk() {
JavaRuntimeInfo info = new JavaRuntimeInfo();
String homeDir = info.getHomeDir();
String version = new JavaInfo().getVersion();
if (StrUtil.isEmpty(homeDir) || StrUtil.isEmpty(version)) {
return null;
}
String path = FileUtil.normalize(homeDir.replace("jre", ""));
JdkInfoModel jdkInfoModel = new JdkInfoModel();
jdkInfoModel.setId(IdUtil.fastUUID());
jdkInfoModel.setVersion(version);
jdkInfoModel.setPath(path);
return jdkInfoModel;
}
@Override
protected void handleTextMessage(Map<String, Object> attributes, ProxySession proxySession, JSONObject json, ConsoleCommandOp consoleCommandOp) {
UserOperateLogV1.OptType type = null;
switch (consoleCommandOp) {
case stop:
type = UserOperateLogV1.OptType.Stop;
break;
case start:
type = UserOperateLogV1.OptType.Start;
break;
case restart:
type = UserOperateLogV1.OptType.Restart;
break;
default:
break;
}
if (type != null) {
// 记录操作日志
UserModel userInfo = (UserModel) attributes.get("userInfo");
String reqId = IdUtil.fastUUID();
json.put("reqId", reqId);
//
String projectId = (String) attributes.get("projectId");
OperateLogController.CacheInfo cacheInfo = cacheInfo(attributes, json, type, projectId);
try {
operateLogController.log(reqId, userInfo, "还没有响应", cacheInfo);
} catch (Exception e) {
DefaultSystemLog.getLog().error("记录操作日志异常", e);
}
}
proxySession.send(json.toString());
}