Example usage for java.net UnknownHostException getClass

List of usage examples for java.net UnknownHostException getClass

Introduction

In this page you can find the example usage for java.net UnknownHostException getClass.

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:net.decix.jatlasx.ripe.atlas.api.handler.ProbeHandler.java

public List<IpAddress> handleResponse(String jsonString) {

    JSONObject jsonObj = new JSONObject(jsonString);
    JSONArray probeDescArray = (JSONArray) jsonObj.get("objects");
    JSONObject probeDescObj = (JSONObject) probeDescArray.get(0);

    String ipAddress = (String) probeDescObj.get(ApiKeys.ipv4);

    List<IpAddress> list = new ArrayList<IpAddress>();
    IpAddress address = null;/*from   ww  w  .  j  a v  a 2  s. c o m*/
    try {
        address = new IpAddress(ipAddress);
        list.add(address);
    } catch (UnknownHostException e) {
        String errorMsg = "Could not create IP-addresses";
        System.err.println(e.getClass().getName() + ":" + errorMsg + " (" + this.getClass().getName() + ")");
    }
    return list;
}

From source file:net.decix.jatlasx.ripe.atlas.api.handler.TraceHandler.java

public List<IpAddress> handleResponse(String jsonString) {

    List<IpAddress> ipAddresses = new LinkedList<IpAddress>();
    JSONArray jsonArray = new JSONArray(jsonString);

    for (int i = 0; i < 1; i++) {
        JSONObject hop = (JSONObject) jsonArray.get(i);
        String ipAddress = "null";
        if (hop.has("from")) {
            ipAddress = String.valueOf(hop.get("from"));
        }/*ww  w. j a v  a  2s .c  o m*/

        try {
            ipAddresses.add(new IpAddress(ipAddress));
        } catch (UnknownHostException e) {
            String errorMsg = "Could not create IP-address:" + ipAddress;
            System.err.println(e.getClass().getName() + ":" + errorMsg + "(" + this.getClass().getName() + ")");
        }
    }
    return ipAddresses;
}

From source file:net.decix.jatlasx.ripe.atlas.api.handler.TracerouteHandler.java

public List<TraceroutePath> handleResponse(String jsonString) {

    List<TraceroutePath> listOfPaths = new LinkedList<TraceroutePath>();

    JSONArray tracesListArray = new JSONArray(jsonString);

    for (int i = 0; i < tracesListArray.length(); i++) {
        JSONObject results = (JSONObject) tracesListArray.get(i);
        IpAddress source = null;//  w w  w. j a va 2  s .  c  om
        IpAddress destination = null;
        try {
            source = new IpAddress((String) results.get("from"));
            destination = new IpAddress((String) results.get("dst_name"));
        } catch (UnknownHostException e) {
            String errorMsg = "Could not create IP-addresses";
            System.err
                    .println(e.getClass().getName() + ":" + errorMsg + " (" + this.getClass().getName() + ")");
        }
        TracesHandler handler = new TracesHandler();
        String resultString = results.get("result").toString();
        List<IpAddress> trace = handler.handleResponse(resultString);

        TraceroutePath path = new TraceroutePath(source, destination, trace);
        listOfPaths.add(path);
    }
    return listOfPaths;
}

From source file:com.clustercontrol.repository.factory.SearchNodeBySNMP.java

/**
 *  ?????/*w  ww.  ja v a2s.  c  o m*/
 * @param IPadder
 * @param ret
 * @param mode
 * @param locale
 * @return
 * @throws UnknownHostException
 */
