cn.hutool.core.convert.Convert Java Examples

The following examples show how to use cn.hutool.core.convert.Convert. 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 Project: v-mock   Author: i-am-vt   File: UserServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 根据条件分页查询用户列表
 *
 * @param user 用户信息
 * @return 用户信息集合信息
 */
@Override
public List<User> selectUserList(User user) {
    Long beginTime = Convert.toLong(user.getParams().get("beginTime"));
    Long endTime = Convert.toLong(user.getParams().get("endTime"));
    return this.list(Wrappers.<User>lambdaQuery()
            // like login nameF
            .like(StrUtil.isNotBlank(user.getLoginName()), User::getLoginName, user.getLoginName())
            // equals status
            .eq(user.getStatus() != null, User::getStatus, user.getStatus())
            // like phone
            .like(StrUtil.isNotBlank(user.getPhonenumber()), User::getPhonenumber, user.getPhonenumber())
            // beginTime
            .ge(beginTime != null, User::getCreateTime, beginTime)
            // endTime 加入当日的时间戳
            .le(endTime != null, User::getCreateTime, endTime));
}
 
Example #2
Source Project: v-mock   Author: i-am-vt   File: MockLogServiceImpl.java    License: MIT License 6 votes vote down vote up
/**
 * 获取过滤数据的wrapper
 *
 * @param mockLog  参数实体
 * @param isExport 是否excel导出的过滤,excel导出查询全部字段。
 */
private LambdaQueryWrapper<MockLog> getFilterWrapper(MockLog mockLog, boolean isExport) {
    Long beginTime = Convert.toLong(mockLog.getParams().get("beginTime"));
    Long endTime = Convert.toLong(mockLog.getParams().get("endTime"));
    String from = Convert.toStr(mockLog.getParams().get("from"));
    LambdaQueryWrapper<MockLog> mockLogWrapper = Wrappers.<MockLog>lambdaQuery()
            // like ip
            .like(StrUtil.isNotBlank(mockLog.getRequestIp()), MockLog::getRequestIp, mockLog.getRequestIp())
            // like hit url
            .like(StrUtil.isNotBlank(mockLog.getHitUrl()) && !FROM_URL.equals(from), MockLog::getHitUrl, mockLog.getHitUrl())
            // equals hit url, in url log page
            .eq(StrUtil.isNotBlank(mockLog.getHitUrl()) && FROM_URL.equals(from), MockLog::getHitUrl, mockLog.getHitUrl())
            // equals method
            .eq(StrUtil.isNotBlank(mockLog.getRequestMethod()), MockLog::getRequestMethod, mockLog.getRequestMethod())
            // beginTime
            .ge(beginTime != null, MockLog::getCreateTime, beginTime)
            // endTime 加入当日的时间戳
            .le(endTime != null, MockLog::getCreateTime, endTime);
    // 非导出场景
    if (!isExport) {
        // 只查询需要字段,排除大json字段
        mockLogWrapper.select(MockLog::getLogId, MockLog::getHitUrl, MockLog::getRequestMethod, MockLog::getCreateTime, MockLog::getRequestIp);
    }
    return mockLogWrapper;
}
 
Example #3
Source Project: Jpom   Author: jiangzeyin   File: LinuxSystemCommander.java    License: MIT License 6 votes vote down vote up
/**
     * 获取占用cpu信息
     *
     * @param info cpu信息
     * @return cpu信息
     */
    private static String getLinuxCpu(String info) {
        if (StrUtil.isEmpty(info)) {
            return null;
        }
        int i = info.indexOf(":");
        String[] split = info.substring(i + 1).split(",");
//            1.3% us — 用户空间占用CPU的百分比。
//            1.0% sy — 内核空间占用CPU的百分比。
//            0.0% ni — 改变过优先级的进程占用CPU的百分比
//            97.3% id — 空闲CPU百分比
//            0.0% wa — IO等待占用CPU的百分比
//            0.3% hi — 硬中断(Hardware IRQ)占用CPU的百分比
//            0.0% si — 软中断(Software Interrupts)占用CPU的百分比
        for (String str : split) {
            str = str.trim();
            String value = str.substring(0, str.length() - 2).trim();
            String tag = str.substring(str.length() - 2);
            if ("id".equalsIgnoreCase(tag)) {
                value = value.replace("%", "");
                double val = Convert.toDouble(value, 0.0);
                return String.format("%.2f", 100.00 - val);
            }
        }
        return "0";
    }
 
