CommonUtil.java-一些工具类

多线程 工具区

	/**
     * 等待所有的任务执行完成,不会产生异常信息
     *
     * @param completableFuture 线程同步list
     * @return true 所有线程完成同步
     */
    @SafeVarargs
    @SneakyThrows
    public static <T> boolean waitingAllTaskEnd(CompletableFuture<T>... completableFuture) {
        boolean waitingAllTask = true;
        if (!ObjectUtils.isEmpty(completableFuture)) {
            List<CompletableFuture<T>> completableFutureList = new ArrayList<>(Arrays.asList(completableFuture));
            while (waitingAllTask) {
                Iterator<CompletableFuture<T>> completableFutureIterator = completableFutureList.iterator();
                while (completableFutureIterator.hasNext()) {
                    //只要有一个没有完成,那么结束循环,等待
                    if (!completableFutureIterator.next().isDone()) {
                        waitingAllTask = true;
                        break;
                    } else {
                        completableFutureIterator.remove();
                        waitingAllTask = false;
                    }
                }
                Thread.sleep(1000);
            }
        }
        return !waitingAllTask;
    }

    /**
     * 获取可以使用的线程并发数
     *
     * @return  线程并发数
     */
    public static int getHaveThreadCount(){
        //获取处理器的数目
        int cpuCount = Runtime.getRuntime().availableProcessors();
        //线程并发数
        return cpuCount > 4 ? 3 : 2;
    }

    /**
     * 执行异步操作判断是否等待其中一个线程执行完成,在恢复程序
     *
     * @param dealPersonFutureList 异步执行集合
     */
    @SneakyThrows
    public static void flagCompletableFutureIsSleep(List<CompletableFuture<Void>> dealPersonFutureList) {
        //线程并发数
        int threadCount = getHaveThreadCount();
        //线程结束返回值
        boolean isDone = true;
        //等待1秒
        int waitTime = 1000;
        if (dealPersonFutureList.size() >= threadCount) {
            while (isDone) {
                Iterator<CompletableFuture<Void>> iterator = dealPersonFutureList.iterator();
                while (iterator.hasNext()) {
                    //只要有一个完成了,那么结束循环
                    if (iterator.next().isDone()) {
                        isDone = false;
                        iterator.remove();
                        break;
                    }
                    Thread.sleep(waitTime);
                }
            }
        }
    }

