Java Code Examples for cn.hutool.core.collection.CollUtil

The following examples show how to use cn.hutool.core.collection.CollUtil. These examples are extracted from open source projects. 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
/**
 * 删除部门
 *
 * @param id 部门 ID
 * @return 成功、失败
 */
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean removeDeptById(Integer id) {
	//级联删除部门
	List<Integer> idList = sysDeptRelationService
		.list(Wrappers.<SysDeptRelation>query().lambda()
			.eq(SysDeptRelation::getAncestor, id))
		.stream()
		.map(SysDeptRelation::getDescendant)
		.collect(Collectors.toList());

	if (CollUtil.isNotEmpty(idList)) {
		this.removeByIds(idList);
	}

	//删除部门级联关系
	sysDeptRelationService.deleteAllDeptRealtion(id);
	return Boolean.TRUE;
}
 
Example 2
/**
 * 维护部门关系
 *
 * @param sysDept 部门
 */
@Override
@Transactional(rollbackFor = Exception.class)
public void insertDeptRelation(SysDept sysDept) {
	//增加部门关系表
	SysDeptRelation condition = new SysDeptRelation();
	condition.setDescendant(sysDept.getParentId());
	List<SysDeptRelation> relationList = sysDeptRelationMapper
		.selectList(Wrappers.<SysDeptRelation>query().lambda()
			.eq(SysDeptRelation::getDescendant, sysDept.getParentId()))
		.stream().map(relation -> {
			relation.setDescendant(sysDept.getDeptId());
			return relation;
		}).collect(Collectors.toList());
	if (CollUtil.isNotEmpty(relationList)) {
		this.saveBatch(relationList);
	}

	//自己也要维护到关系表中
	SysDeptRelation own = new SysDeptRelation();
	own.setDescendant(sysDept.getDeptId());
	own.setAncestor(sysDept.getDeptId());
	sysDeptRelationMapper.insert(own);
}
 
Example 3
/**
 * 返回当前Oauth列表
 *
 * @return Oauth列表
 */
@SuppressWarnings("unchecked")
public List<String> oauthList() {
    // 默认列表
    List<String> defaultList = properties.getType().keySet().stream().map(Enum::name).collect(Collectors.toList());
    // 扩展列表
    List<String> extendList = new ArrayList<>();
    ExtendProperties extend = properties.getExtend();
    if (null != extend) {
        Class enumClass = extend.getEnumClass();
        List<String> names = EnumUtil.getNames(enumClass);
        // 扩展列表
        extendList = extend.getConfig()
            .keySet()
            .stream()
            .filter(x -> names.contains(x.toUpperCase()))
            .map(String::toUpperCase)
            .collect(Collectors.toList());
    }

    // 合并
    return (List<String>) CollUtil.addAll(defaultList, extendList);
}
 
Example 4
/**
 * 处理简单邮件类型
 *
 * @param message 邮件内容
 * @return boolean
 */
private boolean processSimpleEmail(EmailMessage message) {
	// 注意邮件发送可能出现异常,注意catch
	try {
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
		simpleMailMessage.setFrom("\"" + message.getFrom() + "\" <" + username + ">");
		simpleMailMessage.setTo(ArrayUtil.toArray(message.getTos(), String.class));
		simpleMailMessage.setSubject(message.getSubject());
		simpleMailMessage.setText(message.getContent());

		// 设置抄送人列表
		if (CollUtil.isEmpty(message.getCcs())) {
			simpleMailMessage.setCc(ArrayUtil.toArray(message.getCcs(), String.class));
		}
		mailSender.send(simpleMailMessage);
		return true;
	} catch (Exception e) {
		log.error("简单邮件发送异常!", e);
		return false;
	}
}
 
Example 5
Source Project: spring-boot-demo   Source File: BaseDao.java    License: MIT License 6 votes vote down vote up
/**
 * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列}
 *
 * @param t          对象
 * @param ignoreNull 是否忽略空值
 * @return 字段列表
 */
