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 File: OrgServiceImpl.java    From zuihou-admin-cloud with 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 #2
Source File: RoleService.java    From Guns with 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 #3
Source File: MonitorListController.java    From Jpom with 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 #4
Source File: TencentServiceImpl.java    From zfile with 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 #5
Source File: ConstantFactory.java    From Guns with 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 #6
Source File: LinuxSystemCommander.java    From Jpom with 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 #7
Source File: LinuxSystemCommander.java    From Jpom with 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 #8
Source File: InjectableConfiguration.java    From simple-robot-core with 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 #9
Source File: RestRoleService.java    From Guns with 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 #10
Source File: MethodUtil.java    From simple-robot-core with 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 #11
Source File: MockLogServiceImpl.java    From v-mock with 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 #12
Source File: OrgServiceImpl.java    From zuihou-admin-boot with 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 #13
Source File: StationServiceImpl.java    From zuihou-admin-boot with 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 #14
Source File: JvmUtil.java    From Jpom with 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 #15
Source File: HutoolController.java    From mall-learning with 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 #16
Source File: UserServiceImpl.java    From v-mock with 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 #17
Source File: StationServiceImpl.java    From zuihou-admin-cloud with 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 #18
Source File: SysUserServiceImpl.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 批量删除用户信息
 *
 * @param ids 需要删除的数据ID
 * @return 结果
 */
@Override
public int deleteUserByIds(String ids) {
    Long[] userIds = Convert.toLongArray(ids);
    for (Long userId : userIds) {
        if (SysUser.isAdmin(userId)) {
            throw new BusinessException("不允许删除超级管理员用户");
        }
    }
    return userMapper.deleteUserByIds(userIds);
}
 
Example #19
Source File: TimeUtils.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
public static LocalDateTime getPasswordErrorLockTime(String time) {
    if (time == null || "".equals(time)) {
        return LocalDateTime.MAX;
    }
    if ("0".equals(time)) {
        return LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
    }
    char unit = Character.toLowerCase(time.charAt(time.length() - 1));

    if (time.length() == 1) {
        unit = 'd';
    }
    Long lastTime = Convert.toLong(time.substring(0, time.length() - 1));

    LocalDateTime passwordErrorLastTime = LocalDateTime.MAX;
    switch (unit) {
        //时
        case 'h':
            passwordErrorLastTime = LocalDateTime.now().plusHours(lastTime);
            break;
        //天
        case 'd':
            passwordErrorLastTime = LocalDateTime.now().plusDays(lastTime);
            break;
        //周
        case 'w':
            passwordErrorLastTime = LocalDateTime.now().plusWeeks(lastTime);
            break;
        //月
        case 'm':
            passwordErrorLastTime = LocalDateTime.now().plusMonths(lastTime);
            break;
        default:
            passwordErrorLastTime = LocalDateTime.now().plusDays(lastTime);
            break;
    }

    return passwordErrorLastTime;
}
 
Example #20
Source File: TimeUtils.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
public static LocalDateTime getPasswordErrorLockTime(String time) {
    if (time == null || "".equals(time)) {
        return LocalDateTime.MAX;
    }
    if ("0".equals(time)) {
        return LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
    }
    char unit = Character.toLowerCase(time.charAt(time.length() - 1));

    if (time.length() == 1) {
        unit = 'd';
    }
    Long lastTime = Convert.toLong(time.substring(0, time.length() - 1));

    LocalDateTime passwordErrorLastTime = LocalDateTime.MAX;
    switch (unit) {
        //时
        case 'h':
            passwordErrorLastTime = LocalDateTime.now().plusHours(lastTime);
            break;
        //天
        case 'd':
            passwordErrorLastTime = LocalDateTime.now().plusDays(lastTime);
            break;
        //周
        case 'w':
            passwordErrorLastTime = LocalDateTime.now().plusWeeks(lastTime);
            break;
        //月
        case 'm':
            passwordErrorLastTime = LocalDateTime.now().plusMonths(lastTime);
            break;
        default:
            passwordErrorLastTime = LocalDateTime.now().plusDays(lastTime);
            break;
    }

    return passwordErrorLastTime;
}
 
