Example usage for org.apache.commons.net.util SubnetUtils getInfo

List of usage examples for org.apache.commons.net.util SubnetUtils getInfo

Introduction

In this page you can find the example usage for org.apache.commons.net.util SubnetUtils getInfo.

Prototype

public final SubnetInfo getInfo() 

Source Link

Document

Return a SubnetInfo instance that contains subnet-specific statistics

Usage

From source file:eu.smartenit.sdn.floodlight090.dtm.DTM.java

/**
 * Returns output port of switch for a new flow.
 *
 * @return output port number//from w  w w . ja v  a2 s.  c o m
 */
public synchronized short getReactiveWithReferenceOutOfPortNumber() {
    logger.debug("getOutOfPortNumberReactiveWithReference() begin");
    if (configData == null) {
        throw new IllegalArgumentException("DTM has not been configured yet");
    }

    if (rVectorMap.isEmpty() || cVectorMap.isEmpty()) {
        throw new IllegalArgumentException("Vectors not set");
    }

    OFPacketIn pi = getOFPacketIn();
    String piDestAddr = intToStringIp(
            new OFMatch().loadFromPacket(pi.getPacketData(), pi.getInPort()).getNetworkDestination());

    logger.debug("Network dest = " + intToStringIp(
            new OFMatch().loadFromPacket(pi.getPacketData(), pi.getInPort()).getNetworkDestination()));

    short[] selectedDaRouterOfPortNumber = null;
    for (ConfigDataEntry entry : configData.getEntries()) {
        String subnet = entry.getRemoteDcPrefix().getPrefix() + "/"
                + Integer.toString(entry.getRemoteDcPrefix().getPrefixLength());
        SubnetUtils utils = new SubnetUtils(subnet);
        if (utils.getInfo().isInRange(piDestAddr)) {
            selectedDaRouterOfPortNumber = new short[] {
                    (short) entry.getTunnels().get(0).getDaRouterOfPortNumber(),
                    (short) entry.getTunnels().get(1).getDaRouterOfPortNumber() };
            logger.debug("IP " + piDestAddr + " in range " + subnet);
        }
    }

    if (selectedDaRouterOfPortNumber == null) {
        logger.debug("Destination host unreachable! Wrong IP address: " + piDestAddr);
        logger.debug("getOutOfPortNumberReactiveWithReference() end");
        return 0;
    }

    logger.debug("Selected DA router ports: " + Arrays.toString(selectedDaRouterOfPortNumber));

    double[] C = { daRouterCVectorMap.get(selectedDaRouterOfPortNumber[0]),
            daRouterCVectorMap.get(selectedDaRouterOfPortNumber[1]), };

    double[] R = { daRouterRVectorMap.get(selectedDaRouterOfPortNumber[0]),
            daRouterRVectorMap.get(selectedDaRouterOfPortNumber[1]), };

    if (daRouterCompenstatingToTunnelMap.get(selectedDaRouterOfPortNumber[0]) > 0) {
        compensatingToTunnel = 1;
    } else if (daRouterCompenstatingToTunnelMap.get(selectedDaRouterOfPortNumber[1]) > 0) {
        compensatingToTunnel = 2;
    } else {
        compensatingToTunnel = 0;
    }

    double[] normalizedR = { R[0] / (R[0] + R[1]), R[1] / (R[0] + R[1]) };
    double[] invNormalizedR = { normalizedR[1], normalizedR[0] };
    double[] traffic = new double[LINK_COUNT];
    double trafficDCDC = 0;
    for (int i = 0; i < LINK_COUNT; i++) {
        traffic[i] = transmittedBytesMap.get(selectedDaRouterOfPortNumber[i])
                - transmittedBytesStartMap.get(selectedDaRouterOfPortNumber[i]);
        trafficDCDC += traffic[i];
    }
    int tunnel;
    if (compensatingToTunnel != 0) { // compensate == true
        int ti = compensatingToTunnel - 1;
        if (traffic[ti] < C[ti] / invNormalizedR[ti]) {
            tunnel = compensatingToTunnel;
            logger.debug("Compensating to tunnel " + tunnel);
        } else {
            resetTransmittedBytesStart(selectedDaRouterOfPortNumber[0]);
            resetTransmittedBytesStart(selectedDaRouterOfPortNumber[1]);
            if (compensatingToTunnel == 1) {
                tunnel = 2;
            } else {
                tunnel = 1;
            }
            logger.debug("Turning off compensation, sending flow to tunnel " + tunnel);
            compensatingToTunnel = 0; // compensate = false
            daRouterCompenstatingToTunnelMap.put(selectedDaRouterOfPortNumber[0], (short) 0);
            daRouterCompenstatingToTunnelMap.put(selectedDaRouterOfPortNumber[1], (short) 0);
        }
    } else {
        if (traffic[0] / trafficDCDC <= normalizedR[0]) {
            tunnel = 1;
        } else {
            tunnel = 2;
        }
        logger.debug("Not compensating, sending flow to tunnel " + tunnel);
    }
    // change tunnel to DA Router port number
    if (tunnel == 1) {
        daRouterOfPortNumber = selectedDaRouterOfPortNumber[0];
    } else if (tunnel == 2) {
        daRouterOfPortNumber = selectedDaRouterOfPortNumber[1];
    } else {
        daRouterOfPortNumber = 0; //drop flow
    }
    logger.debug("Summary:");
    logger.debug("\t C: " + Arrays.toString(C));
    logger.debug("\t normalizedR: " + Arrays.toString(normalizedR));
    logger.debug("\t transmittedBytesStart: " + transmittedBytesStartMap.toString());
    logger.debug("\t transmittedBytes: " + transmittedBytesMap.toString());
    logger.debug("\t traffic: " + Arrays.toString(traffic) + ", trafficDAB: " + trafficDCDC);
    logger.debug("\t OFPortNumber: " + daRouterOfPortNumber);
    logger.debug("getOutOfPortNumberReactiveWithReference() end");
    return (short) daRouterOfPortNumber;
}