Example #4
Source Project: Jpom   Author: jiangzeyin   File: LinuxSystemCommander.java    License: MIT License 6 votes vote down vote up
@Override
public String stopService(String serviceName) {
    if (StrUtil.startWith(serviceName, StrUtil.SLASH)) {
        String ps = getPs(serviceName);
        List<String> list = StrUtil.splitTrim(ps, StrUtil.LF);
        if (list == null || list.isEmpty()) {
            return "stop";
        }
        String s = list.get(0);
        list = StrUtil.splitTrim(s, StrUtil.SPACE);
        if (list == null || list.size() < 2) {
            return "stop";
        }
        File file = new File(SystemUtil.getUserInfo().getHomeDir());
        int pid = Convert.toInt(list.get(1), 0);
        if (pid <= 0) {
            return "error stop";
        }
        return kill(file, pid);
    }
    String format = StrUtil.format("service {} stop", serviceName);
    return CommandUtil.execSystemCommand(format);
}
 
Example #5
Source Project: Jpom   Author: jiangzeyin   File: MonitorListController.java    License: MIT License 6 votes vote down vote up
/**
 * 开启或关闭监控
 *
 * @param id     id
 * @param status 状态
 * @param type   类型
 * @return json
 */
@RequestMapping(value = "changeStatus", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OptLog(UserOperateLogV1.OptType.ChangeStatusMonitor)
@Feature(method = MethodFeature.EDIT)
public String changeStatus(@ValidatorConfig(@ValidatorItem(value = ValidatorRule.NOT_BLANK, msg = "id不能为空")) String id,
                           String status, String type) {
    MonitorModel monitorModel = monitorService.getItem(id);
    if (monitorModel == null) {
        return JsonMessage.getString(405, "不存在监控项啦");
    }
    boolean bStatus = Convert.toBool(status, false);
    if ("status".equalsIgnoreCase(type)) {
        monitorModel.setStatus(bStatus);
    } else if ("restart".equalsIgnoreCase(type)) {
        monitorModel.setAutoRestart(bStatus);
    } else {
        return JsonMessage.getString(405, "type不正确");
    }
    monitorService.updateItem(monitorModel);
    return JsonMessage.getString(200, "修改成功");
}
 
Example #6
Source Project: Jpom   Author: jiangzeyin   File: JvmUtil.java    License: MIT License 6 votes vote down vote up
/**
 * 获取jmx 服务对象,如果没有加载则加载对应插件
 *
 * @param virtualMachine virtualMachine
 * @return JMXServiceURL
 * @throws IOException                  IO
 * @throws AgentLoadException           插件加载
 * @throws AgentInitializationException 插件初始化
 */
private static JMXServiceURL getJMXServiceURL(VirtualMachine virtualMachine) throws IOException, AgentLoadException, AgentInitializationException, ClassNotFoundException {
    try {
        String address = virtualMachine.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
        if (address != null) {
            return new JMXServiceURL(address);
        }
        int pid = Convert.toInt(virtualMachine.id());
        address = importFrom(pid);
        if (address != null) {
            return new JMXServiceURL(address);
        }
        String agent = getManagementAgent();
        virtualMachine.loadAgent(agent);
        address = virtualMachine.getAgentProperties().getProperty("com.sun.management.jmxremote.localConnectorAddress");
        if (address != null) {
            return new JMXServiceURL(address);
        }
        return null;
    } catch (InternalError internalError) {
        DefaultSystemLog.getLog().error("jmx 异常", internalError);
        return null;
    }
}
 
Example #7
Source Project: mall-learning   Author: macrozheng   File: HutoolController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation("Convert使用:类型转换工具类")
@GetMapping(value = "/covert")
public CommonResult covert() {
    //转换为字符串
    int a = 1;
    String aStr = Convert.toStr(a);
    //转换为指定类型数组
    String[] b = {"1", "2", "3", "4"};
    Integer[] bArr = Convert.toIntArray(b);
    //转换为日期对象
    String dateStr = "2017-05-06";
    Date date = Convert.toDate(dateStr);
    //转换为列表
    String[] strArr = {"a", "b", "c", "d"};
    List<String> strList = Convert.toList(String.class, strArr);
    return CommonResult.success(null, "操作成功");
}
 
Example #8
Source Project: zuihou-admin-boot   Author: zuihou   File: StationServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private List<Station> getStations(Set<Serializable> ids) {
    if (ids.isEmpty()) {
        return Collections.emptyList();
    }
    List<Long> idList = ids.stream().mapToLong(Convert::toLong).boxed().collect(Collectors.toList());

    List<Station> list = null;
    if (idList.size() <= 1000) {
        list = idList.stream().map(this::getByIdCache).filter(Objects::nonNull).collect(Collectors.toList());
    } else {
        LbqWrapper<Station> query = Wraps.<Station>lbQ()
                .in(Station::getId, idList)
                .eq(Station::getStatus, true);
        list = super.list(query);

        if (!list.isEmpty()) {
            list.forEach(item -> {
                String itemKey = key(item.getId());
                cacheChannel.set(getRegion(), itemKey, item);
            });
        }
    }
    return list;
}
 
Example #9
Source Project: zuihou-admin-boot   Author: zuihou   File: OrgServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private List<Org> getOrgs(Set<Serializable> ids) {
    if (ids.isEmpty()) {
        return Collections.emptyList();
    }
    List<Long> idList = ids.stream().mapToLong(Convert::toLong).boxed().collect(Collectors.toList());

    List<Org> list = null;
    if (idList.size() <= 1000) {
        list = idList.stream().map(this::getByIdCache).filter(Objects::nonNull).collect(Collectors.toList());
    } else {
        LbqWrapper<Org> query = Wraps.<Org>lbQ()
                .in(Org::getId, idList)
                .eq(Org::getStatus, true);
        list = super.list(query);

        if (!list.isEmpty()) {
            list.forEach(item -> {
                String itemKey = key(item.getId());
                cacheChannel.set(getRegion(), itemKey, item);
            });
        }
    }
    return list;
}
 
Example #10
Source Project: Guns   Author: stylefeng   File: ConstantFactory.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
@Cacheable(value = Cache.CONSTANT, key = "'" + CacheKey.ROLES_NAME + "'+#roleIds")
public String getRoleName(String roleIds) {
    if (ToolUtil.isEmpty(roleIds)) {
        return "";
    }
    Long[] roles = Convert.toLongArray(roleIds);
    StringBuilder sb = new StringBuilder();
    for (Long role : roles) {
        Role roleObj = roleMapper.selectById(role);
        if (ToolUtil.isNotEmpty(roleObj) && ToolUtil.isNotEmpty(roleObj.getName())) {
            sb.append(roleObj.getName()).append(",");
        }
    }
    return StrUtil.removeSuffix(sb.toString(), ",");
}
 
Example #11
Source Project: Guns   Author: stylefeng   File: RoleService.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 设置某个角色的权限
 *
 * @param roleId 角色id
 * @param ids    权限的id
 * @date 2017年2月13日 下午8:26:53
 */
@Transactional(rollbackFor = Exception.class)
public void setAuthority(Long roleId, String ids) {

    // 删除该角色所有的权限
    this.roleMapper.deleteRolesById(roleId);

    // 添加新的权限
    for (Long id : Convert.toLongArray(ids.split(","))) {
        Relation relation = new Relation();
        relation.setRoleId(roleId);
        relation.setMenuId(id);
        this.relationMapper.insert(relation);
    }

    // 刷新当前用户的权限
    userService.refreshCurrentUser();
}
 
Example #12
Source Project: zfile   Author: zhaojun1998   File: TencentServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public void init(Integer driveId) {
    this.driveId = driveId;
    Map<String, StorageConfig> stringStorageConfigMap =
            storageConfigService.selectStorageConfigMapByDriveId(driveId);
    String secretId = stringStorageConfigMap.get(StorageConfigConstant.SECRET_ID_KEY).getValue();
    String secretKey = stringStorageConfigMap.get(StorageConfigConstant.SECRET_KEY).getValue();
    String endPoint = stringStorageConfigMap.get(StorageConfigConstant.ENDPOINT_KEY).getValue();
    bucketName = stringStorageConfigMap.get(StorageConfigConstant.BUCKET_NAME_KEY).getValue();
    domain = stringStorageConfigMap.get(StorageConfigConstant.DOMAIN_KEY).getValue();
    basePath = stringStorageConfigMap.get(StorageConfigConstant.BASE_PATH).getValue();
    isPrivate = Convert.toBool(stringStorageConfigMap.get(StorageConfigConstant.IS_PRIVATE).getValue(), true);

    if (Objects.isNull(secretId) || Objects.isNull(secretKey) || Objects.isNull(endPoint) || Objects.isNull(bucketName)) {
        log.debug("初始化存储策略 [{}] 失败: 参数不完整", getStorageTypeEnum().getDescription());
        isInitialized = false;
    } else {
        BasicAWSCredentials credentials = new BasicAWSCredentials(secretId, secretKey);
        s3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(endPoint, "cos")).build();

        testConnection();
        isInitialized = true;
    }
}
 