private List<Field> getField(T t, Boolean ignoreNull) {
	// 获取所有字段,包含父类中的字段
	Field[] fields = ReflectUtil.getFields(t.getClass());

	// 过滤数据库中不存在的字段,以及自增列
	List<Field> filterField;
	Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class)));

	// 是否过滤字段值为null的字段
	if (ignoreNull) {
		filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList());
	} else {
		filterField = fieldStream.collect(Collectors.toList());
	}
	return filterField;
}
 
Example 6
Source Project: Jpom   Source File: ProjectListController.java    License: MIT License 6 votes vote down vote up
/**
 * 展示项目页面
 */
@RequestMapping(value = "project_copy_list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String projectCopyList(String id) {
    ProjectInfoModel projectInfoModel = projectInfoService.getItem(id);
    if (projectInfoModel == null) {
        return JsonMessage.getString(404, "没有对应项目");
    }
    List<ProjectInfoModel.JavaCopyItem> javaCopyItemList = projectInfoModel.getJavaCopyItemList();
    if (CollUtil.isEmpty(javaCopyItemList)) {
        return JsonMessage.getString(404, "对应项目没有副本集");
    }
    JSONArray array = new JSONArray();
    for (ProjectInfoModel.JavaCopyItem javaCopyItem : javaCopyItemList) {
        JSONObject object = javaCopyItem.toJson();
        object.put("status", javaCopyItem.tryGetStatus());
        array.add(object);
    }

    return JsonMessage.getString(200, "", array);
}
 
Example 7
Source Project: Jpom   Source File: ProjectInfoModel.java    License: MIT License 6 votes vote down vote up
public boolean removeCopyItem(String copyId) {
    if (StrUtil.isEmpty(copyId)) {
        return true;
    }
    if (CollUtil.isEmpty(javaCopyItemList)) {
        return true;
    }
    int size = javaCopyItemList.size();
    List<JavaCopyItem> collect = javaCopyItemList.stream().filter(javaCopyItem -> !StrUtil.equals(javaCopyItem.getId(), copyId)).collect(Collectors.toList());
    if (size - 1 == collect.size()) {
        this.javaCopyItemList = collect;
        return true;
    } else {
        return false;
    }
}
 
Example 8
Source Project: Jpom   Source File: BuildListController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "list_data.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@Feature(method = MethodFeature.LIST)
public String getMonitorList(String group) {
    List<BuildModelVo> list = buildService.list(BuildModelVo.class);
    if (StrUtil.isNotEmpty(group) && CollUtil.isNotEmpty(list)) {
        List<BuildModelVo> array = new ArrayList<>();
        for (BuildModelVo buildModelVo : list) {
            if (group.equals(buildModelVo.getGroup())) {
                array.add(buildModelVo);
            }
        }
        list = array;
    }
    return JsonMessage.getString(200, "", list);
}
 
Example 9
Source Project: Jpom   Source File: NodeIndexController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "list.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
@Feature(method = MethodFeature.LIST)
public String list(String group) {
    List<NodeModel> nodeModels = nodeService.list();
    //
    if (nodeModels != null && StrUtil.isNotEmpty(group)) {
        // 筛选
        List<NodeModel> filterList = nodeModels.stream().filter(nodeModel -> StrUtil.equals(group, nodeModel.getGroup())).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(filterList)) {
            // 如果传入的分组找到了节点,就返回  否则返回全部
            nodeModels = filterList;
        }
    }
    setAttribute("array", nodeModels);
    // 获取所有的ssh 名称
    JSONObject sshName = new JSONObject();
    List<SshModel> sshModels = sshService.list();
    if (sshModels != null) {
        sshModels.forEach(sshModel -> sshName.put(sshModel.getId(), sshModel.getName()));
    }
    setAttribute("sshName", sshName);
    // group
    HashSet<String> allGroup = nodeService.getAllGroup();
    setAttribute("groups", allGroup);
    return "node/list";
}
 