private static NodeInfo stractProperty(String ipAddress, int port, String community, int version,
        String securityLevel, String user, String authPass, String privPass, String authProtocol,
        String privProtocol, DataTable ret) throws UnknownHostException {

    NodeInfo property = new NodeInfo();
    String facilityId = null;

    /*
     * hinemos.properties?repository.device.search.verbose=true?????
     * IO?0??????search??
     * ?false???0???search?
     * since 3.2.0
     */
    boolean verbose = HinemosPropertyUtil.getHinemosPropertyBool("repository.device.search.verbose", false);

    //""??
    if (ret.getValue(getEntryKey(SearchDeviceProperties.getOidDescr())) != null) {
        if (((String) ret.getValue(getEntryKey(SearchDeviceProperties.getOidDescr())).getValue())
                .length() != 0) {
            property.setDescription("Auto detect at " + HinemosTime.getDateString());
        }
    }

    int ipAddressVersion = 0;
    try {
        InetAddress address = InetAddress.getByName(ipAddress);

        if (address instanceof Inet4Address) {
            //IPv4?????String?
            if (ipAddress.matches(".{1,3}?\\..{1,3}?\\..{1,3}?\\..{1,3}?")) {
                property.setIpAddressV4(ipAddress);
                ipAddressVersion = 4;
            }

        } else if (address instanceof Inet6Address) {
            property.setIpAddressV6(ipAddress);
            ipAddressVersion = 6;
        }

        //IP??
        property.setIpAddressVersion(ipAddressVersion);
    } catch (UnknownHostException e) {
        m_log.info("stractProperty() : " + e.getClass().getSimpleName() + ", " + e.getMessage());
        throw e;
    }

    //SNMP?
    property.setSnmpPort(port);
    property.setSnmpCommunity(community);
    property.setSnmpVersion(version);
    property.setSnmpSecurityLevel(securityLevel);
    property.setSnmpUser(user);
    property.setSnmpAuthPassword(authPass);
    property.setSnmpPrivPassword(privPass);
    property.setSnmpAuthProtocol(authProtocol);
    property.setSnmpPrivProtocol(privProtocol);

    //hostname ?
    if (ret.getValue(getEntryKey(SearchDeviceProperties.getOidName())) != null) {
        String hostname = (String) ret.getValue(getEntryKey(SearchDeviceProperties.getOidName())).getValue();
        m_log.debug("hostname=" + hostname);
        if (hostname.length() != 0) {
            //hosname.domain???hostname??
            hostname = getShortName(hostname);

            //ID???
            facilityId = hostname;
            property.setFacilityId(hostname);
            property.setFacilityName(hostname);

            //?????????
            ArrayList<NodeHostnameInfo> list = new ArrayList<NodeHostnameInfo>();
            list.add(new NodeHostnameInfo(property.getFacilityId(), hostname));
            property.setNodeHostnameInfo(list);
            property.setNodeName(hostname);
        }
    } else {
        m_log.info("hostname is null");
    }

    //?snmpd.conf?????
    if (ret.getValue(getEntryKey(SearchDeviceProperties.getOidContact())) != null) {
        if (((String) ret.getValue(getEntryKey(SearchDeviceProperties.getOidContact())).getValue())
                .length() != 0) {
            property.setAdministrator(
                    (String) ret.getValue(getEntryKey(SearchDeviceProperties.getOidContact())).getValue());
        }
    }

    //????Windows, Linux, Solaris?Other??
    String platform = "OTHER";
    if (ret.getValue(getEntryKey(SearchDeviceProperties.getOidDescr())) != null) {
        String description = ((String) ret.getValue(getEntryKey(SearchDeviceProperties.getOidDescr()))
                .getValue());
        if (description.length() != 0) {
            String OsName = "";

            //OS?????

            if (description.matches(".*indows.*")) {
                OsName = "Windows";
                platform = "WINDOWS";
            } else if (description.matches(".*inux.*")) {
                OsName = "Linux";
                platform = "LINUX";
            } else if (solarisFlag && (description.matches(".*SunOS.*") || description.matches("Solaris"))) {
                // ?SOLARIS????????
                // ??????SOLARIS?
                OsName = "Solaris";
                platform = "SOLARIS";
            } else {
                if (description.indexOf(" ") != -1) {
                    OsName = description.substring(0, description.indexOf(" "));
                }
            }

            //OS??????
            property.setOsName(OsName);

            //OS?
            property.setOsVersion(description);
        }
    }

    // 
    // ?OTHER
    property.setPlatformFamily(platform);

    HashMap<String, Boolean> diskNameDuplicateSet = createDiskNameDuplicateSet(ret);
    HashMap<String, Boolean> nicNameDuplicateSet = createNicNameDuplicateSet(ret);

    // ???????????
    // ????????????????
    int deviceCount = 0;

    // Disk?
    ArrayList<NodeDiskInfo> diskList = new ArrayList<NodeDiskInfo>();
    for (String fullOid : ret.keySet()) {
        //DISK???
        if (!fullOid.startsWith(getEntryKey(SearchDeviceProperties.getOidDiskIndex()) + ".")) {
            continue;
        }
        // SearchDeviceProperties.getOidDISK_INDEX=".1.3.6.1.4.1.2021.13.15.1.1.1";
        // SearchDeviceProperties.getOidDISK_NAME =".1.3.6.1.4.1.2021.13.15.1.1.2";
        if (ret.getValue(fullOid) == null || ret.getValue(fullOid).getValue() == null
                || ((Long) ret.getValue(fullOid).getValue()) == 0) {
            continue;
        }
        m_log.debug("Find Disk : fullOid = " + fullOid);

        String i = fullOid.substring(fullOid.lastIndexOf(".") + 1);
        String disk = (String) ret.getValue(getEntryKey(SearchDeviceProperties.getOidDiskName() + "." + i))
                .getValue();
        Long ionRead = ret.getValue(getEntryKey(SearchDeviceProperties.getOidDiskIonRead() + "." + i)) == null
                ? Long.valueOf(0)
                : (Long) ret.getValue(getEntryKey(SearchDeviceProperties.getOidDiskIonRead() + "." + i))
                        .getValue();
        Long ionWrite = ret.getValue(getEntryKey(SearchDeviceProperties.getOidDiskIonWrite() + "." + i)) == null
                ? Long.valueOf(0)
                : (Long) ret.getValue(getEntryKey(SearchDeviceProperties.getOidDiskIonWrite() + "." + i))
                        .getValue();
        Long ioRead = ret.getValue(getEntryKey(SearchDeviceProperties.getOidDiskIoRead() + "." + i)) == null
                ? Long.valueOf(0)
                : (Long) ret.getValue(getEntryKey(SearchDeviceProperties.getOidDiskIoRead() + "." + i))
                        .getValue();
        Long ioWrite = ret.getValue(getEntryKey(SearchDeviceProperties.getOidDiskIoWrite() + "." + i)) == null
                ? Long.valueOf(0)
                : (Long) ret.getValue(getEntryKey(SearchDeviceProperties.getOidDiskIoWrite() + "." + i))
                        .getValue();
        //DISK_IO?0?????
        if (verbose || (ionRead != 0 && ionWrite != 0 && ioRead != 0 && ioWrite != 0)) {

            // ???????????(OID)??
            if (diskNameDuplicateSet != null && diskNameDuplicateSet.get(disk) != null
                    && diskNameDuplicateSet.get(disk)) {
                disk = disk + "(" + i + ")";
            }

            NodeDiskInfo diskInfo = new NodeDiskInfo(facilityId,
                    ((Long) ret.getValue(fullOid).getValue()).intValue(), DeviceTypeConstant.DEVICE_DISK, disk);
            // ???
            diskInfo.setDeviceDisplayName(disk);
            // ?(0)
            diskInfo.setDiskRpm(0);
            deviceCount++;
            diskList.add(diskInfo);
        }
    }
    Collections.sort(diskList, new Comparator<NodeDeviceInfo>() {
        @Override
        public int compare(NodeDeviceInfo o1, NodeDeviceInfo o2) {
            int ret = 0;
            ret = o1.getDeviceType().compareTo(o2.getDeviceType());
            if (ret == 0) {
                ret = o1.getDeviceDisplayName().compareTo(o2.getDeviceDisplayName());
            }
            return ret;
        }
    });
    property.setNodeDiskInfo(diskList);

    // NIC?
    ArrayList<NodeNetworkInterfaceInfo> nicList = new ArrayList<NodeNetworkInterfaceInfo>();
    for (String fullOid : ret.keySet()) {
        //SearchDeviceProperties.getOidNIC_INDEX =".1.3.6.1.2.1.2.2.1.1";
        //SearchDeviceProperties.getOidNIC_NAME  =".1.3.6.1.2.1.2.2.1.2";
        //NIC???
        if (!fullOid.startsWith(getEntryKey(SearchDeviceProperties.getOidNicIndex()) + ".")) {
            continue;
        }
        String tmpIndex = fullOid.substring(fullOid.lastIndexOf(".") + 1);
        String deviceName = "";
        if (ret.getValue(fullOid) == null || ret.getValue(fullOid).getValue() == null
                || ((Long) ret.getValue(fullOid).getValue()) == 0) {
            continue;
        }
        m_log.debug("Find Nic : fullOid = " + fullOid);

        deviceName = (String) ret.getValue(getEntryKey(SearchDeviceProperties.getOidNicName() + "." + tmpIndex))
                .getValue();

        String nicMacAddress = "";
        if (ret.getValue(getEntryKey(SearchDeviceProperties.getOidNicMacAddress() + "." + tmpIndex)) != null) {
            nicMacAddress = (String) ret
                    .getValue(getEntryKey(SearchDeviceProperties.getOidNicMacAddress() + "." + tmpIndex))
                    .getValue();
        }

        String nicIpAddress = "";

        if (ipAddressVersion == 4) {
            // IPv4 address from IP-MIB::ipAddressIfIndex.ipv4
            //
            // (sample)
            // # snmpwalk -c public -v 2c localhost .1.3.6.1.2.1.4.34.1.3.1.4
            // IP-MIB::ipAddressIfIndex.ipv4."127.0.0.1" = INTEGER: 1
            // IP-MIB::ipAddressIfIndex.ipv4."192.168.10.211" = INTEGER: 3
            // IP-MIB::ipAddressIfIndex.ipv4."192.168.10.255" = INTEGER: 3
            // IP-MIB::ipAddressIfIndex.ipv4."192.168.11.211" = INTEGER: 2
            // IP-MIB::ipAddressIfIndex.ipv4."192.168.11.255" = INTEGER: 2
            Pattern ipAddrV4Pattern = Pattern.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})$");
            if (ret.getValueSetStartWith(getEntryKey(SearchDeviceProperties.getOidNicIpAddressv4())) != null) {
                for (TableEntry entry : ret
                        .getValueSetStartWith(getEntryKey(SearchDeviceProperties.getOidNicIpAddressv4()))) {
                    if (entry.getValue() != null && tmpIndex.equals(((Long) entry.getValue()).toString())) {
                        Matcher matcher = ipAddrV4Pattern.matcher(entry.getKey());
                        if (matcher.find()) {
                            // check address type (allow only unicast)
                            // # snmpwalk -On -c public -v 2c 192.168.10.101 IP-MIB::ipAddressType.ipv4
                            // .1.3.6.1.2.1.4.34.1.4.1.4.127.0.0.1 = INTEGER: unicast(1)
                            // .1.3.6.1.2.1.4.34.1.4.1.4.192.168.10.101 = INTEGER: unicast(1)
                            // .1.3.6.1.2.1.4.34.1.4.1.4.192.168.10.255 = INTEGER: broadcast(3)
                            if (ret.getValue(getEntryKey(SearchDeviceProperties.getOidNicIpAddressv4Type() + "."
                                    + matcher.group(1))) != null) {
                                if ((Long) ret
                                        .getValue(getEntryKey(SearchDeviceProperties.getOidNicIpAddressv4Type()
                                                + "." + matcher.group(1)))
                                        .getValue() != 1) {
                                    continue;
                                }
                            }

                            // set first matched address
                            nicIpAddress = matcher.group(1);
                            break;
                        }
                    }
                }
            }
        } else {
            // IPv6 Address from IP-MIB::ipAddressIfIndex.ipv6
            //
            // (sample)
            // # snmpwalk -c public -v 2c localhost .1.3.6.1.2.1.4.34.1.3.2.16
            // IP-MIB::ipAddressIfIndex.ipv6."00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:01" = INTEGER: 1
            // IP-MIB::ipAddressIfIndex.ipv6."fe:80:00:00:00:00:00:00:50:54:00:ff:fe:be:83:2a" = INTEGER: 2
            // IP-MIB::ipAddressIfIndex.ipv6."fe:80:00:00:00:00:00:00:50:54:00:ff:fe:ed:d4:3c" = INTEGER: 3
            Pattern ipAddrV6Pattern = Pattern.compile(
                    "((\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3}))$");
            if (ret.getValueSetStartWith(getEntryKey(SearchDeviceProperties.getOidNicIpAddressv6())) != null) {
                for (TableEntry entry : ret
                        .getValueSetStartWith(getEntryKey(SearchDeviceProperties.getOidNicIpAddressv6()))) {
                    if (entry.getValue() != null && tmpIndex.equals(((Long) entry.getValue()).toString())) {
                        m_log.debug(entry.getKey() + " : " + entry.getValue());
                        Matcher matcher = ipAddrV6Pattern.matcher(entry.getKey());
                        if (matcher.find()) {
                            // check address type (allow only unicast)
                            // # snmpwalk -On -c public -v 2c localhost IP-MIB::ipAddressType.ipv6
                            // .1.3.6.1.2.1.4.34.1.4.2.16.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1 = INTEGER: unicast(1)
                            // .1.3.6.1.2.1.4.34.1.4.2.16.254.128.0.0.0.0.0.0.80.84.0.255.254.190.131.42 = INTEGER: unicast(1)
                            if (ret.getValue(getEntryKey(SearchDeviceProperties.getOidNicIpAddressv6Type() + "."
                                    + matcher.group(1))) != null) {
                                if ((Long) ret
                                        .getValue(getEntryKey(SearchDeviceProperties.getOidNicIpAddressv6Type()
                                                + "." + matcher.group(1)))
                                        .getValue() != 1) {
                                    continue;
                                }
                            }

                            // set first matched address
                            String hex = "";
                            for (int i = 1; i < 17; i++) {
                                hex = String.format("%02x", Integer.parseInt(matcher.group(i + 1)))
                                        .toUpperCase();
                                nicIpAddress += "".equals(nicIpAddress) ? hex : ":" + hex;
                            }
                            break;
                        }
                    }
                }
            }
        }

        // NIC?IN/OUT?0????
        String key = "";
        key = getEntryKey(SearchDeviceProperties.getOidNicInOctet() + "." + tmpIndex);
        Long inOctet = ret.getValue(key) == null ? Long.valueOf(0) : (Long) ret.getValue(key).getValue();
        key = getEntryKey(SearchDeviceProperties.getOidNicOutOctet() + "." + tmpIndex);
        Long outOctet = ret.getValue(key) == null ? Long.valueOf(0) : (Long) ret.getValue(key).getValue();
        if (!verbose && inOctet == 0 && outOctet == 0) {
            continue;
        }
        // ???????????(OID)??
        if (nicNameDuplicateSet != null && nicNameDuplicateSet.get(deviceName) != null
                && nicNameDuplicateSet.get(deviceName)) {
            deviceName = deviceName + "(." + tmpIndex + ")";
        }
        Long deviceIndex = (Long) ret
                .getValue(getEntryKey(SearchDeviceProperties.getOidNicIndex() + "." + tmpIndex)).getValue();
        NodeNetworkInterfaceInfo nicInfo = new NodeNetworkInterfaceInfo(facilityId, deviceIndex.intValue(),
                DeviceTypeConstant.DEVICE_NIC, deviceName);
        // ???
        nicInfo.setDeviceDisplayName(deviceName);
        // ????
        if (deviceName.length() > 128) {
            deviceName = deviceName.substring(0, 128);
        }
        nicInfo.setDeviceName(deviceName);
        // MAC?
        nicInfo.setNicMacAddress(nicMacAddress);
        // IP?
        nicInfo.setNicIpAddress(nicIpAddress);
        deviceCount++;
        nicList.add(nicInfo);
    }
    Collections.sort(nicList, new Comparator<NodeDeviceInfo>() {
        @Override
        public int compare(NodeDeviceInfo o1, NodeDeviceInfo o2) {
            int ret = 0;
            ret = o1.getDeviceType().compareTo(o2.getDeviceType());
            if (ret == 0) {
                ret = o1.getDeviceDisplayName().compareTo(o2.getDeviceDisplayName());
            }
            return ret;
        }
    });
    property.setNodeNetworkInterfaceInfo(nicList);

    //
    deviceCount = 0;
    ArrayList<NodeFilesystemInfo> filesystemList = new ArrayList<NodeFilesystemInfo>();
    for (String fullOid : ret.keySet()) {
        // SearchDeviceProperties.getOidFILESYSTEM_INDEX = ".1.3.6.1.2.1.25.2.3.1.1";
        // SearchDeviceProperties.getOidFILESYSTEM_NAME  = ".1.3.6.1.2.1.25.2.3.1.3";
        //DISK???
        if (!fullOid.startsWith(getEntryKey(SearchDeviceProperties.getOidFilesystemIndex()) + ".")) {
            continue;
        }
        if (ret.getValue(fullOid) == null || ret.getValue(fullOid).getValue() == null
                || ((Long) ret.getValue(fullOid).getValue()) == 0) {
            continue;
        }
        m_log.debug("Find FileSystem : fullOid = " + fullOid);

        //hrStrageFixedDisk?????
        //.1.3.6.1.2.1.25.2.1.4?hrStrageFixedDisk
        String i = fullOid.substring(fullOid.lastIndexOf(".") + 1);
        String strageType = ret.getValue(getEntryKey(SearchDeviceProperties.getOidFilesystemType() + "." + i))
                .getValue().toString();

        if (strageType.equals(".1.3.6.1.2.1.25.2.1.4")) {

            //hrStorageSize?0????
            String hrStorageSize = getEntryKey(SearchDeviceProperties.getOidFilesystemSize() + "." + i);
            Long storageSize = ret.getValue(hrStorageSize) == null ? Long.valueOf(0)
                    : (Long) ret.getValue(hrStorageSize).getValue();
            if (!verbose && storageSize == 0) {
                continue;
            }

            NodeFilesystemInfo filesystem = new NodeFilesystemInfo(facilityId,
                    ((Long) ret.getValue(getEntryKey(SearchDeviceProperties.getOidFilesystemIndex() + "." + i))
                            .getValue()).intValue(),
                    DeviceTypeConstant.DEVICE_FILESYSTEM,
                    ((String) ret.getValue(getEntryKey(SearchDeviceProperties.getOidFilesystemName() + "." + i))
                            .getValue()));

            //??
            filesystem.setDeviceDisplayName(convStringFilessystem(
                    ((String) ret.getValue(getEntryKey(SearchDeviceProperties.getOidFilesystemName() + "." + i))
                            .getValue())));
            deviceCount++;
            filesystemList.add(filesystem);
        }
    }
    Collections.sort(filesystemList, new Comparator<NodeDeviceInfo>() {
        @Override
        public int compare(NodeDeviceInfo o1, NodeDeviceInfo o2) {
            int ret = 0;
            ret = o1.getDeviceType().compareTo(o2.getDeviceType());
            if (ret == 0) {
                ret = o1.getDeviceDisplayName().compareTo(o2.getDeviceDisplayName());
            }
            return ret;
        }
    });
    property.setNodeFilesystemInfo(filesystemList);

    // CPU
    deviceCount = 0;
    ArrayList<NodeCpuInfo> cpuList = new ArrayList<NodeCpuInfo>();
    for (String fullOid : ret.keySet()) {
        // SearchDeviceProperties.getOidCPU_INDEX=".1.3.6.1.2.1.25.3.3.1.2";
        if (!fullOid.startsWith(getEntryKey(SearchDeviceProperties.getOidCpuIndex()) + ".")
                || ret.getValue(fullOid) == null) {
            continue;
        }
        m_log.debug("Find Cpu : fullOid = " + fullOid);

        String indexStr = fullOid.replaceFirst(getEntryKey(SearchDeviceProperties.getOidCpuIndex()) + ".", "");
        m_log.debug("cpu fullOid = " + fullOid + ", index = " + indexStr);
        NodeCpuInfo cpu = new NodeCpuInfo(facilityId, Integer.valueOf(indexStr), DeviceTypeConstant.DEVICE_CPU,
                indexStr);
        cpu.setDeviceDisplayName(DeviceTypeConstant.DEVICE_CPU + deviceCount);
        cpu.setDeviceName(indexStr);

        cpuList.add(cpu);
        deviceCount++;
    }
    Collections.sort(cpuList, new Comparator<NodeDeviceInfo>() {
        @Override
        public int compare(NodeDeviceInfo o1, NodeDeviceInfo o2) {
            int ret = 0;
            ret = o1.getDeviceType().compareTo(o2.getDeviceType());
            if (ret == 0) {
                ret = o1.getDeviceDisplayName().compareTo(o2.getDeviceDisplayName());
            }
            return ret;
        }
    });
    property.setNodeCpuInfo(cpuList);

    property.setNodeMemoryInfo(new ArrayList<NodeMemoryInfo>());

    m_log.debug("device search " + property.toString());
    return property;
}

