cn.hutool.core.util.StrUtil Java Examples
The following examples show how to use
cn.hutool.core.util.StrUtil.
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: YxMiniPayService.java From yshopmall with Apache License 2.0 | 7 votes |
/** * 退款 * @param orderId * @param totalFee * @throws WxPayException */ public void refundOrder(String orderId, Integer totalFee) throws WxPayException { String apiUrl = redisHandler.getVal(ShopKeyUtils.getApiUrl()); if (StrUtil.isBlank(apiUrl)) throw new ErrorRequestException("请配置api地址"); WxPayService wxPayService = WxPayConfiguration.getWxAppPayService(); WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest(); wxPayRefundRequest.setTotalFee(totalFee);//订单总金额 wxPayRefundRequest.setOutTradeNo(orderId); wxPayRefundRequest.setOutRefundNo(orderId); wxPayRefundRequest.setRefundFee(totalFee);//退款金额 wxPayRefundRequest.setNotifyUrl(apiUrl + "/api/notify/refund"); wxPayService.refund(wxPayRefundRequest); }
Example #2
Source File: RoleModel.java From Jpom with MIT License | 6 votes |
private boolean forTree(List<TreeLevel> treeLevels, ClassFeature classFeature, String dataId) { if (treeLevels == null || treeLevels.isEmpty()) { return false; } for (TreeLevel treeLevel : treeLevels) { ClassFeature nowFeature = ClassFeature.valueOf(treeLevel.getClassFeature()); if (nowFeature == classFeature && StrUtil.equals(treeLevel.getData(), dataId)) { // 是同一个功能 return true; } if (nowFeature != classFeature) { List<TreeLevel> children = treeLevel.getChildren(); if (forTree(children, classFeature, dataId)) { return true; } } } return false; }
Example #3
Source File: SettingController.java From sk-admin with Apache License 2.0 | 6 votes |
@RequestMapping(value = "/oss/{serviceName}", method = RequestMethod.GET) @ApiOperation(value = "查看OSS配置") public Result<OssSetting> oss(@PathVariable String serviceName) { Setting setting = new Setting(); if (serviceName.equals(SettingConstant.QINIU_OSS) || serviceName.equals(SettingConstant.ALI_OSS) || serviceName.equals(SettingConstant.TENCENT_OSS) || serviceName.equals(SettingConstant.MINIO_OSS) || serviceName.equals(SettingConstant.LOCAL_OSS)) { setting = settingService.get(serviceName); } if (setting == null || StrUtil.isBlank(setting.getValue())) { return new ResultUtil<OssSetting>().setData(null); } OssSetting ossSetting = new Gson().fromJson(setting.getValue(), OssSetting.class); ossSetting.setSecretKey("**********"); return new ResultUtil<OssSetting>().setData(ossSetting); }
Example #4
Source File: LoginService.java From v-mock with MIT License | 6 votes |
/** * 登录 */ public User login(String username, String password) { // 用户名或密码为空 错误 if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) { throw new UserNotExistsException(); } // 查询用户信息 User user = userService.selectUserByLoginName(username); if (user == null) { throw new UserNotExistsException(); } if (UserStatus.DISABLE.getCode().equals(user.getStatus())) { throw new UserBlockedException(); } passwordService.validate(user, password); recordLoginInfo(user); return user; }
Example #5
Source File: GlobalUserController.java From zuihou-admin-boot with Apache License 2.0 | 6 votes |
@Override public R<GlobalUser> handlerSave(GlobalUserSaveDTO model) { if (StrUtil.isEmpty(model.getTenantCode()) || BizConstant.SUPER_TENANT.equals(model.getTenantCode())) { return success(baseService.save(model)); } else { BaseContextHandler.setTenant(model.getTenantCode()); User user = BeanPlusUtil.toBean(model, User.class); user.setName(StrHelper.getOrDef(model.getName(), model.getAccount())); if (StrUtil.isEmpty(user.getPassword())) { user.setPassword(BizConstant.DEF_PASSWORD); } user.setStatus(true); userService.initUser(user); return success(BeanPlusUtil.toBean(user, GlobalUser.class)); } }
Example #6
Source File: PostController.java From stone with GNU General Public License v3.0 | 6 votes |
/** * 将所有文章推送到百度 * * @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 #7
Source File: OutGivingController.java From Jpom with MIT License | 6 votes |
@RequestMapping(value = "edit.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE) @Feature(method = MethodFeature.EDIT) public String edit(String id) { setAttribute("type", "add"); if (StrUtil.isNotEmpty(id)) { OutGivingModel outGivingModel = outGivingServer.getItem(id); if (outGivingModel != null) { setAttribute("item", outGivingModel); setAttribute("type", "edit"); } } UserModel userModel = getUser(); List<NodeModel> nodeModels = nodeService.listAndProject(); setAttribute("nodeModels", nodeModels); // String reqId = nodeService.cacheNodeList(nodeModels); setAttribute("reqId", reqId); JSONArray afterOpt = BaseEnum.toJSONArray(AfterOpt.class); setAttribute("afterOpt", afterOpt); return "outgiving/edit"; }
Example #8
Source File: PasswordDecoderFilter.java From albedo with GNU Lesser General Public License v3.0 | 6 votes |
@Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 不是登录请求,直接向下执行 if (!StrUtil.containsAnyIgnoreCase(request.getRequestURI(), applicationProperties.getAdminPath(SecurityConstants.AUTHENTICATE_URL))) { filterChain.doFilter(request, response); return; } String queryParam = request.getQueryString(); Map<String, String> paramMap = HttpUtil.decodeParamMap(queryParam, CharsetUtil.CHARSET_UTF_8); String password = request.getParameter(PASSWORD); if (StrUtil.isNotBlank(password)) { try { password = decryptAes(password, applicationProperties.getSecurity().getEncodeKey()); } catch (Exception e) { log.error("密码解密失败:{}", password); throw e; } paramMap.put(PASSWORD, password.trim()); } ParameterRequestWrapper requestWrapper = new ParameterRequestWrapper(request, paramMap); filterChain.doFilter(requestWrapper, response); }
Example #9
Source File: YxMiniPayService.java From yshopmall with Apache License 2.0 | 6 votes |
/** * 小程序支付 * * @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 #10
Source File: FileManageFactory.java From sk-admin with Apache License 2.0 | 6 votes |
/** * 使用配置的服务上传时location传入null 管理文件时需传入存储位置location * * @param location * @return */ public FileManage getFileManage(int location) { Setting setting = settingService.get(SettingConstant.OSS_USED); if (setting == null || StrUtil.isBlank(setting.getValue())) { throw new SkException("您还未配置OSS存储服务"); } String type = setting.getValue(); if ((type.equals(SettingConstant.QINIU_OSS)) || CommonConstant.OSS_QINIU == location) { return qiNiuFileManage; } else if ((type.equals(SettingConstant.ALI_OSS)) || CommonConstant.OSS_ALI == location) { return aliFileManage; } else if ((type.equals(SettingConstant.TENCENT_OSS)) || CommonConstant.OSS_TENCENT == location) { return tencentFileManage; } else if ((type.equals(SettingConstant.MINIO_OSS)) || CommonConstant.OSS_MINIO == location) { return minIOFileManage; } else if ((type.equals(SettingConstant.LOCAL_OSS)) || CommonConstant.OSS_LOCAL == location) { return localFileManage; } else { throw new SkException("暂不支持该存储配置,请检查配置"); } }
Example #11
Source File: BuildTriggerController.java From Jpom with MIT License | 6 votes |
@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 #12
Source File: TieBaLiveApi.java From tieba-api with MIT License | 6 votes |
/** * 公共请求方法 * @param url * @param bduss * @param stoken * @param params * @return */ public static JSONObject commonRequest(String url, String bduss, String stoken, String... params) { HttpRequest request = HttpRequest.post(url) .form("BDUSS", bduss) .form("stoken", stoken) .form("_client_version", "10.3.8.1") .form("_client_type", 2) .form("timestamp", System.currentTimeMillis()); for (String param : params) { request.form(StrUtil.subBefore(param, "=", false), StrUtil.subAfter(param, "=", false)); } request.form("tbs", getTbs(bduss)); Map<String, Object> formMap = request.form(); formMap = MapUtil.sort(formMap); StringBuilder sb = new StringBuilder(); for (String key : formMap.keySet()) { sb.append(String.format("%s=%s", key, formMap.get(key)).toString()); } sb.append("tiebaclient!!!"); String sign = SecureUtil.md5(sb.toString()).toUpperCase(); String body = request.form("sign", sign).execute().body(); if(StrUtil.isNotBlank(body)) { return JSON.parseObject(body); } return null; }
Example #13
Source File: JwtTokenUtil.java From mall-swarm with Apache License 2.0 | 6 votes |
/** * 当原来的token没过期时是可以刷新的 * * @param oldToken 带tokenHead的token */ public String refreshHeadToken(String oldToken) { if(StrUtil.isEmpty(oldToken)){ return null; } String token = oldToken.substring(tokenHead.length()); if(StrUtil.isEmpty(token)){ return null; } //token校验不通过 Claims claims = getClaimsFromToken(token); if(claims==null){ return null; } //如果token已经过期,不支持刷新 if(isTokenExpired(token)){ return null; } //如果token在30分钟之内刚刷新过,返回原token if(tokenRefreshJustBefore(token,30*60)){ return token; }else{ claims.put(CLAIM_KEY_CREATED, new Date()); return generateToken(claims); } }
Example #14
Source File: JobServiceImpl.java From LuckyFrameWeb with GNU Affero General Public License v3.0 | 6 votes |
/** * 新增任务 * * @param job 调度信息 调度信息 */ @Override public int insertJobCron(Job job) { if(StrUtil.isNotEmpty(job.getCreateBy())){ job.setCreateBy(job.getCreateBy()); job.setUpdateBy(job.getCreateBy()); }else{ job.setCreateBy(ShiroUtils.getLoginName()); job.setUpdateBy(ShiroUtils.getLoginName()); } job.setCreateTime(new Date()); job.setUpdateTime(new Date()); //job.setStatus(ScheduleConstants.Status.PAUSE.getValue()); int rows = jobMapper.insertJob(job); if (rows > 0) { ScheduleUtils.createScheduleJob(scheduler, job); } return rows; }
Example #15
Source File: RsaAuthApiController.java From littleca with Apache License 2.0 | 6 votes |
@PostMapping @ResponseBody public Result auth(@RequestBody EncodeRequestDTO authRequestEncode, HttpServletRequest request) throws Exception { String encodeData = authRequestEncode.getData(); if (StrUtil.isEmpty(encodeData)) { throw new AuthException("参数为空"); } AuthProperties.RsaAuthProperties rsaConfig = authProperties.getRsa(); String data = null; try { data = new String(rsa.decrypt(Base64.decodeBase64(encodeData), rsaConfig.getServerPrivateKey()), "UTF-8"); } catch (Exception e) { log.error("认证服务解密异常:[{}],加密数据:[{}],异常信息:{}", e, encodeData, e); throw new AuthException("认证服务解密异常"); } AuthRequestDTO authRequestDTO = JSONUtil.parseObject(data, AuthRequestDTO.class); AuthResultWrapper resultWrapper = apiAccountAuthHelper.auth(authRequestDTO, AuthType.RSA, request); return encodeResult(resultWrapper, rsaConfig); }
Example #16
Source File: MonitorService.java From spring-boot-demo with MIT License | 6 votes |
/** * 在线用户分页列表 * * @param pageCondition 分页参数 * @return 在线用户分页列表 */ public PageResult<OnlineUser> onlineUser(PageCondition pageCondition) { PageResult<String> keys = redisUtil.findKeysForPage(Consts.REDIS_JWT_KEY_PREFIX + Consts.SYMBOL_STAR, pageCondition.getCurrentPage(), pageCondition.getPageSize()); List<String> rows = keys.getRows(); Long total = keys.getTotal(); // 根据 redis 中键获取用户名列表 List<String> usernameList = rows.stream() .map(s -> StrUtil.subAfter(s, Consts.REDIS_JWT_KEY_PREFIX, true)) .collect(Collectors.toList()); // 根据用户名查询用户信息 List<User> userList = userDao.findByUsernameIn(usernameList); // 封装在线用户信息 List<OnlineUser> onlineUserList = Lists.newArrayList(); userList.forEach(user -> onlineUserList.add(OnlineUser.create(user))); return new PageResult<>(onlineUserList, total); }
Example #17
Source File: ProjectFileControl.java From Jpom with MIT License | 6 votes |
@RequestMapping(value = "download", method = RequestMethod.GET) public String download(String id, String filename, String levelName) { String safeFileName = pathSafe(filename); if (StrUtil.isEmpty(safeFileName)) { return JsonMessage.getString(405, "非法操作"); } try { ProjectInfoModel pim = projectInfoService.getItem(id); File file; if (StrUtil.isEmpty(levelName)) { file = FileUtil.file(pim.allLib(), filename); } else { file = FileUtil.file(pim.allLib(), levelName, filename); } if (file.isDirectory()) { return "暂不支持下载文件夹"; } ServletUtil.write(getResponse(), file); } catch (Exception e) { DefaultSystemLog.getLog().error("下载文件异常", e); } return "下载失败。请刷新页面后重试"; }
Example #18
Source File: UmsResourceServiceImpl.java From mall with Apache License 2.0 | 6 votes |
@Override public List<UmsResource> list(Long categoryId, String nameKeyword, String urlKeyword, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum,pageSize); UmsResourceExample example = new UmsResourceExample(); UmsResourceExample.Criteria criteria = example.createCriteria(); if(categoryId!=null){ criteria.andCategoryIdEqualTo(categoryId); } if(StrUtil.isNotEmpty(nameKeyword)){ criteria.andNameLike('%'+nameKeyword+'%'); } if(StrUtil.isNotEmpty(urlKeyword)){ criteria.andUrlLike('%'+urlKeyword+'%'); } return resourceMapper.selectByExample(example); }
Example #19
Source File: ImageCodeFilter.java From pre with GNU General Public License v3.0 | 6 votes |
/** * 验证流程 * * @param request */ private void validateCode(HttpServletRequest request) { String captcha = obtainImageCode(request); String t = obtainT(request); // 验证验证码 if (StrUtil.isBlank(captcha)) { throw new ValidateCodeException("验证码不能为空"); } // 从redis中获取之前保存的验证码跟前台传来的验证码进行匹配 Object kaptcha = redisTemplate.opsForValue().get(PreConstant.PRE_IMAGE_KEY + t); if (kaptcha == null) { throw new ValidateCodeException("验证码已失效"); } if (!captcha.toLowerCase().equals(kaptcha)) { throw new ValidateCodeException("验证码错误"); } }
Example #20
Source File: BaseDao.java From spring-boot-demo with MIT License | 6 votes |
/** * 通用插入,自增列需要添加 {@link Pk} 注解 * * @param t 对象 * @param ignoreNull 是否忽略 null 值 * @return 操作的行数 */ protected Integer insert(T t, Boolean ignoreNull) { String table = getTableName(t); List<Field> filterField = getField(t, ignoreNull); List<String> columnList = getColumns(filterField); String columns = StrUtil.join(Const.SEPARATOR_COMMA, columnList); // 构造占位符 String params = StrUtil.repeatAndJoin("?", columnList.size(), Const.SEPARATOR_COMMA); // 构造值 Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray(); String sql = StrUtil.format("INSERT INTO {table} ({columns}) VALUES ({params})", Dict.create().set("table", table).set("columns", columns).set("params", params)); log.debug("【执行SQL】SQL:{}", sql); log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values)); return jdbcTemplate.update(sql, values); }
Example #21
Source File: LinuxProjectCommander.java From Jpom with MIT License | 6 votes |
@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 #22
Source File: SshInstallAgentController.java From Jpom with MIT License | 6 votes |
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 #23
Source File: ConstantFactory.java From Guns with GNU Lesser General Public License v3.0 | 6 votes |
@Override public String getPositionIds(Long userId) { StringBuilder positionIds = new StringBuilder(); List<UserPos> userPosList = this.userPosService.list( new QueryWrapper<UserPos>().eq("user_id", userId)); if (userPosList != null && userPosList.size() > 0) { for (UserPos userPos : userPosList) { Position position = positionService.getById(userPos.getPosId()); if (position != null) { positionIds.append(",").append(position.getPositionId()); } } } return StrUtil.removePrefix(positionIds.toString(), ","); }
Example #24
Source File: SpelUtil.java From mall4j with GNU Affero General Public License v3.0 | 6 votes |
/** * 支持 #p0 参数索引的表达式解析 * @param rootObject 根对象,method 所在的对象 * @param spel 表达式 * @param method ,目标方法 * @param args 方法入参 * @return 解析后的字符串 */ public static String parse(Object rootObject,String spel, Method method, Object[] args) { if (StrUtil.isBlank(spel)) { return StrUtil.EMPTY; } //获取被拦截方法参数名列表(使用Spring支持类库) LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer(); String[] paraNameArr = u.getParameterNames(method); if (ArrayUtil.isEmpty(paraNameArr)) { return spel; } //使用SPEL进行key的解析 ExpressionParser parser = new SpelExpressionParser(); //SPEL上下文 StandardEvaluationContext context = new MethodBasedEvaluationContext(rootObject,method,args,u); //把方法参数放入SPEL上下文中 for (int i = 0; i < paraNameArr.length; i++) { context.setVariable(paraNameArr[i], args[i]); } return parser.parseExpression(spel).getValue(context, String.class); }
Example #25
Source File: IndexController.java From zuihou-admin-boot with Apache License 2.0 | 6 votes |
@RequestMapping(value = "login", method = RequestMethod.POST) @ResponseBody @PermessionLimit(limit = false) public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember) { // valid if (PermissionInterceptor.ifLogin(request)) { return ReturnT.SUCCESS; } // param if (StrUtil.isBlank(userName) || StrUtil.isBlank(password)) { return new ReturnT<String>(500, I18nUtil.getString("login_param_empty")); } boolean ifRem = (StrUtil.isNotBlank(ifRemember) && "on".equals(ifRemember)) ? true : false; // do login boolean loginRet = PermissionInterceptor.login(response, userName, password, ifRem); if (!loginRet) { return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid")); } return ReturnT.SUCCESS; }
Example #26
Source File: SnowFlakeId.java From magic-starter with GNU Lesser General Public License v3.0 | 6 votes |
/** * 构造 * * @param workerId 终端ID * @param dataCenterId 数据中心ID * @param isUseSystemClock 是否使用{@link SystemClock} 获取当前时间戳 * @param prefix 前缀 */ public SnowFlakeId(long workerId, long dataCenterId, boolean isUseSystemClock, Prefix prefix) { // 最大支持机器节点数0~31,一共32个 long maxWorkerId = ~(-1L << WORKER_ID_BITS); if (workerId > maxWorkerId || workerId < 0) { throw new IdException(StrUtil.format("worker Id can't be greater than {} or less than 0", maxWorkerId)); } // 最大支持数据中心节点数0~31,一共32个 long maxDataCenterId = ~(-1L << DATA_CENTER_ID_BITS); if (dataCenterId > maxDataCenterId || dataCenterId < 0) { throw new IdException(StrUtil.format("data center Id can't be greater than {} or less than 0", maxDataCenterId)); } this.workerId = workerId; this.dataCenterId = dataCenterId; this.useSystemClock = isUseSystemClock; this.prefix = prefix; }
Example #27
Source File: ZooLockAspect.java From spring-boot-demo with MIT License | 6 votes |
/** * 环绕操作 * * @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 #28
Source File: AdminServiceImpl.java From halo with GNU General Public License v3.0 | 6 votes |
@Override public AuthToken authCodeCheck(LoginParam loginParam) { // get user final User user = this.authenticate(loginParam); // check authCode if (MFAType.useMFA(user.getMfaType())) { if (StrUtil.isBlank(loginParam.getAuthcode())) { throw new BadRequestException("请输入两步验证码"); } TwoFactorAuthUtils.validateTFACode(user.getMfaKey(), loginParam.getAuthcode()); } if (SecurityContextHolder.getContext().isAuthenticated()) { // If the user has been logged in throw new BadRequestException("您已登录,请不要重复登录"); } // Log it then login successful eventPublisher.publishEvent(new LogEvent(this, user.getUsername(), LogType.LOGGED_IN, user.getNickname())); // Generate new token return buildAuthToken(user); }
Example #29
Source File: BuildService.java From Jpom with MIT License | 5 votes |
public boolean checkNode(String nodeId) { List<BuildModel> list = list(); if (list == null || list.isEmpty()) { return false; } for (BuildModel buildModel : list) { if (buildModel.getReleaseMethod() == BuildModel.ReleaseMethod.Project.getCode()) { String releaseMethodDataId = buildModel.getReleaseMethodDataId(); if (StrUtil.startWith(releaseMethodDataId, nodeId + ":")) { return true; } } } return false; }
Example #30
Source File: JobController.java From spring-boot-demo with MIT License | 5 votes |
/** * 删除定时任务 */ @DeleteMapping public ResponseEntity<ApiResponse> deleteJob(JobForm form) throws SchedulerException { if (StrUtil.hasBlank(form.getJobGroupName(), form.getJobClassName())) { return new ResponseEntity<>(ApiResponse.msg("参数不能为空"), HttpStatus.BAD_REQUEST); } jobService.deleteJob(form); return new ResponseEntity<>(ApiResponse.msg("删除成功"), HttpStatus.OK); }