数据库 反射区

	/**
     * 根据类名,方法名,参数获取注解(@Query)中的sql语句的对应vo字段
     *
     * @param daoClass       dao实体类
     * @param daoMethod      dao方法名
     * @param parameterTypes dao方法参数
     * @return 需要赋值的字段列表
     */
    private static List<String> getFiledNameList(Class<?> daoClass, String daoMethod, Class<?>... parameterTypes) {
        //字段名称集合
        List<String> filedNameList = new ArrayList<>();
        try {
            Method method = daoClass.getDeclaredMethod(daoMethod, parameterTypes);
            if (org.apache.commons.lang3.ObjectUtils.allNotNull(method)) {
                //获取查询注解
                Query query = method.getDeclaredAnnotation(Query.class);
                if (!ObjectUtils.isEmpty(query)) {
                    //sql语句
                    String sql = query.value();
                    if (org.apache.commons.lang3.StringUtils.isNotEmpty(sql)) {
                        String sqlTemp = sql;
                        sql = sql.trim().toLowerCase();
                        int selectIndex = !sql.contains("select") ? sql.indexOf("SELECT") : sql.indexOf("select");
                        int fromIndex = !sql.contains("from") ? sql.indexOf("FROM") : sql.indexOf("from");
                        //字段字符串
                        sql = sqlTemp;
                        String filedStr = sql.substring(selectIndex + 6, fromIndex);
                        String[] filedStrArr = filedStr.split(",");
                        for (String s : filedStrArr) {
                            String filedName = "";
                            String filedStrTemp = s.trim();
                            int asIndex = filedStrTemp.contains("as") ? filedStrTemp.indexOf("as") : filedStrTemp.contains("AS") ? filedStrTemp.indexOf("AS") : -1;
                            if (asIndex != -1) {
                                filedName = filedStrTemp.substring(asIndex + 2);
                            } else {
                                String[] filedStrArrTemp = filedStrTemp.split("\\.");
                                //如果有表名前缀 如  a.name
                                if (filedStrArrTemp.length > 1) {
                                    filedName = filedStrArrTemp[1].trim();
                                    //如  a.name  perName
                                    filedStrArrTemp = filedName.split("\\s+");
                                    if (filedStrArrTemp.length > 1) {
                                        filedName = filedStrArrTemp[1].trim();
                                    }
                                } else {
                                    filedName = filedStrTemp;
                                }
                            }
                            filedName = filedName.trim();
                            if (StringUtils.isNotBlank(filedName)) {
                                filedNameList.add(filedName);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filedNameList;
    }

    /**
     * 根据原始数据,封装为指定的vo列表
     *
     * @param listDataObj    原始数据
     * @param target         希望转换的类
     * @param daoClass       dao类
     * @param daoMethod      dao的方法
     * @param parameterTypes dao方法参数
     * @param <T>            需要转换的类
     * @return 对应转换类的集合
     */
    public static <T> List<T> objArrToListVo(List<?> listDataObj, Class<T> target, Class<?> daoClass, String daoMethod, Class<?>... parameterTypes) {
        List<T> listData = new ArrayList<>();
        try {
            //字段名称集合
            List<String> filedNameList = getFiledNameList(daoClass, daoMethod, parameterTypes);
            listDataObj.forEach(row -> {
                listData.add(objToVo((Object[]) row, filedNameList, target));
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        return listData;
    }

    /**
     * 把原始数组列表转换为vo类
     *
     * @param data          原始数据数组
     * @param filedNameList 需要转换的字段列表,一次排序的
     * @param target        转换的类类型
     * @param <T>           转换的类类型
     * @return 封装好的vo类
     */
    public static <T> T objToVo(Object[] data, List<String> filedNameList, Class<T> target) {
        T o = null;
        try {
            o = target.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int valueIndex = 0;
        for (int i = 0; i < filedNameList.size(); i++) {
            Object valueObj = data[valueIndex];
            if (Objects.isNull(valueObj)) {
                continue;
            }
            Field field = null;
            try {
                field = target.getDeclaredField(filedNameList.get(i));
            } catch (NoSuchFieldException e) {
                continue;
            }
            field.setAccessible(true);
            Class<?> type = field.getType();
            String simpleName1 = type.getSimpleName();
            if ("String".equals(simpleName1)) {
                ReflectionUtils.setField(field, o, String.valueOf(valueObj));
            } else if ("Short".equals(simpleName1) || "short".equals(simpleName1)) {
                ReflectionUtils.setField(field, o, Short.valueOf(String.valueOf(valueObj)));
            } else if ("int".equals(simpleName1) || "Integer".equals(simpleName1)) {
                ReflectionUtils.setField(field, o, Integer.parseInt(String.valueOf(valueObj)));
            } else if ("long".equals(simpleName1) || "Long".equals(simpleName1)) {
                ReflectionUtils.setField(field, o, Long.parseLong(String.valueOf(valueObj)));
            } else if ("double".equals(simpleName1) || "Double".equals(simpleName1)) {
                ReflectionUtils.setField(field, o, Double.parseDouble(String.valueOf(valueObj)));
            } else if ("float".equals(simpleName1) || "Float".equals(simpleName1)) {
                ReflectionUtils.setField(field, o, Float.parseFloat(String.valueOf(valueObj)));
            } else if ("Date".equals(simpleName1) || "date".equals(simpleName1)) {
                ReflectionUtils.setField(field, o, (Date) valueObj);
            } else if ("LocalDateTime".equals(simpleName1)) {
                ReflectionUtils.setField(field, o, (LocalDateTime) valueObj);
            } else if ("boolean".equals(simpleName1) || "Boolean".equals(simpleName1)) {
                ReflectionUtils.setField(field, o, (boolean) valueObj);
            }
            //值得索引增加
            valueIndex++;
        }
        return o;
    }

sql语句工具区

List列表转sql(‘in’) 语句

 	/**
     * list列表 转 sql in 查询里面的字符串字符串  如: 'a','b'
     *
     * @param strList 转换list
     * @param join str需要间隔的字符
     * @return 字符串列表
     */
    public static <T> String listToJoinSqlStr(List<T> strList, String join) {
        StringBuilder joinStr = new StringBuilder();
        if (!CollectionUtils.isEmpty(strList)) {
            for (int i = 0; i < strList.size(); i++) {
                if (i != 0) {
                    joinStr.append(join);
                }
                joinStr.append("'").append(strList.get(i)).append("'");
            }
        }
        return joinStr.toString();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值