Example #13
Source Project: simple-robot-core   Author: ForteScarlet   File: InjectableConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public T inject(T config, Map<String, Object> data) {
    AtomicReference<T> configRe = new AtomicReference<>(config);
    // 遍历data
    data.forEach((key, value) -> {
        // 存在值
        if (value != null) {
            // 从值集合中获取
            Map.Entry<Class, BiFunction<Object, T, T>> entry = injectFunctionMap.get(key);
            if(entry != null){
                // 如果存在这个entry,获取值并注入
                Object convertValue = Convert.convert(entry.getKey(), value);
                // 执行注入并为config重新赋值
                // 虽然本质上应该是不会变化config对象的
                configRe.set(entry.getValue().apply(convertValue, config));
            }
        }
    });
    return configRe.get();
}
 
Example #14
Source Project: Guns   Author: stylefeng   File: RestRoleService.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 设置某个角色的权限
 *
 * @param roleId 角色id
 * @param ids    权限的id
 * @date 2017年2月13日 下午8:26:53
 */
@Transactional(rollbackFor = Exception.class)
public void setAuthority(Long roleId, String ids) {

    // 删除该角色所有的权限
    this.restRoleMapper.deleteRolesById(roleId);

    // 添加新的权限
    for (Long id : Convert.toLongArray(ids.split(","))) {
        RestRelation relation = new RestRelation();
        relation.setRoleId(roleId);
        relation.setMenuId(id);
        this.restRelationMapper.insert(relation);
    }

    // 刷新当前用户的权限
    restUserService.refreshCurrentUser();
}
 
