Java Code Examples for cn.hutool.core.collection.CollUtil#isEmpty()

The following examples show how to use cn.hutool.core.collection.CollUtil#isEmpty() . 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: 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 2
Source File: DynamicAccessDecisionManager.java    From mall-swarm with Apache License 2.0 6 votes vote down vote up
@Override
public void decide(Authentication authentication, Object object,
                   Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
    // 当接口未被配置资源时直接放行
    if (CollUtil.isEmpty(configAttributes)) {
        return;
    }
    Iterator<ConfigAttribute> iterator = configAttributes.iterator();
    while (iterator.hasNext()) {
        ConfigAttribute configAttribute = iterator.next();
        //将访问所需资源或用户拥有资源进行比对
        String needAuthority = configAttribute.getAttribute();
        for (GrantedAuthority grantedAuthority : authentication.getAuthorities()) {
            if (needAuthority.trim().equals(grantedAuthority.getAuthority())) {
                return;
            }
        }
    }
    throw new AccessDeniedException("抱歉,您没有访问权限");
}
 
Example 3
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 4
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 5
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 6
Source File: SysUserServiceImpl.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public void saveUserAndUserRole(SysUser user) {
	user.setCreateTime(new Date());
	sysUserMapper.insert(user);
	if(CollUtil.isEmpty(user.getRoleIdList())){
		return ;
	}
	//保存用户与角色关系
	sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
}
 
Example 7
Source File: SysUserServiceImpl.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public void updateUserAndUserRole(SysUser user) {
	// 更新用户
	sysUserMapper.updateById(user);

	//先删除用户与角色关系
	sysUserRoleMapper.deleteByUserId(user.getUserId());

	if(CollUtil.isEmpty(user.getRoleIdList())){
		return ;
	}
	//保存用户与角色关系
	sysUserRoleMapper.insertUserAndUserRole(user.getUserId(), user.getRoleIdList());
}
 
Example 8
Source File: ProdPropServiceImpl.java    From mall4j with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public void saveProdPropAndValues(@Valid ProdProp prodProp) {
    ProdProp dbProdProp = prodPropMapper.getProdPropByPropNameAndShopId(prodProp.getPropName(), prodProp.getShopId(), prodProp.getRule());
    if (dbProdProp != null) {
        throw new YamiShopBindException("已有相同名称规格");
    }
    prodPropMapper.insert(prodProp);
    if (CollUtil.isEmpty(prodProp.getProdPropValues())) {
        return;
    }
    prodPropValueMapper.insertPropValues(prodProp.getPropId(), prodProp.getProdPropValues());

}
 
Example 9
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 10
Source File: DataMigrationUtils.java    From v-mock with MIT License 5 votes vote down vote up
/**
 * 数据迁移操作
 */
@SneakyThrows
public static void dataMigrationCheck() {
    // 检查是否需要数据迁移
    String isNeedDataMigration = System.getProperty("dm");
    // -Ddm参数传了【true, yes, y, t, ok, 1, on, 是, 对, 真】 都行
    if (!BooleanUtil.toBoolean(isNeedDataMigration)) {
        log.info("Without data migration. ");
        return;
    }
    // 获取历史版本的数据文件
    List<File> historyDataFileList = getHistoryDataFileList();
    // check empty
    if (CollUtil.isEmpty(historyDataFileList)) {
        log.info("No history database file found. Run application..");
        return;
    }
    // 选出旧版本的数据库文件
    File targetOldDbFile = getTargetFile(historyDataFileList);
    log.info("Find old version db file {}. start migration...", targetOldDbFile.getName());
    // 获取当前ClassLoader
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    // DB文件URL
    URL currentDbFileUrl = classLoader.getResource(DB_FILE_PATH);
    // 以 link org.sqlite.SQLiteConnection 源码中的命名方式迁移DB文件
    String dbFileName = String.format("sqlite-jdbc-tmp-%d.db", currentDbFileUrl.hashCode());
    String tempFolder = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
    File currentDbFile = new File(tempFolder, dbFileName);
    // 将旧数据库文件复制一份,并用当前数据库命名方式命名以完成数据迁移
    File currentDb = FileUtil.copy(targetOldDbFile, currentDbFile, true);
    log.info("Data file {} migration success", currentDb.getName());
}
 
Example 11
Source File: ProjectInfoModel.java    From Jpom with MIT License 5 votes vote down vote up
public JavaCopyItem findCopyItem(String copyId) {
    if (StrUtil.isEmpty(copyId)) {
        return null;
    }
    List<JavaCopyItem> javaCopyItemList = getJavaCopyItemList();
    if (CollUtil.isEmpty(javaCopyItemList)) {
        return null;
    }
    Optional<JavaCopyItem> first = javaCopyItemList.stream().filter(javaCopyItem -> StrUtil.equals(javaCopyItem.getId(), copyId)).findFirst();
    return first.orElse(null);
}
 