Example 10
Source Project: spring-boot-demo   Source File: BaseDao.java    License: MIT License 6 votes vote down vote up
/**
 * 获取列
 *
 * @param fieldList 字段列表
 * @return 列信息列表
 */
private List<String> getColumns(List<Field> fieldList) {
	// 构造列
	List<String> columnList = CollUtil.newArrayList();
	for (Field field : fieldList) {
		Column columnAnnotation = field.getAnnotation(Column.class);
		String columnName;
		if (ObjectUtil.isNotNull(columnAnnotation)) {
			columnName = columnAnnotation.name();
		} else {
			columnName = field.getName();
		}
		columnList.add(StrUtil.format("`{}`", columnName));
	}
	return columnList;
}
 
Example 11
Source Project: mall-learning   Source File: HutoolController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation("CollUtil使用:集合工具类")
@GetMapping("/collUtil")
public CommonResult collUtil() {
    //数组转换为列表
    String[] array = new String[]{"a", "b", "c", "d", "e"};
    List<String> list = CollUtil.newArrayList(array);
    //join:数组转字符串时添加连接符号
    String joinStr = CollUtil.join(list, ",");
    LOGGER.info("collUtil join:{}", joinStr);
    //将以连接符号分隔的字符串再转换为列表
    List<String> splitList = StrUtil.split(joinStr, ',');
    LOGGER.info("collUtil split:{}", splitList);
    //创建新的Map、Set、List
    HashMap<Object, Object> newMap = CollUtil.newHashMap();
    HashSet<Object> newHashSet = CollUtil.newHashSet();
    ArrayList<Object> newList = CollUtil.newArrayList();
    //判断列表是否为空
    CollUtil.isEmpty(list);
    CollUtil.isNotEmpty(list);
    return CommonResult.success(null, "操作成功");
}
 
Example 12
Source Project: spring-boot-demo   Source File: BaseDao.java    License: MIT License 6 votes vote down vote up
/**
 * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列}
 *
 * @param t          对象
 * @param ignoreNull 是否忽略空值
 * @return 字段列表
 */
private List<Field> getField(T t, Boolean ignoreNull) {
	// 获取所有字段,包含父类中的字段
	Field[] fields = ReflectUtil.getFields(t.getClass());

	// 过滤数据库中不存在的字段,以及自增列
	List<Field> filterField;
	Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class)));

	// 是否过滤字段值为null的字段
	if (ignoreNull) {
		filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList());
	} else {
		filterField = fieldStream.collect(Collectors.toList());
	}
	return filterField;
}
 
Example 13
Source Project: spring-boot-demo   Source File: BaseDao.java    License: MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example 14
Source Project: spring-boot-demo   Source File: BaseDao.java    License: MIT License 6 votes vote down vote up
/**
 * 获取列
 *
 * @param fieldList 字段列表
 * @return 列信息列表
 */
private List<String> getColumns(List<Field> fieldList) {
	// 构造列
	List<String> columnList = CollUtil.newArrayList();
	for (Field field : fieldList) {
		Column columnAnnotation = field.getAnnotation(Column.class);
		String columnName;
		if (ObjectUtil.isNotNull(columnAnnotation)) {
			columnName = columnAnnotation.name();
		} else {
			columnName = field.getName();
		}
		columnList.add(StrUtil.format("`{}`", columnName));
	}
	return columnList;
}
 
Example 15
Source Project: spring-boot-demo   Source File: BaseDao.java    License: MIT License 6 votes vote down vote up
/**
 * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列}
 *
 * @param t          对象
 * @param ignoreNull 是否忽略空值
 * @return 字段列表
 */
private List<Field> getField(T t, Boolean ignoreNull) {
	// 获取所有字段,包含父类中的字段
	Field[] fields = ReflectUtil.getFields(t.getClass());

	// 过滤数据库中不存在的字段,以及自增列
	List<Field> filterField;
	Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class)));

	// 是否过滤字段值为null的字段
	if (ignoreNull) {
		filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList());
	} else {
		filterField = fieldStream.collect(Collectors.toList());
	}
	return filterField;
}
 
