cn.hutool.core.collection.CollUtil Java Examples

The following examples show how to use cn.hutool.core.collection.CollUtil. 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: BaseDao.java    From spring-boot-demo with 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 #2
Source File: SysDeptServiceImpl.java    From smaker with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 删除部门
 *
 * @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 #3
Source File: TarocoRedisRepository.java    From Taroco with 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 #4
Source File: BaseDao.java    From spring-boot-demo with 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 #5
Source File: AuthRequestFactory.java    From justauth-spring-boot-starter with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 返回当前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 #6
Source File: VersionIsolationRule.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
/**
 * 优先根据版本号取实例
 */
@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 #7
Source File: UserInfoHeaderFilter.java    From Taroco with 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 #8
Source File: SysDeptRelationServiceImpl.java    From smaker with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 维护部门关系
 *
 * @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 #9
Source File: UmsAdminServiceImpl.java    From mall with 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 #10
Source File: EmailMessageSender.java    From magic-starter with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 处理简单邮件类型
 *
 * @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 #11
Source File: UmsAdminServiceImpl.java    From mall-swarm with 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 #12
Source File: ProjectListController.java    From Jpom with 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 #13
Source File: TarocoRedisRepository.java    From Taroco with 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 #14
Source File: HutoolController.java    From mall-learning with 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 #15
Source File: BaseDao.java    From spring-boot-demo with 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 #16
Source File: NodeIndexController.java    From Jpom with 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 #17
Source File: BuildListController.java    From Jpom with 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 #18
Source File: BaseDao.java    From spring-boot-demo with 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 #19
Source File: BaseDao.java    From spring-boot-demo with 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 #20
Source File: ProjectInfoModel.java    From Jpom with 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 #21
Source File: BaseDao.java    From spring-boot-demo with 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 #22
Source File: BaseDao.java    From spring-boot-demo with 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 #23
Source File: User.java    From Taroco with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    if (CollUtil.isEmpty(roles)) {
        return Collections.emptyList();
    }
    final List<GrantedAuthority> authorities = new ArrayList<>(AuthorityUtils.createAuthorityList(
            roles.stream().map(Role::getAuthority).collect(Collectors.joining())));
    roles.forEach(role -> {
        if (CollUtil.isNotEmpty(role.getOperations())) {
            authorities.addAll(AuthorityUtils.createAuthorityList(
                    role.getOperations().stream().map(Operation::getAuthority).collect(Collectors.joining())));
        }
    });
    return authorities;
}
 
Example #24
Source File: BaseDataService.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 删除json对象
 *
 * @param filename 文件
 * @param key      key
 */
protected void deleteJson(String filename, String key) {
    // 读取文件,如果存在记录,则抛出异常
    JSONObject allData = getJSONObject(filename);
    JSONObject data = allData.getJSONObject(key);
    // 判断是否存在数据
    if (CollUtil.isEmpty(data)) {
        throw new JpomRuntimeException("项目名称存不在!");
    } else {
        allData.remove(key);
        JsonFileUtil.saveJson(getDataFilePath(filename), allData);
    }
}
 
Example #25
Source File: SqlCityParserDecorator.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
private void buildCitySql(List<Area> cities, Long parentId) {
    if (CollUtil.isNotEmpty(cities)) {

        cities.forEach(item -> item.setParentId(parentId));

        areaService.saveBatch(cities);

        for (Area city : cities) {
            buildCitySql(city.getChildren(), city.getId());
        }
    }
}
 
Example #26
Source File: OauthClient.java    From Taroco with Apache License 2.0 5 votes vote down vote up
public OauthClient(final OauthClientVo vo) {
    this.setClientId(vo.getClientId());
    this.setAppName(vo.getAppName());
    this.setResourceIds(CollUtil.join(vo.getResourceIds(), StrUtil.COMMA));
    this.setClientSecret(vo.getClientSecret());
    this.setScope(CollUtil.join(vo.getScope(), StrUtil.COMMA));
    this.setAuthorizedGrantTypes(CollUtil.join(vo.getAuthorizedGrantTypes(), StrUtil.COMMA));
    this.setWebServerRedirectUri(vo.getWebServerRedirectUri());
    this.setAuthorities(CollUtil.join(vo.getAuthorities(), StrUtil.COMMA));
    this.setAutoapprove(String.valueOf(vo.getAutoapprove()));
}
 