From source file:eu.smartenit.sdn.floodlight090.dtm.DTM.java

/**
 * Updates reference vector. Does nothing if provided with null value.
 *
 * @param referenceVector reference vector
 *///from  ww  w  .j  a v a2  s  .  c o m
public synchronized void setReferenceVector(RVector referenceVector) throws IllegalArgumentException {
    logger.debug("setReferenceVector(RVector) begin");
    if (configData == null) {
        throw new IllegalArgumentException("DTM has not been configured yet (ConfigData is null)");
    }

    if (referenceVector == null) {
        logger.debug("Not updating Reference vector");
        logger.debug("setReferenceVector(RVector) end");
        return;
    }

    validateReferenceVector(referenceVector);

    this.referenceVector = referenceVector;
    for (VectorValue vectorValue : referenceVector.getVectorValues()) {
        rVectorMap.put(vectorValue.getTunnelEndPrefix(), vectorValue.getValue());
    }

    for (VectorValue vectorValue : referenceVector.getVectorValues()) {
        String subnet = vectorValue.getTunnelEndPrefix().getPrefix() + "/"
                + Integer.toString(vectorValue.getTunnelEndPrefix().getPrefixLength());
        SubnetUtils utils = new SubnetUtils(subnet);
        for (ConfigDataEntry configDataEntry : configData.getEntries()) {
            for (TunnelInfo tunnelInfo : configDataEntry.getTunnels()) {
                if (utils.getInfo()
                        .isInRange(tunnelInfo.getTunnelID().getRemoteTunnelEndAddress().getPrefix())) {
                    daRouterRVectorMap.put((short) tunnelInfo.getDaRouterOfPortNumber(),
                            vectorValue.getValue());
                }
            }
        }
    }
    calculateRInvMap(referenceVector);

    logger.debug("Reference vector set to " + referenceVector);
    logger.debug("setReferenceVector(RVector) end");
}

From source file:eu.smartenit.sdn.floodlight090.dtm.DTM.java