Example 16
Source Project: mall-swarm   Source File: UmsAdminServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int updatePassword(UpdateAdminPasswordParam param) {
    if(StrUtil.isEmpty(param.getUsername())
            ||StrUtil.isEmpty(param.getOldPassword())
            ||StrUtil.isEmpty(param.getNewPassword())){
        return -1;
    }
    UmsAdminExample example = new UmsAdminExample();
    example.createCriteria().andUsernameEqualTo(param.getUsername());
    List<UmsAdmin> adminList = adminMapper.selectByExample(example);
    if(CollUtil.isEmpty(adminList)){
        return -2;
    }
    UmsAdmin umsAdmin = adminList.get(0);
    if(!passwordEncoder.matches(param.getOldPassword(),umsAdmin.getPassword())){
        return -3;
    }
    umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword()));
    adminMapper.updateByPrimaryKey(umsAdmin);
    return 1;
}
 
Example 17
Source Project: mall   Source File: UmsAdminServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int updatePassword(UpdateAdminPasswordParam param) {
    if(StrUtil.isEmpty(param.getUsername())
            ||StrUtil.isEmpty(param.getOldPassword())
            ||StrUtil.isEmpty(param.getNewPassword())){
        return -1;
    }
    UmsAdminExample example = new UmsAdminExample();
    example.createCriteria().andUsernameEqualTo(param.getUsername());
    List<UmsAdmin> adminList = adminMapper.selectByExample(example);
    if(CollUtil.isEmpty(adminList)){
        return -2;
    }
    UmsAdmin umsAdmin = adminList.get(0);
    if(!passwordEncoder.matches(param.getOldPassword(),umsAdmin.getPassword())){
        return -3;
    }
    umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword()));
    adminMapper.updateByPrimaryKey(umsAdmin);
    adminCacheService.delAdmin(umsAdmin.getId());
    return 1;
}
 
Example 18
Source Project: Taroco   Source File: TarocoRedisRepository.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据key获取对象
 *
 * @param keyPatten the key patten
 * @return the keys values
 */
public Map<String, String> getKeysValues(final String keyPatten) {
    log.debug("[redisTemplate redis]  getValues()  patten={} ", keyPatten);
    return redisTemplate.execute((RedisCallback<Map<String, String>>) connection -> {
        RedisSerializer<String> serializer = getRedisSerializer();
        Map<String, String> maps = new HashMap<>(16);
        Set<String> keys = redisTemplate.keys(keyPatten + "*");
        if (CollUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                byte[] bKeys = serializer.serialize(key);
                byte[] bValues = connection.get(bKeys);
                String value = serializer.deserialize(bValues);
                maps.put(key, value);
            }
        }
        return maps;
    });
}
 
Example 19
Source Project: Taroco   Source File: UserInfoHeaderFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Object run() {
    RequestContext ctx = RequestContext.getCurrentContext();
    HttpServletRequest request = ctx.getRequest();
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        RequestContext requestContext = RequestContext.getCurrentContext();
        requestContext.addZuulRequestHeader(SecurityConstants.USER_HEADER, authentication.getName());
        requestContext.addZuulRequestHeader(SecurityConstants.USER_ROLE_HEADER, CollUtil.join(authentication.getAuthorities(), ","));
        String tokenValue = extractToken(request);
        if (!StringUtils.isEmpty(tokenValue)) {
            OAuth2AccessToken accessToken = tokenStore.readAccessToken(tokenValue);
            if (accessToken != null && !CollectionUtils.isEmpty(accessToken.getAdditionalInformation())) {
                Map<String, Object> information = accessToken.getAdditionalInformation();
                requestContext.addZuulRequestHeader(SecurityConstants.HEADER_LABEL, information.get(SecurityConstants.HEADER_LABEL) + "");
                requestContext.addZuulRequestHeader(SecurityConstants.USER_PERMISSION_HEADER, information.get(SecurityConstants.USER_PERMISSION_HEADER) + "");
            }
        }
    }
    return null;
}
 