Example #21
Source File: TestUtil.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void appendUrl(StringBuilder sb, Object value, String key, Charset charset) {
	String valueStr = Convert.toStr(value);
	sb.append(URLUtil.encodeAll(key, charset)).append("=");
	if (StrUtil.isNotEmpty(valueStr)) {
		sb.append(URLUtil.encodeAll(valueStr, charset));
	}
}
 
Example #22
Source File: NoBootTest.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void testSort() {
    List<com.github.zuihou.file.entity.File> list = new ArrayList<>();
    list.add(com.github.zuihou.file.entity.File.builder().id(3L).build());
    list.add(com.github.zuihou.file.entity.File.builder().id(1L).build());
    list.add(com.github.zuihou.file.entity.File.builder().id(2L).build());
    list.add(com.github.zuihou.file.entity.File.builder().id(5L).build());

    list.sort((f1, f2) -> Convert.toInt(f2.getId()) - Convert.toInt(f1.getId()));


    list.forEach(System.out::println);

}
 
Example #23
Source File: MenuServiceImpl.java    From zuihou-admin-cloud with 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 #24
Source File: UserServiceImpl.java    From zuihou-admin-boot with 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 #25
Source File: GenController.java    From RuoYi with Apache License 2.0 5 votes vote down vote up
/**
 * 批量生成代码
 */
@RequiresPermissions("tool:gen:code")
@Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/batchGenCode")
@ResponseBody
public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
    String[] tableNames = Convert.toStrArray(tables);
    byte[] data = genService.generatorCode(tableNames);
    this.genCode(response, data);
}
 
Example #26
Source File: TenantServiceImpl.java    From zuihou-admin-cloud with 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 #27
Source File: RoleServiceImpl.java    From zuihou-admin-boot with 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;
}
 
Example #28
Source File: AreaServiceImpl.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
private void delete(List<Long> ids) {
    // 查询子节点
    List<Long> childIds = super.listObjs(Wraps.<Area>lbQ().select(Area::getId).in(Area::getParentId, ids), Convert::toLong);
    if (!childIds.isEmpty()) {
        removeByIds(childIds);
        delete(childIds);
    }
    log.debug("退出地区数据递归");
}
 
Example #29
Source File: SmsTencentStrategy.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
@Override
protected SmsResult send(SmsDO smsDO) {
    try {
        //初始化单发
        SmsSingleSender singleSender = new SmsSingleSender(Convert.toInt(smsDO.getAppId(), 0), smsDO.getAppSecret());

        String paramStr = smsDO.getTemplateParams();

        JSONObject param = JSONObject.parseObject(paramStr, Feature.OrderedField);

        Set<Map.Entry<String, Object>> sets = param.entrySet();

        ArrayList<String> paramList = new ArrayList<>();
        for (Map.Entry<String, Object> val : sets) {
            paramList.add(val.getValue().toString());
        }

        SmsSingleSenderResult singleSenderResult = singleSender.sendWithParam("86", smsDO.getPhone(),
                Convert.toInt(smsDO.getTemplateCode()), paramList, smsDO.getSignName(), "", "");
        log.info("tencent result={}", singleSenderResult.toString());
        return SmsResult.build(ProviderType.TENCENT, String.valueOf(singleSenderResult.result),
                singleSenderResult.sid, singleSenderResult.ext,
                ERROR_CODE_MAP.getOrDefault(String.valueOf(singleSenderResult.result), singleSenderResult.errMsg), singleSenderResult.fee);
    } catch (Exception e) {
        log.error(e.getMessage());
        return SmsResult.fail(e.getMessage());
    }
}
 
Example #30
Source File: TestResource.java    From zuihou-admin-boot with 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");
}