public synchronized Map<NetworkAddressIPv4, Short> getProactiveOutOfPortNumber() {
    logger.debug("getOutOfPortNumberProactiveWithoutReference() begin");
    if (configData == null) {
        throw new IllegalArgumentException("DTM has not been configured yet");
    }//ww w .  j av  a  2  s  .c  o  m

    if (cVectorMap.isEmpty()) {
        throw new IllegalArgumentException("Compensation vector empty");
    }

    for (VectorValue cVectorValue : compensationVector.getVectorValues()) {
        if (cVectorValue.getValue() >= 0) {
            String subnet = cVectorValue.getTunnelEndPrefix().getPrefix() + "/"
                    + Integer.toString(cVectorValue.getTunnelEndPrefix().getPrefixLength());
            SubnetUtils utils = new SubnetUtils(subnet);
            for (ConfigDataEntry configDataEntry : configData.getEntries()) {
                for (TunnelInfo tunnelInfo : configDataEntry.getTunnels()) {
                    if (utils.getInfo()
                            .isInRange(tunnelInfo.getTunnelID().getRemoteTunnelEndAddress().getPrefix())) {
                        dcPrefixOutOfPortMap.put(configDataEntry.getRemoteDcPrefix(),
                                (short) tunnelInfo.getDaRouterOfPortNumber());
                    }
                }
            }
        }
    }
    logger.debug("getOutOfPortNumberProactiveWithoutReference() end");

    return dcPrefixOutOfPortMap;
}

From source file:core.Task.java

/**
 * ----------------------/*from w w w  .  j a v a2  s  .  c o m*/
 * Executing discovery
 * ----------------------
 */