From source file:net.decix.jatlasx.ripe.atlas.api.handler.ProbeListHandler.java

public List<Probe> handleResponse(String jsonString) {

    List<Probe> probes = new ArrayList<Probe>();

    JSONObject jsonObj = new JSONObject(jsonString);
    JSONArray probeListArray = (JSONArray) jsonObj.get("objects");

    for (int i = 0; i < probeListArray.length(); i++) {
        JSONObject probeObj = (JSONObject) probeListArray.get(i);
        // a probe has to have an IPv4 address
        if (!probeObj.get(ApiKeys.ipv4).equals(null)) {
            String ipAddress = String.valueOf(probeObj.get(ApiKeys.ipv4));
            Long id = (Long) probeObj.getLong(ApiKeys.id);
            boolean isPublic = (Boolean) probeObj.get(ApiKeys.isPublic);
            Long asNum = 0L;//ww  w.j a v  a 2  s. c o  m
            if (!probeObj.get(ApiKeys.asn).equals(null)) {
                asNum = (Long) probeObj.getLong(ApiKeys.asn);
            } else {
                // Ignore probe if asNum is not specified
                continue;
            }

            String status = (String) probeObj.get(ApiKeys.status);
            // only select probes which provide an IPv4 address
            if (ipAddress != null && asn == asNum && status.equals("Connected") && isPublic) {
                Probe newProbe = new Probe(ApiKeys.probes, id, 1);
                newProbe.setAsn(asNum);
                try {
                    newProbe.setIpAddress(new IpAddress(ipAddress));
                } catch (UnknownHostException e) {
                    String errorMsg = "Could not create IP-address:" + ipAddress;
                    System.err.println(
                            e.getClass().getName() + ":" + errorMsg + "(" + this.getClass().getName() + ")");
                }
                probes.add(newProbe);
            }
        }
    }
    return probes;
}