Example #15
Source Project: simple-robot-core   Author: ForteScarlet   File: MethodUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * 执行一个方法,可以为基本的数据类型进行转化
     *
     * @param obj
     * @param args
     * @param method
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public static Object invoke(Object obj, Object[] args, Method method) throws InvocationTargetException, IllegalAccessException {

        //获取参数的数据类型数组,准备转化数据类型
        Parameter[] parameters = method.getParameters();
        //如果传入参数与方法参数数量不符 ,抛出异常
        //不知道是否能识别 String... args 这种参数
        if (args.length != parameters.length) {
            throw new RuntimeException("参数长度不匹配");
        }
        //创建一个新的Object数组保存转化后的参数,如果使用原数组的话会抛异常:ArrayStoreException
        Object[] newArr = new Object[args.length];
        //遍历参数并转化
        for (int i = 0; i < parameters.length; i++) {
            //使用BeanUtils的数据类型器对参数的数据类型进行转化
            //保存至新的参数集
//            newArr[i] = ConvertUtils.convert(args[i], parameters[i].getType());
            newArr[i] = Convert.convert(parameters[i].getType(), args[i]);
        }

        //返回方法的执行结果
        return method.invoke(obj, newArr);
    }
 
Example #16
Source Project: zuihou-admin-cloud   Author: zuihou   File: StationServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private List<Station> getStations(Set<Serializable> ids) {
    if (ids.isEmpty()) {
        return Collections.emptyList();
    }
    List<Long> idList = ids.stream().mapToLong(Convert::toLong).boxed().collect(Collectors.toList());

    List<Station> list = null;
    if (idList.size() <= 1000) {
        list = idList.stream().map(this::getByIdCache).filter(Objects::nonNull).collect(Collectors.toList());
    } else {
        LbqWrapper<Station> query = Wraps.<Station>lbQ()
                .in(Station::getId, idList)
                .eq(Station::getStatus, true);
        list = super.list(query);

        if (!list.isEmpty()) {
            list.forEach(item -> {
                String itemKey = key(item.getId());
                cacheChannel.set(getRegion(), itemKey, item);
            });
        }
    }
    return list;
}
 