private void runDiscovery() {

    HashMap<String, HashMap<String, String>> networks;
    List<String> exclusions;

    /*
     * Get networks
     */
    ApiRequest networksRequest = new ApiRequest(this.coordinates).setRequestMethod(ApiRequestMethods.GET)
            .setApiMethod("v1/core/get-networks");

    ApiResponse networksResponse = ApiCaller.request(networksRequest);

    if (!networksResponse.success) {

        /*
         * Log record
         * Can't get node list
         */
        this.logBadResponse("ERROR", "TASK GET NODES",
                "Task " + this.coordinates.get("taskName") + " can't get discovery network list.",
                networksResponse);
        return;
    }

    String networksJson = networksResponse.response;

    Type networksType = new TypeToken<HashMap<String, HashMap<String, String>>>() {
    }.getType();

    try {
        networks = gson.fromJson(networksJson, networksType);

    } catch (JsonSyntaxException e) {
        this.logException("ERROR", "TASK GET NODES",
                "Task " + this.coordinates.get("taskName") + " can't parse discovery network list from json.",
                e);
        return;
    }

    /*
     * Get exclusions IP's
     */
    ApiRequest exclusionsRequest = new ApiRequest(this.coordinates).setRequestMethod(ApiRequestMethods.GET)
            .setApiMethod("v1/core/get-exclusions");

    ApiResponse exclusionsResponse = ApiCaller.request(exclusionsRequest);

    if (!exclusionsResponse.success) {

        /*
         * Log record
         * Can't get node list
         */
        this.logBadResponse("ERROR", "TASK GET NODES",
                "Task " + this.coordinates.get("taskName") + " can't get exclusions ip list.",
                exclusionsResponse);
        return;
    }

    String exclusionsJson = exclusionsResponse.response;

    Type exclusionsType = new TypeToken<ArrayList<String>>() {
    }.getType();

    try {
        exclusions = gson.fromJson(exclusionsJson, exclusionsType);
    } catch (JsonSyntaxException e) {
        this.logException("ERROR", "TASK GET NODES",
                "Task " + this.coordinates.get("taskName") + " can't parse exclusions ip list from json.", e);
        return;
    }

    /*
     * Thread executor init
     */
    ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadCount); // number of threads

    /*
     * Futures for workers results return
     */
    List<Future<Boolean>> results = new ArrayList<>();

    // Adding discovery workers to executor
    // noinspection Java8MapForEach
    networks.entrySet().forEach(node -> {

        Boolean dataValid = true;

        String[] allIps = {};
        List<String> allExclusions = new ArrayList<>();

        String snmpRead = node.getValue().get("snmp_read");
        String version = node.getValue().get("snmp_version");
        String port = node.getValue().get("port_snmp");
        String networkId = node.getValue().get("id");

        Integer snmpVer = 1;
        Integer snmpPort = 161;

        if (snmpRead == null || snmpRead.length() == 0) {
            dataValid = false;
            String unknownTaskMessage = "Task " + this.coordinates.get("taskName") + ". Network "
                    + node.getKey() + ": empty SNMP read community.";
            this.logMessage("ERROR", "TASK EXECUTE", unknownTaskMessage);
        }
        if (version == null || version.length() == 0) {
            dataValid = false;
            String unknownTaskMessage = "Task " + this.coordinates.get("taskName") + ". Network "
                    + node.getKey() + ": empty SNMP version.";
            this.logMessage("ERROR", "TASK EXECUTE", unknownTaskMessage);
        }
        if (port == null || port.length() == 0) {
            dataValid = false;
            String unknownTaskMessage = "Task " + this.coordinates.get("taskName") + ". Network "
                    + node.getKey() + ": empty SNMP port.";
            this.logMessage("ERROR", "TASK EXECUTE", unknownTaskMessage);
        }

        if (dataValid) {
            /*
             * Set SNMP version
             */
            try {
                snmpVer = Integer.parseInt(version);
            } catch (NumberFormatException e) {
                dataValid = false;
                String parseVersionMessage = "Task " + this.coordinates.get("taskName") + ", node "
                        + this.coordinates.get("nodeId") + ": can't parse SNMP version of network";
                this.logException("ERROR", "TASK EXECUTE", parseVersionMessage, e);
            }

            /*
             * Set SNMP port
             */
            try {
                snmpPort = Integer.parseInt(port);
            } catch (NumberFormatException e) {
                dataValid = false;
                String parsePortMessage = "Task " + this.coordinates.get("taskName") + ", node "
                        + this.coordinates.get("nodeId") + ": can't parse SNMP port to integer.";
                this.logException("WARNING", "TASK EXECUTE", parsePortMessage, e);
            }
        }

        /*
         * Calculating all IPs of current subnet
         */
        if (dataValid) {
            try {
                SubnetUtils subnet = new SubnetUtils(node.getKey());

                /*
                 * If exclusions ip is in subnet range, add it to exclusuins list
                 */
                for (String exclusionIp : exclusions) {
                    try {
                        if (subnet.getInfo().isInRange(exclusionIp)) {
                            allExclusions.add(exclusionIp);
                        }
                    } catch (IllegalArgumentException e) {
                        dataValid = false;
                        String validateExclusionsMessage = "Task " + this.coordinates.get("taskName")
                                + ", node " + this.coordinates.get("nodeId") + ": wrong exclusion ip "
                                + exclusionIp;
                        this.logException("WARNING", "TASK EXECUTE", validateExclusionsMessage, e);
                    }
                }

                allIps = subnet.getInfo().getAllAddresses();
            } catch (Exception e) {
                dataValid = false;
                String extractIpsMessage = "Task " + this.coordinates.get("taskName") + ", node "
                        + this.coordinates.get("nodeId") + ": can't extract IPs from subnet.";
                this.logException("WARNING", "TASK EXECUTE", extractIpsMessage, e);
            }
        }

        if (dataValid) {
            for (String ip : allIps) {
                if (!allExclusions.contains(ip)) {
                    Map<String, String> currentCoord = new HashMap<>();
                    currentCoord.putAll(this.coordinates);
                    currentCoord.put("nodeIp", ip);
                    results.add(executor.submit(new WorkerDiscovery(currentCoord, this.settings, networkId,
                            snmpVer, snmpRead, snmpPort)));
                }
            }
        }
    });

    for (Future<Boolean> result : results) {

        Boolean currentResult;

        try {
            currentResult = result.get();

            if (currentResult) {
                this.success++;
            } else {
                this.failed++;
            }

        } catch (Exception e) {
            this.logException("ERROR", "TASK GET WORKER RESPONSE", "Task " + this.coordinates.get("taskName")
                    + " was interrupted while waiting for discovery worker result.", e);
            return;
        }
    }

    executor.shutdown();

    /*
     * Task finish log
     */
    String finalMessage = "Task " + this.coordinates.get("taskName") + " has been finished. " + " Success: "
            + this.success + ". Failed or offline: " + this.failed + ".";
    this.logMessage("INFO", "TASK FINISH", finalMessage);

}

From source file:eu.smartenit.sdn.floodlight090.dtm.DTM.java

/**
 * Updates compensation vector.//from  w  w  w.  ja va2  s  . com
 *
 * @param compensationVector compensation vector
 */