From source file:org.zaproxy.zap.extension.ascanrules.BufferOverflow.java

@Override
public void scan(HttpMessage msg, String param, String value) {

    if (this.isStop()) { // Check if the user stopped things
        if (log.isDebugEnabled()) {
            log.debug("Scanner " + this.getName() + " Stopping.");
        }/*w  ww  .  ja v  a  2  s.  c  o m*/
        return; // Stop!
    }
    if (getBaseMsg().getResponseHeader().getStatusCode() == HttpStatusCode.INTERNAL_SERVER_ERROR) // Check to see if the page closed initially
    {
        return; // Stop
    }

    try {
        // This is where you change the 'good' request to attack the application
        // You can make multiple requests if needed
        String checkStringHeader1 = "Connection: close"; // Un natural close
        // Always use getNewMsg() for each new request
        msg = getNewMsg();
        String returnAttack = randomCharacterString(2100);
        setParameter(msg, param, returnAttack);
        try {
            sendAndReceive(msg);
        } catch (UnknownHostException ex) {
            if (log.isDebugEnabled())
                log.debug("Caught " + ex.getClass().getName() + " " + ex.getMessage() + " when accessing: "
                        + msg.getRequestHeader().getURI().toString()
                        + "\n The target may have replied with a poorly formed redirect due to our input.");
            return; // Something went wrong no point continuing
        }

        HttpResponseHeader requestReturn = msg.getResponseHeader();
        // This is where BASE baseResponseBody was you detect potential vulnerabilities in the
        // response
        String chkerrorheader = requestReturn.getHeadersAsString();
        log.debug("Header: " + chkerrorheader);
        if (msg.getResponseHeader().getStatusCode() == HttpStatusCode.INTERNAL_SERVER_ERROR
                && chkerrorheader.contains(checkStringHeader1)) {
            log.debug("Found Header");
            bingo(getRisk(), Alert.CONFIDENCE_MEDIUM, this.getBaseMsg().getRequestHeader().getURI().toString(),
                    param, msg.getRequestHeader().toString(), this.getOther(), msg);
            return;
        }

        return;
    } catch (URIException e) {
        if (log.isDebugEnabled()) {
            log.debug("Failed to send HTTP message, cause: " + e.getMessage());
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }
}

From source file:io.kamax.mxisd.lookup.strategy.RecursivePriorityLookupStrategy.java

private boolean isAllowedForRecursive(String source) {
    boolean canRecurse = false;

    try {//w  w  w.j a v a  2 s  .c  o  m
        if (cfg.isEnabled()) {
            log.debug("Checking {} CIDRs for recursion", allowedCidr.size());
            for (CIDRUtils cidr : allowedCidr) {
                if (cidr.isInRange(source)) {
                    log.debug("{} is in range {}, allowing recursion", source, cidr.getNetworkAddress());
                    canRecurse = true;
                    break;
                } else {
                    log.debug("{} is not in range {}", source, cidr.getNetworkAddress());
                }
            }
        }
    } catch (UnknownHostException e) {
        // this should never happened as we should have only IP ranges!
        log.error("Unexpected {} exception: {}", e.getClass().getSimpleName(), e.getMessage());
    }

    return canRecurse;
}

From source file:com.mirth.connect.connectors.tcp.TcpMessageReceiver.java

public void doConnect() throws ConnectException {
    disposing.set(false);//from   ww w.j a va 2s  .co m
    URI uri = endpoint.getEndpointURI().getUri();
    try {
        serverSocket = createSocket(uri);
        monitoringController.updateStatus(connector, connectorType, Event.INITIALIZED);
    } catch (UnknownHostException e) {
        logger.error(e.getClass().getName() + ": " + e.getMessage());
        throw new org.mule.providers.ConnectException(new Message("tcp", 1, uri), e, this);
    } catch (Exception e) {
        throw new org.mule.providers.ConnectException(new Message("tcp", 1, uri), e, this);
    }

    try {
        getWorkManager().scheduleWork(this, WorkManager.INDEFINITE, null, null);
    } catch (WorkException e) {
        throw new ConnectException(new Message(Messages.FAILED_TO_SCHEDULE_WORK), e, this);
    }
}

From source file:com.clustercontrol.winservice.util.RequestWinRM.java

/**
 * WinRM????Windows??Running??????/*from w  w  w  .j  a  v  a  2s  . co m*/
 * 
 * @param ipAddress
 * @param user
 * @param userPassword
 * @param port
 * @param protocol
 * @param timeout
 * @param retries
 * @return
 */
public boolean polling(String ipAddress, String user, String userPassword, int port, String protocol,
        int timeout, int retries) throws HinemosUnknown, WsmanException {
    m_log.debug("polling() " + "ipAddress = " + ipAddress + ",user = " + user + ",userPassword = "
            + userPassword + ",port = " + port + ",protocol = " + protocol + ",timeout = " + timeout
            + ",retries = " + retries);

    // XML?TransformerFactory?
    m_log.debug("polling() javax.xml.transform.TransformerFactory = "
            + System.getProperty("javax.xml.transform.TransformerFactory"));
    System.setProperty("javax.xml.transform.TransformerFactory",
            "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");

    // URL??
    try {
        InetAddress address = InetAddress.getByName(ipAddress);
        if (address instanceof Inet6Address) {
            m_url = protocol + "://[" + ipAddress + "]:" + port + "/wsman";
        } else {
            m_url = protocol + "://" + ipAddress + ":" + port + "/wsman";
        }
    } catch (UnknownHostException e) {
        m_log.info("polling() ipAddress is not valid : " + ipAddress + e.getClass().getSimpleName() + ", "
                + e.getMessage());
        throw new HinemosUnknown("ipAddress is not valid : " + ipAddress);
    }
    m_log.debug("polling() url = " + m_url);

    // ????
    m_con = WsmanConnection.createConnection(m_url);
    m_con.setAuthenticationScheme("basic");
    m_con.setUsername(user);
    m_con.setUserpassword(userPassword);
    m_con.setTimeout(timeout);

    boolean sslTrustall = HinemosPropertyUtil.getHinemosPropertyBool("monitor.winservice.ssl.trustall", true);
    if (sslTrustall) {
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            }
        };

        m_con.setTrustManager(tm);
        m_con.setHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    } else {
        // HTTP???? common-httpclient ? HostnameVerifier ?
        m_con.setHostnameVerifier(SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    }

    // URI?
    ManagedReference ref = m_con.newReference(URI_WIN32_SERVICE);
    ref.addSelector("Name", m_serviceName);

    // 
    int count = 0;
    WsmanException lastException = null;
    while (count < retries) {
        try {
            // 
            ManagedInstance inst = ref.get();
            if (m_log.isDebugEnabled()) {
                m_log.debug(WsmanUtils.getXML(inst));
            }

            // ??
            Object stateObj = inst.getProperty("State");
            if (stateObj != null) {
                m_state = stateObj.toString();
            } else {
                count++;
                continue;
            }

            // ?
            if (STATE_RUNNING.equalsIgnoreCase(m_state)) {

                // [OK]
                m_message = m_serviceName + " Service is " + STATE_RUNNING;
                m_messageOrg = m_serviceName + " Service is " + STATE_RUNNING;
                m_date = HinemosTime.currentTimeMillis();

                break;
            } else {
                // [NG]
                m_message = m_serviceName + " Service is not " + STATE_RUNNING;
                m_messageOrg = m_serviceName + " Service is another state : " + m_state;
                m_date = HinemosTime.currentTimeMillis();

                return false;
            }

        } catch (WsmanException e) {
            m_log.debug("polling() url=" + m_url + ", count=" + count + " " + e.getMessage() + ", "
                    + e.getReason());

            lastException = e; // ??
            count++;
            continue;

        } finally {

            if (m_con != null) {
                m_con = null;
            }
        }
    }

    // ???NG
    if (count == retries) {

        // ?
        m_message = "WinRM Access Error . ";
        m_messageOrg = "WinRM Access Error . ";
        if (lastException != null) {
            m_messageOrg = m_messageOrg + " : " + lastException.getMessage();
        }
        m_date = HinemosTime.currentTimeMillis();

        if (lastException != null) {
            m_log.info("winservice url=" + m_url + ", message=" + lastException.getMessage() + ", reason="
                    + lastException.getReason());
            if (lastException.getMessage() == null) {
                throw new HinemosUnknown(
                        MessageConstant.MESSAGE_WINSERVICE_NAME_NOT_EXIST_OR_NOT_REFERENCE_AUTHORITY_TO_WINRM
                                .getMessage() + " : " + lastException.getReason());
            } else {
                if (lastException.getMessage().indexOf("HTTP response code: 401") != -1) {
                    throw new HinemosUnknown(
                            MessageConstant.MESSAGE_FAIL_AT_WINRM_ID_OR_PASSWORD_OR_LOGINAUTH_ERR.getMessage());
                }
            }
            throw lastException;
        } else {
            // ??????????
            throw new HinemosUnknown("winservice unknown");
        }
    }

    // [OK]?????
    return true;
}