Example #17
Source Project: zuihou-admin-cloud   Author: zuihou   File: OrgServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private List<Org> getOrgs(Set<Serializable> ids) {
    if (ids.isEmpty()) {
        return Collections.emptyList();
    }
    List<Long> idList = ids.stream().mapToLong(Convert::toLong).boxed().collect(Collectors.toList());

    List<Org> list = null;
    if (idList.size() <= 1000) {
        list = idList.stream().map(this::getByIdCache).filter(Objects::nonNull).collect(Collectors.toList());
    } else {
        LbqWrapper<Org> query = Wraps.<Org>lbQ()
                .in(Org::getId, idList)
                .eq(Org::getStatus, true);
        list = super.list(query);

        if (!list.isEmpty()) {
            list.forEach(item -> {
                String itemKey = key(item.getId());
                cacheChannel.set(getRegion(), itemKey, item);
            });
        }
    }
    return list;
}
 
Example #18
Source Project: zuihou-admin-cloud   Author: zuihou   File: TenantServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean delete(List<Long> ids) {
    List<String> tenantCodeList = listObjs(Wraps.<Tenant>lbQ().select(Tenant::getCode).in(Tenant::getId, ids), Convert::toStr);
    if (tenantCodeList.isEmpty()) {
        return true;
    }
    removeByIds(ids);

    return initSystemContext.delete(tenantCodeList);
}
 
Example #19
Source Project: microservices-platform   Author: zlt2000   File: SysMenuController.java    License: Apache License 2.0 5 votes vote down vote up
@ApiOperation(value = "根据roleCodes获取对应的权限")
@SuppressWarnings("unchecked")
@Cacheable(value = "menu", key ="#roleCodes")
@GetMapping("/{roleCodes}")
public List<SysMenu> findMenuByRoles(@PathVariable String roleCodes) {
    List<SysMenu> result = null;
    if (StringUtils.isNotEmpty(roleCodes)) {
        Set<String> roleSet = (Set<String>)Convert.toCollection(HashSet.class, String.class, roleCodes);
        result = menuService.findByRoleCodes(roleSet, CommonConstant.PERMISSION);
    }
    return result;
}
 
Example #20
Source Project: Guns   Author: stylefeng   File: ConstantFactory.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public String getMenuNames(String menuIds) {
    Long[] menus = Convert.toLongArray(menuIds);
    StringBuilder sb = new StringBuilder();
    for (Long menu : menus) {
        Menu menuObj = menuMapper.selectById(menu);
        if (ToolUtil.isNotEmpty(menuObj) && ToolUtil.isNotEmpty(menuObj.getName())) {
            sb.append(menuObj.getName()).append(",");
        }
    }
    return StrUtil.removeSuffix(sb.toString(), ",");
}
 
Example #21
Source Project: magic-starter   Author: xkcoding   File: SecureUtil.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 解析token,获得用户信息
 *
 * @param token token
 * @return 用户信息
 */
@SuppressWarnings("unchecked")
private SecureUser getUserFromToken(String token) {
	Claims claims = jwtUtil.getClaimsFromToken(token);
	Object userId = claims.get(JwtUtil.USER_ID);
	Object username = claims.get(JwtUtil.USERNAME);
	Object permissions = claims.get(JwtUtil.PERMISSIONS);

	return SecureUser.builder().id(Convert.toLong(userId)).username((String) username).permissions(CollUtil.newHashSet((List<String>) permissions)).build();
}
 
