Example usage for java.net UnknownHostException getMessage

List of usage examples for java.net UnknownHostException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.nridge.connector.ws.con_ws.restlet.RestletApplication.java

/**
 * Returns a Restlet instance used to identify inbound requests for the
 * web service endpoints.//from w w w . j  a  v  a2s .c  o m
 *
 * @return Restlet instance.
 */
@Override
public Restlet createInboundRoot() {
    Restlet restletRoot;
    Logger appLogger = mAppMgr.getLogger(this, "createInboundRoot");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Context restletContext = getContext();
    Router restletRouter = new Router(restletContext);

    String propertyName = "restlet.host_names";
    String hostNames = mAppMgr.getString(propertyName);
    if (StringUtils.isEmpty(hostNames)) {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();

            routerAttachEndPoints(restletRouter, "localhost");
            routerAttachEndPoints(restletRouter, inetAddress.getHostName());
            routerAttachEndPoints(restletRouter, inetAddress.getHostAddress());
            routerAttachEndPoints(restletRouter, inetAddress.getCanonicalHostName());
        } catch (UnknownHostException e) {
            appLogger.error(e.getMessage(), e);
            routerAttachEndPoints(restletRouter, "localhost");
        }
    } else {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] hostNameList = mAppMgr.getStringArray(propertyName);
            for (String hostName : hostNameList)
                routerAttachEndPoints(restletRouter, hostName);
        }
    }

    RestletFilter restletFilter = new RestletFilter(mAppMgr, restletContext);
    propertyName = "restlet.allow_addresses";
    String allowAddresses = mAppMgr.getString(propertyName);
    if (StringUtils.isNotEmpty(allowAddresses)) {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] allowAddressList = mAppMgr.getStringArray(propertyName);
            for (String allowAddress : allowAddressList) {
                restletFilter.add(allowAddress);
                appLogger.debug("Filter Allow Address: " + allowAddress);
            }
        } else {
            restletFilter.add(allowAddresses);
            appLogger.debug("Filter Allow Address: " + allowAddresses);
        }
        restletFilter.setNext(restletRouter);
        restletRoot = restletFilter;
    } else
        restletRoot = restletRouter;

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return restletRoot;
}

From source file:com.nridge.connector.fs.con_fs.restlet.RestletApplication.java

/**
 * Returns a Restlet instance used to identify inbound requests for the
 * web service endpoints.//  w w w .j  ava 2 s. c  o  m
 *
 * @return Restlet instance.
 */
@Override
public Restlet createInboundRoot() {
    Restlet restletRoot;
    Logger appLogger = mAppMgr.getLogger(this, "createInboundRoot");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    Context restletContext = getContext();
    Router restletRouter = new Router(restletContext);

    String propertyName = Constants.CFG_PROPERTY_PREFIX + ".restlet.host_names";
    String hostNames = mAppMgr.getString(propertyName);
    if (StringUtils.isEmpty(hostNames)) {
        try {
            InetAddress inetAddress = InetAddress.getLocalHost();

            routerAttachEndPoints(restletRouter, Constants.HOST_NAME_DEFAULT);
            routerAttachEndPoints(restletRouter, inetAddress.getHostName());
            routerAttachEndPoints(restletRouter, inetAddress.getHostAddress());
            routerAttachEndPoints(restletRouter, inetAddress.getCanonicalHostName());
        } catch (UnknownHostException e) {
            appLogger.error(e.getMessage(), e);
            routerAttachEndPoints(restletRouter, Constants.HOST_NAME_DEFAULT);
        }
    } else {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] hostNameList = mAppMgr.getStringArray(propertyName);
            for (String hostName : hostNameList)
                routerAttachEndPoints(restletRouter, hostName);
        } else
            routerAttachEndPoints(restletRouter, hostNames);
    }

    RestletFilter restletFilter = new RestletFilter(mAppMgr, restletContext);
    propertyName = Constants.CFG_PROPERTY_PREFIX + ".restlet.allow_addresses";
    String allowAddresses = mAppMgr.getString(propertyName);
    if (StringUtils.isNotEmpty(allowAddresses)) {
        if (mAppMgr.isPropertyMultiValue(propertyName)) {
            String[] allowAddressList = mAppMgr.getStringArray(propertyName);
            for (String allowAddress : allowAddressList) {
                restletFilter.add(allowAddress);
                appLogger.debug("Filter Allow Address: " + allowAddress);
            }
        } else {
            restletFilter.add(allowAddresses);
            appLogger.debug("Filter Allow Address: " + allowAddresses);
        }
        restletFilter.setNext(restletRouter);
        restletRoot = restletFilter;
    } else
        restletRoot = restletRouter;

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return restletRoot;
}