public synchronized void setCompensationVector(CVector compensationVector) {
    logger.debug("setCompensationVector(CVector) begin");
    if (configData == null) {
        throw new IllegalArgumentException("DTM has not been configured yet (ConfigData is null)");
    }
    validateCompensationVector(compensationVector);

    this.compensationVector = compensationVector;
    logger.debug("Compensation vector set to " + compensationVector);

    int i = 1;
    for (VectorValue vectorValue : compensationVector.getVectorValues()) {
        String subnet = vectorValue.getTunnelEndPrefix().getPrefix() + "/"
                + Integer.toString(vectorValue.getTunnelEndPrefix().getPrefixLength());
        SubnetUtils utils = new SubnetUtils(subnet);
        for (ConfigDataEntry configDataEntry : configData.getEntries()) {
            dcNumberCompensateMap.put(i, Boolean.TRUE); //TODO
            for (TunnelInfo tunnelInfo : configDataEntry.getTunnels()) {
                if (utils.getInfo()
                        .isInRange(tunnelInfo.getTunnelID().getRemoteTunnelEndAddress().getPrefix())) {
                    daRouterCVectorMap.put((short) tunnelInfo.getDaRouterOfPortNumber(),
                            vectorValue.getValue());
                    if (configData.getOperationModeSDN() == OperationModeSDN.proactiveWithReferenceVector
                            || configData
                                    .getOperationModeSDN() == OperationModeSDN.reactiveWithReferenceVector) {
                        transmittedBytesStartMap.put((short) tunnelInfo.getDaRouterOfPortNumber(),
                                transmittedBytesMap.get((short) tunnelInfo.getDaRouterOfPortNumber()));
                        if (vectorValue.getValue() > 0) {
                            daRouterCompenstatingToTunnelMap.put((short) tunnelInfo.getDaRouterOfPortNumber(),
                                    (short) 1);
                        }
                        if (vectorValue.getValue() < 0) {
                            daRouterCompenstatingToTunnelMap.put((short) tunnelInfo.getDaRouterOfPortNumber(),
                                    (short) -1);
                        }
                        if (vectorValue.getValue() == 0) {
                            daRouterCompenstatingToTunnelMap.put((short) tunnelInfo.getDaRouterOfPortNumber(),
                                    (short) 0);
                        }
                    }
                }
            }
            i++;
        }
    }

    for (VectorValue vectorValue : compensationVector.getVectorValues()) {
        cVectorMap.put(vectorValue.getTunnelEndPrefix(), vectorValue.getValue());
        if (vectorValue.getValue() > 0) {
            compensatingMap.put((short) compensationVector.getSourceAsNumber(), true);
            compensatingToTunnelMap.put((short) compensationVector.getSourceAsNumber(),
                    vectorValue.getTunnelEndPrefix());
        }
    }

    if (configData.getOperationModeSDN() == OperationModeSDN.proactiveWithReferenceVector
            || configData.getOperationModeSDN() == OperationModeSDN.proactiveWithoutReferenceVector) {
        sendStaticFlowRule(getProactiveOutOfPortNumber());
    }
    logger.debug("setCompensationVector(CVector) end");
}

From source file:com.cloud.network.bigswitch.BigSwitchBcfUtils.java