Example #22
Source Project: Jpom   Author: jiangzeyin   File: SystemConfigController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(value = "save_config.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String saveConfig(String content, String restart) {
    if (StrUtil.isEmpty(content)) {
        return JsonMessage.getString(405, "内容不能为空");
    }
    try {
        YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
        ByteArrayResource resource = new ByteArrayResource(content.getBytes());
        yamlPropertySourceLoader.load("test", resource);
    } catch (Exception e) {
        DefaultSystemLog.getLog().warn("内容格式错误,请检查修正", e);
        return JsonMessage.getString(500, "内容格式错误,请检查修正:" + e.getMessage());
    }
    if (JpomManifest.getInstance().isDebug()) {
        return JsonMessage.getString(405, "调试模式不支持在线修改,请到resource目录下");
    }
    File resourceFile = ExtConfigBean.getResourceFile();
    FileUtil.writeString(content, resourceFile, CharsetUtil.CHARSET_UTF_8);

    if (Convert.toBool(restart, false)) {
        // 重启
        ThreadUtil.execute(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ignored) {
            }
            JpomApplication.restart();
        });
    }
    return JsonMessage.getString(200, "修改成功");
}
 
Example #23
Source Project: Jpom   Author: jiangzeyin   File: AbstractProjectCommander.java    License: MIT License 5 votes vote down vote up
/**
 * 转换pid
 *
 * @param result 查询信息
 * @return int
 */
public static int parsePid(String result) {
    if (result.startsWith(AbstractProjectCommander.RUNNING_TAG)) {
        return Convert.toInt(result.split(":")[1]);
    }
    return 0;
}
 
Example #24
Source Project: zuihou-admin-cloud   Author: zuihou   File: TestResource.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testObjlist() {
    for (int i = 0; i < 20; i++) {
        List<Long> list = orgService.listObjs(Convert::toLong);
        log.info("listsize={}", list.size());
    }
    log.info("endendendendend");
}
 
Example #25
Source Project: RuoYi   Author: lerry903   File: SysRoleServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 批量选择授权用户角色
 *
 * @param roleId  角色ID
 * @param userIds 需要删除的用户数据ID
 * @return 结果
 */
@Override
public int insertAuthUsers(Long roleId, String userIds) {
    Long[] users = Convert.toLongArray(userIds);
    // 新增用户与角色管理
    List<SysUserRole> list = new ArrayList<>();
    for (Long userId : users) {
        SysUserRole ur = new SysUserRole();
        ur.setUserId(userId);
        ur.setRoleId(roleId);
        list.add(ur);
    }
    return userRoleMapper.batchUserRole(list);
}
 
Example #26
Source Project: Jpom   Author: jiangzeyin   File: DbConfig.java    License: MIT License 5 votes vote down vote up
/**
 * 自动清理数据接口
 *
 * @param tableName 表名
 * @param timeClo   时间字段
 * @param maxCount  最大数量
 * @param consumer  查询出超过范围的时间回调
 */
public static void autoClear(String tableName, String timeClo, int maxCount, Consumer<Entity> whereCon, Consumer<Long> consumer) {
    if (maxCount <= 0) {
        return;
    }
    ThreadUtil.execute(() -> {
        Entity entity = Entity.create(tableName);
        if (whereCon != null) {
            // 条件
            whereCon.accept(entity);
        }
        Page page = new Page(maxCount, 1);
        page.addOrder(new Order(timeClo, Direction.DESC));
        PageResult<Entity> pageResult;
        try {
            pageResult = Db.use().setWrapper((Character) null).page(entity, page);
            if (pageResult.isEmpty()) {
                return;
            }
            Entity entity1 = pageResult.get(0);
            long time = Convert.toLong(entity1.get(timeClo.toUpperCase()), 0L);
            if (time <= 0) {
                return;
            }
            consumer.accept(time);
        } catch (SQLException e) {
            DefaultSystemLog.getLog().error("数据库查询异常", e);
        }
    });
}
 