From source file:org.apache.hyracks.control.cc.cluster.NodeManager.java

private InetAddress getIpAddress(NodeControllerState ncState) throws HyracksException {
    String ipAddress = ncState.getNCConfig().getDataPublicAddress();
    try {//from  ww w . j  av a  2s . co m
        return InetAddress.getByName(ipAddress);
    } catch (UnknownHostException e) {
        throw HyracksException.create(ErrorCode.INVALID_NETWORK_ADDRESS, e, e.getMessage());
    }
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Performs a DNS lookup of a given name and type against a provided server
 * (or if no server is provided, the default system resolver).
 *
 * If an error occurs during the lookup, a <code>UtilityException</code> is
 * thrown containing the error response text.
 * /*  w w w .ja  va2 s  .co  m*/
 * @param resolverHost - The target host to use for resolution. Can be null, if not provided the
 * the default system resolver is used.
 * @param recordName - The DNS hostname/IP address to lookup.
 * @param recordType - The type of record to look up.
 * @param searchList - A search list to utilize if a short name is provided.
 * @return An ArrayList as output from the request
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized List<List<String>> executeDNSLookup(final String resolverHost,
        final String recordName, final String recordType, final String[] searchList) throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeDNSLookup(final String resolverHost, final String recordName, final String recordType, final String[] searchList) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("String: {}", resolverHost);
        DEBUGGER.debug("String: {}", recordName);
        DEBUGGER.debug("String: {}", recordType);
        DEBUGGER.debug("String: {}", (Object) searchList);
    }

    Lookup lookup = null;
    String responseName = null;
    String responseType = null;
    Record[] recordList = null;
    String responseAddress = null;
    SimpleResolver resolver = null;
    List<String> lookupData = null;
    List<List<String>> response = null;

    final String currentTimeout = Security.getProperty("networkaddress.cache.ttl");

    if (DEBUG) {
        DEBUGGER.debug("currentTimeout: {}", currentTimeout);
    }

    try {
        // no authorization required for service lookup
        Name name = Name.fromString(recordName);
        lookup = new Lookup(name, Type.value(recordType));

        if (DEBUG) {
            DEBUGGER.debug("Name: {}", name);
            DEBUGGER.debug("Lookup: {}", lookup);
        }

        if (StringUtils.isNotEmpty(resolverHost)) {
            resolver = new SimpleResolver(resolverHost);

            if (DEBUG) {
                DEBUGGER.debug("SimpleResolver: {}", resolver);
            }
        } else {
            resolver = new SimpleResolver();

            if (DEBUG) {
                DEBUGGER.debug("SimpleResolver: {}", resolver);
            }
        }

        lookup.setResolver(resolver);
        lookup.setCache(null);

        if (searchList != null) {
            lookup.setSearchPath(searchList);
        }

        if (DEBUG) {
            DEBUGGER.debug("Lookup: {}", lookup);
        }

        recordList = lookup.run();

        if (DEBUG) {
            if (recordList != null) {
                for (Record dRecord : recordList) {
                    DEBUGGER.debug("Record: {}", dRecord);
                }
            }
        }

        if (lookup.getResult() != Lookup.SUCCESSFUL) {
            throw new UtilityException("An error occurred during the lookup. The response obtained is: "
                    + lookup.getErrorString());
        }

        response = new ArrayList<List<String>>();

        if ((recordList == null) || (recordList.length == 0)) {
            throw new UtilityException("No results were found for the provided information.");
        }

        switch (recordList.length) {
        case 1:
            Record sRecord = recordList[0];

            if (DEBUG) {
                DEBUGGER.debug("Record: {}", sRecord);
            }

            responseAddress = sRecord.rdataToString();
            responseName = sRecord.getName().toString();
            responseType = Type.string(sRecord.getType());

            lookupData = new ArrayList<String>(Arrays.asList(responseAddress, responseName, responseType));
            if (DEBUG) {
                DEBUGGER.debug("responseAddress: {}", responseAddress);
                DEBUGGER.debug("responseName: {}", responseName);
                DEBUGGER.debug("responseType: {}", responseType);
            }

            response.add(lookupData);

            break;
        default:
            for (Record mRecord : recordList) {
                if (DEBUG) {
                    DEBUGGER.debug("Record: {}", mRecord);
                }

                responseAddress = mRecord.rdataToString();
                responseName = mRecord.getName().toString();
                responseType = Type.string(mRecord.getType());

                lookupData = new ArrayList<String>(Arrays.asList(responseAddress, responseName, responseType));
                if (DEBUG) {
                    DEBUGGER.debug("responseAddress: {}", responseAddress);
                    DEBUGGER.debug("responseName: {}", responseName);
                    DEBUGGER.debug("responseType: {}", responseType);
                }

                response.add(lookupData);

                if (DEBUG) {
                    DEBUGGER.debug("response: {}", response);
                }
            }

            break;
        }

        if (DEBUG) {
            DEBUGGER.debug("response: {}", response);
        }
    } catch (TextParseException tpx) {
        ERROR_RECORDER.error(tpx.getMessage(), tpx);

        throw new UtilityException(tpx.getMessage(), tpx);
    } catch (UnknownHostException uhx) {
        ERROR_RECORDER.error(uhx.getMessage(), uhx);

        throw new UtilityException(uhx.getMessage(), uhx);
    } finally {
        // reset java dns timeout
        try {
            Security.setProperty("networkaddress.cache.ttl", currentTimeout);
        } catch (NullPointerException npx) {
        }
    }

    return response;
}

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