Example 12
Source File: SystemApiServiceImpl.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean batchSave(SystemApiScanSaveDTO data) {
    List<SystemApiSaveDTO> list = data.getSystemApiList();
    if (CollUtil.isEmpty(list)) {
        return false;
    }

    list.forEach((dto) -> {
        try {
            SystemApi systemApi = BeanPlusUtil.toBean(dto, SystemApi.class);
            SystemApi save = this.getApi(dto.getCode());
            if (save == null) {
                systemApi.setIsOpen(false);
                systemApi.setIsPersist(true);
                super.save(systemApi);
            } else {
                systemApi.setId(save.getId());
                super.updateById(systemApi);
            }
        } catch (Exception e) {
            log.warn("api初始化失败", e);
        }
    });

    return true;
}
 
Example 13
Source File: AbstractProjectCommander.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 获取进程占用的主要端口
 *
 * @param pid 进程id
 * @return 端口
 */
public String getMainPort(int pid) {
    String cachePort = PID_PORT.get(pid);
    if (cachePort != null) {
        return cachePort;
    }
    List<NetstatModel> list = listNetstat(pid, true);
    if (list == null) {
        return StrUtil.DASHED;
    }
    List<Integer> ports = new ArrayList<>();
    for (NetstatModel model : list) {
        String local = model.getLocal();
        String portStr = getPortFormLocalIp(local);
        if (portStr == null) {
            continue;
        }
        // 取最小的端口号
        int minPort = Convert.toInt(portStr, Integer.MAX_VALUE);
        if (minPort == Integer.MAX_VALUE) {
            continue;
        }
        ports.add(minPort);
    }
    if (CollUtil.isEmpty(ports)) {
        return StrUtil.DASHED;
    }
    String allPort = CollUtil.join(ports, ",");
    // 缓存
    PID_PORT.put(pid, allPort);
    return allPort;
}
 
Example 14
Source File: BuildService.java    From Jpom with MIT License 5 votes vote down vote up
/**
 * 构建所有分组
 */
public Set<String> listGroup() {
    List<BuildModel> list = list();
    Set<String> set = new HashSet<>();
    if (CollUtil.isEmpty(list)) {
        return set;
    }
    for (BuildModel buildModel : list) {
        String group = buildModel.getGroup();
        if (StrUtil.isNotEmpty(group)) {
            set.add(group);
        }
    }
    return set;
}
 
Example 15
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 16
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 17
Source File: SystemApiServiceImpl.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean batchSave(SystemApiScanSaveDTO data) {
    List<SystemApiSaveDTO> list = data.getSystemApiList();
    if (CollUtil.isEmpty(list)) {
        return false;
    }

    list.forEach((dto) -> {
        try {
            SystemApi systemApi = BeanPlusUtil.toBean(dto, SystemApi.class);
            SystemApi save = this.getApi(dto.getCode());
            if (save == null) {
                systemApi.setIsOpen(false);
                systemApi.setIsPersist(true);
                super.save(systemApi);
            } else {
                systemApi.setId(save.getId());
                super.updateById(systemApi);
            }
        } catch (Exception e) {
            log.warn("api初始化失败", e);
        }
    });

    return true;
}
 
Example 18
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 19
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 20
Source File: OmsPortalOrderServiceImpl.java    From mall with Apache License 2.0 4 votes vote down vote up
@Override
public CommonPage<OmsOrderDetail> list(Integer status, Integer pageNum, Integer pageSize) {
    if(status==-1){
        status = null;
    }
    UmsMember member = memberService.getCurrentMember();
    PageHelper.startPage(pageNum,pageSize);
    OmsOrderExample orderExample = new OmsOrderExample();
    OmsOrderExample.Criteria criteria = orderExample.createCriteria();
    criteria.andDeleteStatusEqualTo(0)
            .andMemberIdEqualTo(member.getId());
    if(status!=null){
        criteria.andStatusEqualTo(status);
    }
    orderExample.setOrderByClause("create_time desc");
    List<OmsOrder> orderList = orderMapper.selectByExample(orderExample);
    CommonPage<OmsOrder> orderPage = CommonPage.restPage(orderList);
    //设置分页信息
    CommonPage<OmsOrderDetail> resultPage = new CommonPage<>();
    resultPage.setPageNum(orderPage.getPageNum());
    resultPage.setPageSize(orderPage.getPageSize());
    resultPage.setTotal(orderPage.getTotal());
    resultPage.setTotalPage(orderPage.getTotalPage());
    if(CollUtil.isEmpty(orderList)){
        return resultPage;
    }
    //设置数据信息
    List<Long> orderIds = orderList.stream().map(OmsOrder::getId).collect(Collectors.toList());
    OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
    orderItemExample.createCriteria().andOrderIdIn(orderIds);
    List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);
    List<OmsOrderDetail> orderDetailList = new ArrayList<>();
    for (OmsOrder omsOrder : orderList) {
        OmsOrderDetail orderDetail = new OmsOrderDetail();
        BeanUtil.copyProperties(omsOrder,orderDetail);
        List<OmsOrderItem> relatedItemList = orderItemList.stream().filter(item -> item.getOrderId().equals(orderDetail.getId())).collect(Collectors.toList());
        orderDetail.setOrderItemList(relatedItemList);
        orderDetailList.add(orderDetail);
    }
    resultPage.setList(orderDetailList);
    return resultPage;
}