public List<AclData> listACLbyNetwork(Network network) {
    List<AclData> aclList = new ArrayList<AclData>();

    List<FirewallRuleVO> fwRules;
    fwRules = _fwRulesDao.listByNetworkAndPurposeAndNotRevoked(network.getId(), Purpose.Firewall);
    List<FirewallRulesCidrsVO> fwCidrList = null;
    SubnetUtils utils;

    for (FirewallRuleVO rule : fwRules) {
        AclData acl = new AclData();
        acl.setId(rule.getUuid());//  w  w w  .j  ava  2s .com
        acl.setPriority((int) rule.getId()); // CloudStack Firewall interface does not have priority
        acl.setIpProto(rule.getProtocol());
        String cidr = null;
        Integer port = rule.getSourcePortStart();
        fwCidrList = _fwCidrsDao.listByFirewallRuleId(rule.getId());
        if (fwCidrList != null) {
            if (fwCidrList.size() > 1 || !rule.getSourcePortEnd().equals(port)) {
                continue;
            } else {
                cidr = fwCidrList.get(0).getCidr();
            }
        }
        if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) {
            cidr = "";
        } else {
            utils = new SubnetUtils(cidr);
            if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) {
                continue;
            }
        }
        acl.setSource(acl.new AclNetwork(cidr, port));
        acl.setAction("permit");

        aclList.add(acl);
    }

    List<NetworkACLItemVO> aclItems;
    List<NetworkACLItemCidrsVO> aclCidrList;

    if (network.getNetworkACLId() != null) {
        aclItems = _aclItemDao.listByACL(network.getNetworkACLId());
        for (NetworkACLItem item : aclItems) {
            AclData acl = new AclData();
            acl.setId(item.getUuid());
            acl.setPriority(item.getNumber());
            acl.setIpProto(item.getProtocol());
            String cidr = null; // currently BCF supports single cidr policy
            Integer port = item.getSourcePortStart(); // currently BCF supports single port policy
            aclCidrList = _aclItemCidrsDao.listByNetworkACLItemId(item.getId());
            if (aclCidrList != null) {
                if (aclCidrList.size() > 1 || !item.getSourcePortEnd().equals(port)) {
                    continue;
                } else {
                    cidr = aclCidrList.get(0).getCidr();
                }
            }
            if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) {
                cidr = "";
            } else {
                utils = new SubnetUtils(cidr);
                if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) {
                    continue;
                }
            }
            acl.setSource(acl.new AclNetwork(cidr, port));
            acl.setAction(item.getAction().name());

            aclList.add(acl);
        }
    }

    return aclList;
}

From source file:com.cloud.network.element.BigSwitchBcfElement.java

@Override
public boolean applyFWRules(Network network, List<? extends FirewallRule> rules)
        throws ResourceUnavailableException {
    SubnetUtils utils;
    String cidr = null;// ww w  .  j a v  a 2  s.  c  o m
    List<String> cidrList;
    for (FirewallRule r : rules) {
        if (r.getState() == FirewallRule.State.Revoke) {
            continue;
        }
        cidrList = r.getSourceCidrList();
        if (cidrList != null) {
            if (cidrList.size() > 1 || !r.getSourcePortEnd().equals(r.getSourcePortStart())) {
                throw new ResourceUnavailableException("One CIDR and one port only please.", Network.class,
                        network.getId());
            } else {
                cidr = cidrList.get(0);
            }
        }
        if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) {
            cidr = "";
        } else {
            utils = new SubnetUtils(cidr);
            if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) {
                throw new ResourceUnavailableException("Invalid CIDR in Firewall rule.", Network.class,
                        network.getId());
            }
        }
    }
    updateBcfRouter(network);
    return true;
}

From source file:com.cloud.network.element.BigSwitchBcfElement.java

@Override
public boolean applyNetworkACLs(Network network, List<? extends NetworkACLItem> rules)
        throws ResourceUnavailableException {
    SubnetUtils utils;
    String cidr = null;/*from  w w w.ja  v  a2  s .  c o m*/
    List<String> cidrList;
    for (NetworkACLItem r : rules) {
        if (r.getState() == NetworkACLItem.State.Revoke) {
            continue;
        }
        cidrList = r.getSourceCidrList();
        if (cidrList != null) {
            if (cidrList.size() > 1 || !r.getSourcePortEnd().equals(r.getSourcePortStart())) {
                throw new ResourceUnavailableException("One CIDR and one port only please.", Network.class,
                        network.getId());
            } else {
                cidr = cidrList.get(0);
            }
        }
        if (cidr == null || cidr.equalsIgnoreCase("0.0.0.0/0")) {
            cidr = "";
        } else {
            utils = new SubnetUtils(cidr);
            if (!utils.getInfo().getNetworkAddress().equals(utils.getInfo().getAddress())) {
                throw new ResourceUnavailableException("Invalid CIDR in Network ACL rule.", Network.class,
                        network.getId());
            }
        }
    }
    updateBcfRouter(network);
    return true;
}

From source file:com.topsec.tsm.sim.asset.web.AssetListController.java