Example 20
Source Project: spring-boot-demo   Source File: BaseDao.java    License: MIT License 6 votes vote down vote up
/**
 * 根据对象查询
 *
 * @param t 查询条件
 * @return 对象列表
 */
public List<T> findByExample(T t) {
	String tableName = getTableName(t);
	List<Field> filterField = getField(t, true);
	List<String> columnList = getColumns(filterField);

	List<String> columns = columnList.stream().map(s -> " and " + s + " = ? ").collect(Collectors.toList());

	String where = StrUtil.join(" ", columns);
	// 构造值
	Object[] values = filterField.stream().map(field -> ReflectUtil.getFieldValue(t, field)).toArray();

	String sql = StrUtil.format("SELECT * FROM {table} where 1=1 {where}", Dict.create().set("table", tableName).set("where", StrUtil.isBlank(where) ? "" : where));
	log.debug("【执行SQL】SQL:{}", sql);
	log.debug("【执行SQL】参数:{}", JSONUtil.toJsonStr(values));
	List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql, values);
	List<T> ret = CollUtil.newArrayList();
	maps.forEach(map -> ret.add(BeanUtil.fillBeanWithMap(map, ReflectUtil.newInstance(clazz), true, false)));
	return ret;
}
 
Example 21
Source Project: Taroco   Source File: TarocoRedisRepository.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 根据key获取对象
 *
 * @param keyPatten the key patten
 * @return the keys values
 */
public Map<String, String> getKeysValues(final String keyPatten) {
    log.debug("[redisTemplate redis]  getValues()  patten={} ", keyPatten);
    return redisTemplate.execute((RedisCallback<Map<String, String>>) connection -> {
        RedisSerializer<String> serializer = getRedisSerializer();
        Map<String, String> maps = new HashMap<>(16);
        Set<String> keys = redisTemplate.keys(keyPatten + "*");
        if (CollUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                byte[] bKeys = serializer.serialize(key);
                byte[] bValues = connection.get(bKeys);
                String value = serializer.deserialize(bValues);
                maps.put(key, value);
            }
        }
        return maps;
    });
}
 
Example 22
/**
 * Handle an application event.
 *
 * @param event the event to respond to
 */
@Override
public void onApplicationEvent(AuthenticationSuccessEvent event) {
	Authentication authentication = (Authentication) event.getSource();
	if (CollUtil.isNotEmpty(authentication.getAuthorities())) {
		handle(authentication);
	}
}
 
Example 23
Source Project: spring-boot-demo   Source File: UserServiceTest.java    License: MIT License 5 votes vote down vote up
/**
 * 测试Mybatis-Plus 查询全部
 */
@Test
public void testQueryAll() {
    List<User> list = userService.list(new QueryWrapper<>());
    Assert.assertTrue(CollUtil.isNotEmpty(list));
    log.debug("【list】= {}", list);
}
 
Example 24
Source Project: spring-boot-demo   Source File: UserMapperTest.java    License: MIT License 5 votes vote down vote up
/**
 * 测试查询所有
 */
@Test
public void selectAllUser() {
    List<User> userList = userMapper.selectAllUser();
    Assert.assertTrue(CollUtil.isNotEmpty(userList));
    log.debug("【userList】= {}", userList);
}
 
Example 25
/**
 * 优先根据版本号取实例
 */