Example #27
Source File: MonitorController.java    From spring-boot-demo with 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();
}
 
Example #28
Source File: SqlCityParserDecorator.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * *实体转sql数据
 *
 * @param provinces 省市县数据
 */
private void buildSql(List<Area> provinces) {
    if (CollUtil.isNotEmpty(provinces)) {

        areaService.saveBatch(provinces);

        for (Area province : provinces) {
            buildCitySql(province.getChildren(), province.getId());
        }
    }
}
 
Example #29
Source File: TokenizerSamples.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
public static void defaultTokenizer(){
    //自动根据用户引入的分词库的jar来自动选择使用的引擎
    TokenizerEngine engine = TokenizerUtil.createEngine();

    //解析文本
    String text = "这两个方法的区别在于返回值";
    Result result = engine.parse(text);
    //输出:这 两个 方法 的 区别 在于 返回 值
    String resultStr = CollUtil.join((Iterator<Word>)result, " ");
    System.out.println(resultStr);
}
 
Example #30
Source File: GlobalExceptionHandler.java    From spring-boot-demo with MIT License 5 votes vote down vote up
@ExceptionHandler(value = Exception.class)
@ResponseBody
public ApiResponse handlerException(Exception e) {
    if (e instanceof NoHandlerFoundException) {
        log.error("【全局异常拦截】NoHandlerFoundException: 请求方法 {}, 请求路径 {}", ((NoHandlerFoundException) e).getRequestURL(), ((NoHandlerFoundException) e).getHttpMethod());
        return ApiResponse.ofStatus(Status.REQUEST_NOT_FOUND);
    } else if (e instanceof HttpRequestMethodNotSupportedException) {
        log.error("【全局异常拦截】HttpRequestMethodNotSupportedException: 当前请求方式 {}, 支持请求方式 {}", ((HttpRequestMethodNotSupportedException) e).getMethod(), JSONUtil.toJsonStr(((HttpRequestMethodNotSupportedException) e).getSupportedHttpMethods()));
        return ApiResponse.ofStatus(Status.HTTP_BAD_METHOD);
    } else if (e instanceof MethodArgumentNotValidException) {
        log.error("【全局异常拦截】MethodArgumentNotValidException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), ((MethodArgumentNotValidException) e).getBindingResult()
                .getAllErrors()
                .get(0)
                .getDefaultMessage(), null);
    } else if (e instanceof ConstraintViolationException) {
        log.error("【全局异常拦截】ConstraintViolationException", e);
        return ApiResponse.of(Status.BAD_REQUEST.getCode(), CollUtil.getFirst(((ConstraintViolationException) e).getConstraintViolations())
                .getMessage(), null);
    } else if (e instanceof MethodArgumentTypeMismatchException) {
        log.error("【全局异常拦截】MethodArgumentTypeMismatchException: 参数名 {}, 异常信息 {}", ((MethodArgumentTypeMismatchException) e).getName(), ((MethodArgumentTypeMismatchException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_MATCH);
    } else if (e instanceof HttpMessageNotReadableException) {
        log.error("【全局异常拦截】HttpMessageNotReadableException: 错误信息 {}", ((HttpMessageNotReadableException) e).getMessage());
        return ApiResponse.ofStatus(Status.PARAM_NOT_NULL);
    } else if (e instanceof BadCredentialsException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USERNAME_PASSWORD_ERROR);
    } else if (e instanceof DisabledException) {
        log.error("【全局异常拦截】BadCredentialsException: 错误信息 {}", e.getMessage());
        return ApiResponse.ofStatus(Status.USER_DISABLED);
    } else if (e instanceof BaseException) {
        log.error("【全局异常拦截】DataManagerException: 状态码 {}, 异常信息 {}", ((BaseException) e).getCode(), e.getMessage());
        return ApiResponse.ofException((BaseException) e);
    }

    log.error("【全局异常拦截】: 异常信息 {} ", e.getMessage());
    return ApiResponse.ofStatus(Status.ERROR);
}