/**
 *  ?????/*from   w w  w  . j  av a  2 s .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:io.fabric8.apiman.ApimanStarter.java

public static URL resolveServiceEndpoint(String scheme, String serviceName, String defaultPort) {
    URL endpoint = null;/* w  w  w  .  ja  v  a 2  s.  co m*/
    String host = null;
    String port = defaultPort;
    try {
        //lookup in the current namespace
        InetAddress initAddress = InetAddress.getByName(serviceName);
        host = initAddress.getCanonicalHostName();
        log.debug("Resolved host using DNS: " + host);
    } catch (UnknownHostException e) {
        log.debug("Could not resolve DNS for " + serviceName + ", trying ENV settings next.");
        host = KubernetesServices.serviceToHostOrBlank(serviceName);
        if ("".equals(host)) {
            return null;
        } else {
            log.debug("Resolved " + serviceName + " host using ENV: " + host);
        }
    }
    port = KubernetesServices.serviceToPortOrBlank(serviceName);
    if ("".equals(port)) {
        port = defaultPort;
        log.debug("Defaulting " + serviceName + " port to: " + port);
    } else {
        log.debug("Resolved " + serviceName + " port using ENV: " + port);
    }

    if (scheme == null) {
        if (port.endsWith("443"))
            scheme = "https";
        else
            scheme = "http";
    }
    try {
        endpoint = new URL(scheme, host, Integer.valueOf(port), "");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return endpoint;
}

From source file:org.csploit.android.net.Network.java

public boolean isInternal(String ip) {
    try {//from  w  ww.  j  a va  2s  . c  o m
        return isInternal(InetAddress.getByName(ip).getAddress());
    } catch (UnknownHostException e) {
        Logger.error(e.getMessage());
    }
    return false;
}

From source file:com.clustercontrol.infra.util.WinRs.java

public WinRs(String host, int port, String protocol, String username, String password) {
    this.username = username;
    this.password = password;

    try {//from  w  w w.  j  a  va2  s .co m
        if (InetAddress.getByName(host) instanceof Inet6Address) {
            if (!"https".equals(protocol)) {
                url = String.format("http://[%s]:%d/wsman", host, port);
            } else {
                url = String.format("https://[%s]:%d/wsman", host, port);
            }
        } else {
            if (!"https".equals(protocol)) {
                url = String.format("http://%s:%d/wsman", host, port);
            } else {
                url = String.format("https://%s:%d/wsman", host, port);
            }
        }
    } catch (UnknownHostException e) {
        m_log.warn("UnknownException " + e.getMessage(), e);
    }
}

From source file:org.jboss.as.test.integration.security.common.Utils.java

