JAVA8中Predicate,Consumer,UnaryOperator接口的应用

笔者平时时间有限,直接贴代码

<T> List<T> readList(Table table, OID[] oids, String[] fieldNames, Class clazz, List<T> defaultValue, Predicate<? super T> filter, Consumer<? super List<T>> consumer, UnaryOperator<? super T> operator);
 @Override
    public <T> List<T> readList(Table table, OID[] oids, String[] fieldNames, Class clazz, List<T> defaultValue, Predicate<? super T> filter, Consumer<? super List<T>> consumer, UnaryOperator<? super T> operator) {
        if (table == null || table.isEmpty()) {
            return defaultValue;
        }

        Class[] declaredFieldType = getDeclaredFieldType(fieldNames, clazz);

        if(ArrayUtils.isEmpty(fieldNames)||ArrayUtils.isEmpty(declaredFieldType))
        {
            log.error("字段名长度和字段数据类型长度不能为null");
            throw new IllegalArgumentException("字段名长度和字段数据类型长度不能为null");
        }

        if(!ArrayUtils.isSameLength(fieldNames, declaredFieldType))
        {
            throw new IllegalArgumentException("字段名个数与字段数据类型数组长度不一致");
        }

        Map<OID, Table.Row> rowMapping = table.getMap();

        if(MapUtils.isEmpty(rowMapping)) {
            return defaultValue;
        }

        log.debug("待查询oid名称:{}",String.join(",", fieldNames));

        String [] oidInDottedString = Arrays.asList(oids).stream().map(OID::toDottedString).toArray(size->new String[size]);

        List<T> list = new LinkedList<T>();

        for(Table.Row row : rowMapping.values()) {

            Set<OID> keys = row.getMap().keySet();

            try {
                T instance = (T)clazz.newInstance();

                for (OID key : keys) {
                    String dotString = key.toDottedString();

                    for (int i = 0; i < oidInDottedString.length; i++) {

                        String oidString = oidInDottedString[i];

                        if (dotString.contains(oidString)) {

                            String fieldName = fieldNames[i];

                            Variable value = row.getVariable(key);

                            Class declaredType = declaredFieldType[i];

                            setProperty(instance,declaredType,fieldName,value);

                        }
                    }
                }

                list.add(instance);

            }catch (IllegalAccessException|InstantiationException e)
            {
                log.error("提取属性失败:{}",e);
            }
        }

        if(operator != null && CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(instance->{operator.apply(instance);});
        }

        if(filter != null && CollectionUtils.isNotEmpty(list)) {
            list = list.stream().filter(filter).collect(Collectors.toList());
        }

        if(consumer != null && CollectionUtils.isNotEmpty(list)) {
            consumer.accept(list);
        }

        return list;
    }
<T> T readObject(Table table, String[] fieldNames, Class clazz, T defaultValue,final Predicate<? super T> filter,final Consumer<? super T> consumer,final UnaryOperator<? super T> operator);

  @Override
    public <T> T readObject(Table table, String[] fieldNames, Class clazz, T defaultValue, Predicate<? super T> filter, Consumer<? super T> consumer, UnaryOperator<? super T> operator) {

        if (table == null || table.isEmpty()) {
            return defaultValue;
        }
        Optional<T> result = readList(table, fieldNames, clazz, Arrays.asList(defaultValue)/*, null, null, null*/).stream().findFirst();

        return handleSingleObject(result,filter,consumer,operator);

用法:(方法签名会有出入,没有的签名方法,通过重载实现了,在此不贴出来代码,看官可自行实现,有疑问可跟帖留意交流)

//读取ip地址、子网掩码
            Table ipAddrTable = snmpHelper.getTable(MIB.IpAddrTable);

            List<SnmpIfCard> ifCards =  agentService.readList(ipAddrTable,
                    agentService.translateOID(SnmpObjectNotation.ipAddrEntry),
                    SnmpObjectNotation.ipFieldNames, SnmpIfCard.class,
                    null,
                    (SnmpIfCard ifCard) -> {
                        if(ifCard!=null) {
                            //过滤掉回环地址
                            String ifIpAddr = ifCard.getIfIpAddr();
                            return !"127.0.0.1".equals(ifIpAddr);
                        }
                        return false;
                    },(SnmpIfCard ifCard)->{
                        if(ifCard != null) {
                            //设置nodeId
                            ifCard.setNodeId(nodeId);
                            return ifCard;
                        }
                        return null;
                    });

            //网口流量
            Table ifTable = snmpHelper.getTable(MIB.IfTable);
            agentService.readList(ifTable,SnmpObjectNotation.trafficFieldNames,SnmpIfCardTraffic.class,
                    null,
                    (SnmpIfCardTraffic traffic)->{
                        if(traffic != null) {
                            Integer ifIndex = traffic.getIfIndex();
                            //如果网口索引里没有这个IfIndex,则不采集(通常是过滤IfIndex =1的本地回环网卡 lo)
                            List<Integer> allIfIndex = ifCards.stream().map(SnmpIfCard::getIfIndex).collect(Collectors.toList());
                            return allIfIndex.contains(ifIndex);
                        }
                        return false;
                    },
                    captured::setTraffics,
                    (SnmpIfCardTraffic traffic)->{
                        if(traffic != null) {
                            //通过网口索引匹配,将对应网口索引的子网掩码和ip地址拷贝到网口流量信息实体上面
                            Optional<SnmpIfCard> matched = matchIfCard(ifCards, traffic);
                            if (matched.isPresent()) {
                                traffic.setNodeId(nodeId);
                                traffic.setIfIpNetMask(matched.get().getIfIpNetMask());
                                traffic.setIfIpAddr(matched.get().getIfIpAddr());
                            }
                            return traffic;
                        }
                        return null;
                    });


            //文件系统使用情况
            Table hrStorageEntry = snmpHelper.getTable(MIB.hrStorageEntry);

            agentService.readList(hrStorageEntry, SnmpObjectNotation.hrStorageEntryFields,
                    SnmpFileSystemUsage.class,null,
                    captured::setFsUsage,
                    (SnmpFileSystemUsage usage)->{
                        if(usage != null) {
                            usage.setNodeId(nodeId);
                            return usage;
                        }
                        return null;
                    });
  //内存使用率
            Table memory = snmpHelper.getTable(MIB.memory);
            agentService.readObject(memory, SnmpObjectNotation.memoryFieldNames, SnmpMemoryUsage.class,
                    (SnmpMemoryUsage) null,
                    captured::setMemoryUsage,
                    (usage) -> {
                        if(usage !=null) {
                            usage.setNodeId(nodeId);
                            return usage;
                        }
                        return null;
                    });


            //系统运行状态,从这里获取cpu使用率信息
            Table sysStats = snmpHelper.getTable(MIB.systemStats);
            agentService.readObject(sysStats, SnmpObjectNotation.systemStatFields, SnmpCPUUsage.class,
                    (SnmpCPUUsage)null,
                    captured::setCpuUsage,
                    (usage) -> {
                        if(usage !=null) {
                            usage.setNodeId(nodeId);
                            return usage;
                        }
                        return null;
                    });

猜你喜欢

转载自www.cnblogs.com/passedbylove/p/11208010.html