From source file:com.dagobert_engine.core.service.MtGoxApiAdapter.java

/**
 * Queries the mtgox api with params/*from   w  w  w. j  a  v  a  2s  . c  o  m*/
 * 
 * @param url
 * @return
 */
public String query(String path, HashMap<String, String> args) {

    final String publicKey = mtGoxConfig.getMtGoxPublicKey();
    final String privateKey = mtGoxConfig.getMtGoxPrivateKey();

    if (publicKey == null || privateKey == null || "".equals(publicKey) || "".equals(privateKey)) {
        throw new ApiKeysNotSetException(
                "Either public or private key of MtGox are not set. Please set them up in src/main/resources/META-INF/seam-beans.xml");
    }

    // Create nonce
    final String nonce = String.valueOf(System.currentTimeMillis()) + "000";

    HttpsURLConnection connection = null;
    String answer = null;
    try {
        // add nonce and build arg list
        args.put(ARG_KEY_NONCE, nonce);
        String post_data = buildQueryString(args);

        String hash_data = path + "\0" + post_data; // Should be correct

        // args signature with apache cryptografic tools
        String signature = signRequest(mtGoxConfig.getMtGoxPrivateKey(), hash_data);

        // build URL
        URL queryUrl = new URL(Constants.API_BASE_URL + path);
        // create and setup a HTTP connection
        connection = (HttpsURLConnection) queryUrl.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty(REQ_PROP_USER_AGENT, com.dagobert_engine.core.util.Constants.APP_NAME);
        connection.setRequestProperty(REQ_PROP_REST_KEY, mtGoxConfig.getMtGoxPublicKey());
        connection.setRequestProperty(REQ_PROP_REST_SIGN, signature.replaceAll("\n", ""));

        connection.setDoOutput(true);
        connection.setDoInput(true);

        // Read the response

        DataOutputStream os = new DataOutputStream(connection.getOutputStream());
        os.writeBytes(post_data);
        os.close();

        BufferedReader br = null;

        // Any error?
        int code = connection.getResponseCode();
        if (code >= 400) {
            // get error stream
            br = new BufferedReader(new InputStreamReader((connection.getErrorStream())));

            answer = toString(br);
            logger.severe("HTTP Error on queryin " + path + ": " + code + ", answer: " + answer);
            throw new MtGoxConnectionError(code, answer);

        } else {
            // get normal stream
            br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
            answer = toString(br);

        }
    } catch (UnknownHostException exc) {
        throw new MtGoxConnectionError("Could not connect to MtGox. Please check your internet connection. ("
                + exc.getClass().getName() + ")");
    } catch (IllegalStateException ex) {
        throw new MtGoxConnectionError(ex);
    } catch (IOException ex) {
        throw new MtGoxConnectionError(ex);
    } finally {

        if (connection != null)
            connection.disconnect();
        connection = null;
    }

    return answer;
}