/**
 * Replace keystore paths and passwords variables in original configuration file with given values and set ${hostname}
 * variable from system property: node0//from  w  w  w.j a va2  s.c  o m
 *
 * @param originalFile String
 * @param keystoreFile File
 * @param trustStoreFile File
 * @param keystorePassword String
 * @param vaultConfig - path to vault settings
 * @return String content
 */
public static String propertiesReplacer(String originalFile, String keystoreFile, String trustStoreFile,
        String keystorePassword, String vaultConfig) {
    String hostname = getDefaultHost(false);

    // expand possible IPv6 address
    try {
        hostname = NetworkUtils.formatPossibleIpv6Address(InetAddress.getByName(hostname).getHostAddress());
    } catch (UnknownHostException ex) {
        String message = "Cannot resolve host address: " + hostname + " , error : " + ex.getMessage();
        LOGGER.error(message);
        throw new RuntimeException(ex);
    }

    final Map<String, String> map = new HashMap<String, String>();
    String content = "";
    if (vaultConfig == null) {
        map.put("vaultConfig", "");
    } else {
        map.put("vaultConfig", vaultConfig);
    }
    map.put("hostname", hostname);
    map.put("keystore", keystoreFile);
    map.put("truststore", trustStoreFile);
    map.put("password", keystorePassword);

    try {
        content = StrSubstitutor
                .replace(IOUtils.toString(CoreUtils.class.getResourceAsStream(originalFile), "UTF-8"), map);
    } catch (IOException ex) {
        String message = "Cannot find or modify configuration file " + originalFile + " , error : "
                + ex.getMessage();
        LOGGER.error(message);
        throw new RuntimeException(ex);
    }

    return content;
}

From source file:com.cws.esolutions.core.utils.NetworkUtils.java

/**
 * Creates an HTTP connection to a provided website and returns the data back
 * to the requestor.//from   w ww .  j a  v a 2s . co  m
 *
 * @param hostName - The fully qualified URL for the host desired. MUST be
 *     prefixed with http/https:// as necessary
 * @param methodType - GET or POST, depending on what is necessary
 * @return A object containing the response data
 * @throws UtilityException {@link com.cws.esolutions.core.utils.exception.UtilityException} if an error occurs processing
 */