Example #27
Source Project: WebStack-Guns   Author: jsnjfz   File: ConstantFactory.java    License: MIT License 5 votes vote down vote up
/**
 * 获取菜单的名称们(多个)
 */
@Override
public String getMenuNames(String menuIds) {
    Integer[] menus = Convert.toIntArray(menuIds);
    StringBuilder sb = new StringBuilder();
    for (int menu : menus) {
        Menu menuObj = menuMapper.selectById(menu);
        if (ToolUtil.isNotEmpty(menuObj) && ToolUtil.isNotEmpty(menuObj.getName())) {
            sb.append(menuObj.getName()).append(",");
        }
    }
    return StrUtil.removeSuffix(sb.toString(), ",");
}
 
Example #28
Source Project: zuihou-admin-boot   Author: zuihou   File: MenuServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public boolean saveWithCache(Menu menu) {
    menu.setIsEnable(Convert.toBool(menu.getIsEnable(), true));
    menu.setIsPublic(Convert.toBool(menu.getIsPublic(), false));
    menu.setParentId(Convert.toLong(menu.getParentId(), DEF_PARENT_ID));
    save(menu);

    if (menu.getIsPublic()) {
        cacheChannel.evict(CacheKey.USER_MENU);
    }
    return true;
}
 
Example #29
Source Project: zuihou-admin-boot   Author: zuihou   File: UserServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private List<User> findUser(Set<Serializable> ids) {
    if (ids.isEmpty()) {
        return Collections.emptyList();
    }
    List<Long> idList = ids.stream().mapToLong(Convert::toLong).boxed().collect(Collectors.toList());


    List<User> list = null;
    if (idList.size() > 100) {
        LbqWrapper<User> query = Wraps.<User>lbQ()
                .in(User::getId, idList)
                .eq(User::getStatus, true);
        list = super.list(query);

        if (!list.isEmpty()) {
            list.forEach(user -> {
                String menuKey = key(user.getId());
                cacheChannel.set(getRegion(), menuKey, user);
            });
        }

    } else {
        list = idList.stream().map(this::getByIdCache)
                .filter(Objects::nonNull).collect(Collectors.toList());
    }
    return list;
}
 
Example #30
Source Project: zuihou-admin-boot   Author: zuihou   File: RoleServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 删除角色时,需要级联删除跟角色相关的一切资源:
 * 1,角色本身
 * 2,角色-组织:
 * 3,角色-权限(菜单和按钮):
 * 4,角色-用户:角色拥有的用户
 * 5,用户-权限:
 *
 * @param ids
 * @return
 */
@Override
@Transactional(rollbackFor = Exception.class)
public boolean removeByIdWithCache(List<Long> ids) {
    if (ids.isEmpty()) {
        return true;
    }
    // 橘色
    boolean removeFlag = removeByIds(ids);
    // 角色组织
    roleOrgService.remove(Wraps.<RoleOrg>lbQ().in(RoleOrg::getRoleId, ids));
    // 角色权限
    roleAuthorityService.remove(Wraps.<RoleAuthority>lbQ().in(RoleAuthority::getRoleId, ids));

    List<Long> userIds = userRoleService.listObjs(
            Wraps.<UserRole>lbQ().select(UserRole::getUserId).in(UserRole::getRoleId, ids),
            Convert::toLong);

    //角色拥有的用户
    userRoleService.remove(Wraps.<UserRole>lbQ().in(UserRole::getRoleId, ids));

    ids.forEach((id) -> {
        cacheChannel.evict(CacheKey.ROLE_MENU, String.valueOf(id));
        cacheChannel.evict(CacheKey.ROLE_RESOURCE, String.valueOf(id));
    });

    if (!userIds.isEmpty()) {
        //用户角色 、 用户菜单、用户资源
        String[] userIdArray = userIds.stream().map(this::key).toArray(String[]::new);
        cacheChannel.evict(CacheKey.USER_ROLE, userIdArray);
        cacheChannel.evict(CacheKey.USER_RESOURCE, userIdArray);
        cacheChannel.evict(CacheKey.USER_MENU, userIdArray);
    }
    return removeFlag;
}