@Override
public Server choose(ILoadBalancer lb, Object key) {
    if (lb == null) {
        return null;
    }
    String version;
    if (key != null && !KEY_DEFAULT.equals(key)) {
        version = key.toString();
    } else {
        version = LbIsolationContextHolder.getVersion();
    }

    List<Server> targetList = null;
    List<Server> upList = lb.getReachableServers();
    if (StrUtil.isNotEmpty(version)) {
        //取指定版本号的实例
        targetList = upList.stream().filter(
                server -> version.equals(
                        ((NacosServer) server).getMetadata().get(CommonConstant.METADATA_VERSION)
                )
        ).collect(Collectors.toList());
    }

    if (CollUtil.isEmpty(targetList)) {
        //只取无版本号的实例
        targetList = upList.stream().filter(
                server -> {
                    String metadataVersion = ((NacosServer) server).getMetadata().get(CommonConstant.METADATA_VERSION);
                    return StrUtil.isEmpty(metadataVersion);
                }
        ).collect(Collectors.toList());
    }

    if (CollUtil.isNotEmpty(targetList)) {
        return getServer(targetList);
    }
    return super.choose(lb, key);
}
 
Example 26
Source Project: spring-boot-demo   Source File: UserMapperTest.java    License: MIT License 5 votes vote down vote up
/**
 * 测试通用Mapper - 查询全部
 */
@Test
public void testQueryAll() {
    List<User> users = userMapper.selectAll();
    Assert.assertTrue(CollUtil.isNotEmpty(users));
    log.debug("【users】= {}", users);
}
 
Example 27
Source Project: spring-microservice-exam   Source File: SubjectCategoryService.java    License: MIT License 5 votes vote down vote up
/**
 * 返回树形分类集合
 *
 * @return List
 * @author tangyi
 * @date 2018/12/04 22:03
 */
   public List<SubjectCategoryDto> menus() {
	SubjectCategory subjectCategory = new SubjectCategory();
	subjectCategory.setTenantCode(SysUtil.getTenantCode());
	// 查询所有分类
	List<SubjectCategory> subjectCategoryList = findList(subjectCategory);
	if (CollectionUtils.isNotEmpty(subjectCategoryList)) {
		// 转成dto
		List<SubjectCategoryDto> subjectCategorySetTreeList = subjectCategoryList.stream().map(SubjectCategoryDto::new).distinct().collect(
				Collectors.toList());
		// 排序、组装树形结构
		return TreeUtil.buildTree(CollUtil.sort(subjectCategorySetTreeList, Comparator.comparingInt(SubjectCategoryDto::getSort)), CommonConstant.ROOT);
	}
	return new ArrayList<>();
}
 
Example 28
Source Project: spring-microservice-exam   Source File: DeptService.java    License: MIT License 5 votes vote down vote up
/**
 * 查询树形部门集合
 *
 * @return List
 * @author tangyi
 * @date 2018/10/25 12:57
 */
public List<DeptDto> depts() {
	Dept dept = new Dept();
	dept.setApplicationCode(SysUtil.getSysCode());
	dept.setTenantCode(SysUtil.getTenantCode());
	// 查询部门集合
	Stream<Dept> deptStream = findList(dept).stream();
	if (Optional.ofNullable(deptStream).isPresent()) {
		List<DeptDto> deptTreeList = deptStream.map(DeptDto::new).collect(Collectors.toList());
		// 排序、构建树形结构
		return TreeUtil
				.buildTree(CollUtil.sort(deptTreeList, Comparator.comparingInt(DeptDto::getSort)), CommonConstant.ROOT);
	}
	return new ArrayList<>();
}
 
Example 29
/**
 * 解析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 30
Source Project: spring-boot-demo   Source File: MonitorController.java    License: MIT License 5 votes vote down vote up
/**
 * 批量踢出在线用户
 *
 * @param names 用户名列表
 */
@DeleteMapping("/online/user/kickout")
public ApiResponse kickoutOnlineUser(@RequestBody List<String> names) {
    if (CollUtil.isEmpty(names)) {
        throw new SecurityException(Status.PARAM_NOT_NULL);
    }
    if (names.contains(SecurityUtil.getCurrentUsername())){
        throw new SecurityException(Status.KICKOUT_SELF);
    }
    monitorService.kickout(names);
    return ApiResponse.ofSuccess();
}