public static final synchronized Object executeHttpConnection(final URL hostName, final String methodType)
        throws UtilityException {
    final String methodName = NetworkUtils.CNAME
            + "#executeHttpConnection(final URL hostName, final String methodType) throws UtilityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", hostName);
        DEBUGGER.debug("Value: {}", methodType);
    }

    RequestConfig requestConfig = null;
    CloseableHttpClient httpClient = null;
    CredentialsProvider credsProvider = null;
    CloseableHttpResponse httpResponse = null;

    final HttpClientParams httpParams = new HttpClientParams();
    final HTTPConfig httpConfig = appBean.getConfigData().getHttpConfig();
    final ProxyConfig proxyConfig = appBean.getConfigData().getProxyConfig();

    if (DEBUG) {
        DEBUGGER.debug("HttpClient: {}", httpClient);
        DEBUGGER.debug("HttpClientParams: {}", httpParams);
        DEBUGGER.debug("HTTPConfig: {}", httpConfig);
        DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
    }
    try {
        final URI requestURI = new URIBuilder().setScheme(hostName.getProtocol()).setHost(hostName.getHost())
                .setPort(hostName.getPort()).build();

        if (StringUtils.isNotEmpty(httpConfig.getTrustStoreFile())) {
            System.setProperty("javax.net.ssl.trustStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getTrustStoreType()) ? httpConfig.getTrustStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.trustStore", httpConfig.getTrustStoreFile());
            System.setProperty("javax.net.ssl.trustStorePassword",
                    PasswordUtils.decryptText(httpConfig.getTrustStorePass(), httpConfig.getTrustStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (StringUtils.isNotEmpty(httpConfig.getKeyStoreFile())) {
            System.setProperty("javax.net.ssl.keyStoreType",
                    (StringUtils.isNotEmpty(httpConfig.getKeyStoreType()) ? httpConfig.getKeyStoreType()
                            : "jks"));
            System.setProperty("javax.net.ssl.keyStore", httpConfig.getKeyStoreFile());
            System.setProperty("javax.net.ssl.keyStorePassword",
                    PasswordUtils.decryptText(httpConfig.getKeyStorePass(), httpConfig.getKeyStoreSalt(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getIterations(),
                            secBean.getConfigData().getSecurityConfig().getKeyBits(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                            secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                            appBean.getConfigData().getSystemConfig().getEncoding()));
        }

        if (proxyConfig.isProxyServiceRequired()) {
            if (DEBUG) {
                DEBUGGER.debug("ProxyConfig: {}", proxyConfig);
            }

            if (StringUtils.isEmpty(proxyConfig.getProxyServerName())) {
                throw new UtilityException(
                        "Configuration states proxy usage is required, but no proxy is configured.");
            }

            if (proxyConfig.isProxyAuthRequired()) {
                List<String> authList = new ArrayList<String>();
                authList.add(AuthPolicy.BASIC);
                authList.add(AuthPolicy.DIGEST);
                authList.add(AuthPolicy.NTLM);

                if (DEBUG) {
                    DEBUGGER.debug("authList: {}", authList);
                }

                requestConfig = RequestConfig.custom()
                        .setConnectionRequestTimeout(
                                (int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setConnectTimeout((int) TimeUnit.SECONDS.toMillis(httpConfig.getConnTimeout()))
                        .setContentCompressionEnabled(Boolean.TRUE)
                        .setProxy(new HttpHost(proxyConfig.getProxyServerName(),
                                proxyConfig.getProxyServerPort()))
                        .setProxyPreferredAuthSchemes(authList).build();

                if (DEBUG) {
                    DEBUGGER.debug("requestConfig: {}", requestConfig);
                }

                String proxyPwd = PasswordUtils.decryptText(proxyConfig.getProxyPassword(),
                        proxyConfig.getProxyPwdSalt(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getIterations(),
                        secBean.getConfigData().getSecurityConfig().getKeyBits(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionAlgorithm(),
                        secBean.getConfigData().getSecurityConfig().getEncryptionInstance(),
                        appBean.getConfigData().getSystemConfig().getEncoding());

                if (DEBUG) {
                    DEBUGGER.debug("proxyPwd: {}", proxyPwd);
                }

                if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_BASIC, proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new UsernamePasswordCredentials(proxyConfig.getProxyUserId(), proxyPwd));
                } else if (StringUtils.equals(NetworkUtils.PROXY_AUTH_TYPE_NTLM,
                        proxyConfig.getProxyAuthType())) {
                    credsProvider = new SystemDefaultCredentialsProvider();
                    credsProvider.setCredentials(
                            new AuthScope(proxyConfig.getProxyServerName(), proxyConfig.getProxyServerPort()),
                            new NTCredentials(proxyConfig.getProxyUserId(), proxyPwd,
                                    InetAddress.getLocalHost().getHostName(),
                                    proxyConfig.getProxyAuthDomain()));
                }

                if (DEBUG) {
                    DEBUGGER.debug("httpClient: {}", httpClient);
                }
            }
        }

        synchronized (new Object()) {
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

            if (StringUtils.equalsIgnoreCase(methodType, "POST")) {
                HttpPost httpMethod = new HttpPost(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            } else {
                HttpGet httpMethod = new HttpGet(requestURI);
                httpMethod.setConfig(requestConfig);

                httpResponse = httpClient.execute(httpMethod);
            }

            int responseCode = httpResponse.getStatusLine().getStatusCode();

            if (DEBUG) {
                DEBUGGER.debug("responseCode: {}", responseCode);
            }

            if (responseCode != 200) {
                ERROR_RECORDER.error("HTTP Response Code received NOT 200: " + responseCode);

                throw new UtilityException("HTTP Response Code received NOT 200: " + responseCode);
            }

            return httpResponse.getEntity().toString();
        }
    } catch (ConnectException cx) {
        throw new UtilityException(cx.getMessage(), cx);
    } catch (UnknownHostException ux) {
        throw new UtilityException(ux.getMessage(), ux);
    } catch (SocketException sx) {
        throw new UtilityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        throw new UtilityException(iox.getMessage(), iox);
    } catch (URISyntaxException usx) {
        throw new UtilityException(usx.getMessage(), usx);
    } finally {
        if (httpResponse != null) {
            try {
                httpResponse.close();
            } catch (IOException iox) {
            } // dont do anything with it
        }
    }
}