@RequestMapping("stopDiscover")
@ResponseBody//  ww w.j a  v a2 s  .  c o m
public Object stopDiscover(@RequestParam(value = "networkAddress", required = false) String networkAddressParam,
        @RequestParam(value = "netmask", defaultValue = "24") int netmask,
        @RequestParam(value = "scanNodeId") String scanNodeId) {
    if (StringUtil.isBlank(networkAddressParam)
            || networkAddressParam.equals(IpAddress.getLocalIp().getLocalhostAddress())) {
        networkAddressParam = IpAddress.getLocalIpv4Address().toString();
    }
    Node collectorNode = nodeMgr.getChildOrSelf(scanNodeId, NodeDefinition.NODE_TYPE_COLLECTOR);
    SubnetUtils subnetUtils = new SubnetUtils(networkAddressParam + "/" + netmask);
    String networkAddress = subnetUtils.getInfo().getNetworkAddress();
    SubNet sbt = dcvAssetManager.getSubNet(collectorNode.getIp(), networkAddress, netmask);
    if (sbt != null) {
        sbt.setScannedCount(sbt.getAssetCount());
    }
    HashMap<String, Object> params = new HashMap<String, Object>(3);
    params.put("networkAddress", networkAddress);
    params.put("netmask", netmask);
    try {
        NodeUtil.dispatchCommand(NodeUtil.getRoute(collectorNode), MessageDefinition.CMD_STOP_DISCOVER, params,
                5000);
    } catch (CommunicationException e) {
        logger.warn("???!");
        return false;
    }
    return true;
}

From source file:com.topsec.tsm.sim.asset.web.AssetListController.java

/**
 * ?//w  w w.  j a  va2s  .com
 * @param networkAddressParam ?
 * @param nodeId ??
 * @param netmask ?
 * @return
 */
@RequestMapping("assetDiscover")
@ResponseBody
public Object assetDiscover(
        @RequestParam(value = "networkAddress", required = false) String networkAddressParam,
        @RequestParam(value = "netmask", defaultValue = "24") int netmask,
        @RequestParam(value = "scanNodeId", required = false) String nodeId,
        @RequestParam(value = "rescan", defaultValue = "false") boolean rescan) {
    Result result = new Result();
    try {
        //???127.0.0.1::1ip??
        if (StringUtil.isBlank(networkAddressParam)
                || networkAddressParam.equals(IpAddress.getLocalIp().getLocalhostAddress())) {
            networkAddressParam = IpAddress.getLocalIpv4Address().toString();
        }
        Node scanNode = nodeMgr.getChildOrSelf(nodeId, NodeDefinition.NODE_TYPE_COLLECTOR);
        SubnetUtils subnetUtils = new SubnetUtils(networkAddressParam + "/" + netmask);
        String networkAddress = subnetUtils.getInfo().getNetworkAddress();
        int assetCount = subnetUtils.getInfo().getAddressCount();
        if (assetCount > MAX_SCAN_HOST_COUNT) {//????
            result.buildError("????(" + MAX_SCAN_HOST_COUNT
                    + ")?????");
            return result;
        }
        if (rescan) {//???
            dcvAssetManager.removeSubnet(new SubNet(scanNode.getIp(), networkAddress, netmask));
        }
        JSONObject data = new JSONObject();
        JSONArray assetsJson = new JSONArray();
        SubNet subnet = dcvAssetManager.getSubNet(scanNode.getIp(), networkAddress, netmask);
        if (subnet == null) {
            result = sendDiscoverCommand(scanNode, networkAddress, netmask, assetCount);
        } else {
            if (ObjectUtils.isNotEmpty(subnet.getAssets())) {
                Node manageNode = nodeMgr.getAuditorOrAgentByIp(subnet.getScanHost());
                for (AssetObject asset : subnet.getAssets()) {
                    JSONObject assetJson = FastJsonUtil.toJSON(asset, "scanNodeId=nodeId", "ip", "mac",
                            "assGroup.groupId=groupId", "assGroup.groupName=groupName");
                    assetJson.put("nodeId", manageNode == null ? nodeMgr.getKernelAuditor(false).getNodeId()
                            : manageNode.getNodeId());
                    assetsJson.add(assetJson);
                }
            }
            result.build(true);
        }
        data.put("rows", assetsJson);
        data.put("total", assetsJson.size());
        data.put("progress", subnet == null ? 0 : subnet.getProgress());
        result.setResult(data);
    } catch (Exception e) {
        logger.error("assetlist/assetDiscover", e);
        result.buildError("?");
    }
    return result;
}