Example usage for com.google.common.net InetAddresses isInetAddress

List of usage examples for com.google.common.net InetAddresses isInetAddress

Introduction

In this page you can find the example usage for com.google.common.net InetAddresses isInetAddress.

Prototype

public static boolean isInetAddress(String ipString) 

Source Link

Document

Returns true if the supplied string is a valid IP string literal, false otherwise.

Usage

From source file:org.apache.stratos.cloud.controller.impl.CloudControllerServiceImpl.java

private boolean isValidIpAddress(String ip) {
    boolean isValid = InetAddresses.isInetAddress(ip);
    return isValid;
}

From source file:org.opendaylight.vpnservice.itm.impl.ItmUtils.java

public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
    final List<IpAddress> lstIpAddress = new ArrayList<>();
    if (StringUtils.isBlank(excludeIpFilter)) {
        return lstIpAddress;
    }/*  www.j a  v a 2  s  .  c  om*/
    final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
    for (String ip : arrIps) {
        if (StringUtils.countMatches(ip, "-") == 1) {
            final String[] arrIpRange = StringUtils.split(ip, '-');
            String strStartIp = StringUtils.trim(arrIpRange[0]);
            String strEndIp = StringUtils.trim(arrIpRange[1]);
            Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
                    new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strStartIp)
                            .toString());
            Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
                    new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(strEndIp)
                            .toString());
            Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
                    new StringBuilder("Invalid exclude IP filter: IP address [").append(strStartIp)
                            .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
            Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
                    new StringBuilder("Invalid exclude IP filter: IP address [").append(strEndIp)
                            .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
            int startIp = subnetInfo.asInteger(strStartIp);
            int endIp = subnetInfo.asInteger(strEndIp);

            Preconditions.checkArgument(startIp < endIp,
                    new StringBuilder("Invalid exclude IP filter: Invalid range [").append(ip).append("] ")
                            .toString());
            for (int i = startIp; i <= endIp; i++) {
                String ipAddress = ipFormat(toIpArray(i));
                validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
            }
        } else {
            validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
        }
    }
    return lstIpAddress;
}

From source file:org.apache.stratos.cloud.controller.iaases.openstack.networking.NeutronNetworkingApi.java

/**
 * Get all predefined all floating IPs defined in cartridge definition.
 *
 * @param array of {@link NetworkInterface}
 * @return list of predefined floating IPs
 *///w  w  w .  j  a v  a2 s.c  om
public List<String> getAllPredefinedFloatingIPs(NetworkInterface[] networkInterfaces) {
    String nwInterfacesNullMsg = "Input NetworkInterface array cannot be null";
    assertNotNull(networkInterfaces, nwInterfacesNullMsg);

    List<String> allPredefinedFloatingIPs = new ArrayList<String>();
    for (NetworkInterface networkInterface : networkInterfaces) {
        // if no floating networks defined, skip it
        if (null == networkInterface.getFloatingNetworks()) {
            continue;
        }
        FloatingNetwork[] floatingNetworks = networkInterface.getFloatingNetworks().getFloatingNetworks();
        if (floatingNetworks == null || floatingNetworks.length == 0) {
            continue;
        }

        for (FloatingNetwork floatingNetwork : floatingNetworks) {
            String floatingIP = floatingNetwork.getFloatingIP();
            // we are giving more priority to network uuid over fixed floating IPs
            // so if both network uuid and floating IPs defined, we are not going to assign those floating IPs
            // so these can be assigned to some other interfaces
            // hence excluding from predefined floating IPs list
            String networkUuid = floatingNetwork.getNetworkUuid();
            if (networkUuid == null || networkUuid.isEmpty()) {
                if (floatingIP != null && InetAddresses.isInetAddress(floatingIP)) {
                    allPredefinedFloatingIPs.add(floatingIP);
                }
            }
        }
    }
    return allPredefinedFloatingIPs;
}

From source file:org.opendaylight.vpnservice.itm.impl.ItmUtils.java

private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
        String ipAddress) {//from  w ww  .j a va 2  s  . c o m
    String ip = StringUtils.trim(ipAddress);
    Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
            new StringBuilder("Invalid exclude IP filter: invalid IP address value ").append(ip).toString());
    Preconditions.checkArgument(subnetInfo.isInRange(ip),
            new StringBuilder("Invalid exclude IP filter: IP address [").append(ip)
                    .append("] not in subnet range ").append(subnetInfo.getCidrSignature()).toString());
    lstIpAddress.add(new IpAddress(ip.toCharArray()));
}

From source file:org.apache.hadoop.hdfs.DFSClient.java

/**
 * Return the socket addresses to use with each configured
 * local interface. Local interfaces may be specified by IP
 * address, IP address range using CIDR notation, interface
 * name (e.g. eth0) or sub-interface name (e.g. eth0:0).
 * The socket addresses consist of the IPs for the interfaces
 * and the ephemeral port (port 0). If an IP, IP range, or
 * interface name matches an interface with sub-interfaces
 * only the IP of the interface is used. Sub-interfaces can
 * be used by specifying them explicitly (by IP or name).
 * //from www.ja  v a2  s. com
 * @return SocketAddresses for the configured local interfaces,
 *    or an empty array if none are configured
 * @throws UnknownHostException if a given interface name is invalid
 */
private static SocketAddress[] getLocalInterfaceAddrs(String interfaceNames[]) throws UnknownHostException {
    List<SocketAddress> localAddrs = new ArrayList<SocketAddress>();
    for (String interfaceName : interfaceNames) {
        if (InetAddresses.isInetAddress(interfaceName)) {
            localAddrs.add(new InetSocketAddress(interfaceName, 0));
        } else if (NetUtils.isValidSubnet(interfaceName)) {
            for (InetAddress addr : NetUtils.getIPs(interfaceName, false)) {
                localAddrs.add(new InetSocketAddress(addr, 0));
            }
        } else {
            for (String ip : DNS.getIPs(interfaceName, false)) {
                localAddrs.add(new InetSocketAddress(ip, 0));
            }
        }
    }
    return localAddrs.toArray(new SocketAddress[localAddrs.size()]);
}

From source file:net.yacy.grid.tools.Domains.java

/**
 * resolve a host address using a local DNS cache and a DNS lookup if necessary
 * @param clienthost/*  ww  w .j  a v a 2 s.c  o m*/
 * @return the hosts InetAddress or null if the address cannot be resolved
 */
public static InetAddress dnsResolve(final String host0) {
    // consider to call stripToHostName() before calling this
    if (host0 == null || host0.isEmpty())
        return null;
    final String host = host0.toLowerCase().trim();

    if (host0.endsWith(".yacyh")) {
        // that should not happen here
        return null;
    }

    // try to resolve host by doing a name cache lookup
    InetAddress ip = NAME_CACHE_HIT.get(host);
    if (ip != null) {
        //System.out.println("DNSLOOKUP-CACHE-HIT(CONC) " + host);
        cacheHit_Hit++;
        return ip;
    }
    cacheHit_Miss++;
    if (NAME_CACHE_MISS.containsKey(host)) {
        //System.out.println("DNSLOOKUP-CACHE-MISS(CONC) " + host);
        cacheMiss_Hit++;
        return null;
    }
    cacheMiss_Miss++;

    // call dnsResolveNetBased(host) using concurrency to interrupt execution in case of a time-out
    final Object sync_obj_new = new Object();
    Object sync_obj = LOOKUP_SYNC.putIfAbsent(host, sync_obj_new);
    if (sync_obj == null)
        sync_obj = sync_obj_new;
    synchronized (sync_obj) {
        // now look again if the host is in the cache where it may be meanwhile because of the synchronization

        ip = NAME_CACHE_HIT.get(host);
        if (ip != null) {
            //System.out.println("DNSLOOKUP-CACHE-HIT(SYNC) " + host);
            LOOKUP_SYNC.remove(host);
            cacheHit_Hit++;
            return ip;
        }
        cacheHit_Miss++;
        if (NAME_CACHE_MISS.containsKey(host)) {
            //System.out.println("DNSLOOKUP-CACHE-MISS(SYNC) " + host);
            LOOKUP_SYNC.remove(host);
            cacheMiss_Hit++;
            return null;
        }
        cacheMiss_Miss++;

        // do the dns lookup on the dns server
        //if (!matchesList(host, nameCacheNoCachingPatterns)) System.out.println("DNSLOOKUP " + host);
        try {
            //final long t = System.currentTimeMillis();
            String oldName = Thread.currentThread().getName();
            Thread.currentThread().setName("Domains: DNS resolve of '" + host + "'"); // thread dump show which host is resolved
            if (InetAddresses.isInetAddress(host)) {
                try {
                    ip = InetAddresses.forString(host);
                } catch (final IllegalArgumentException e) {
                    ip = null;
                }
            }
            Thread.currentThread().setName(oldName);
            if (ip == null)
                try {
                    ip = InetAddress.getByName(host);
                    //ip = TimeoutRequest.getByName(host, 1000); // this makes the DNS request to backbone
                } catch (final UncheckedTimeoutException e) {
                    // in case of a timeout - maybe cause of massive requests - do not fill NAME_CACHE_MISS
                    LOOKUP_SYNC.remove(host);
                    return null;
                }
            //.out.println("DNSLOOKUP-*LOOKUP* " + host + ", time = " + (System.currentTimeMillis() - t) + "ms");
        } catch (final Throwable e) {
            // add new entries
            NAME_CACHE_MISS.insertIfAbsent(host, PRESENT);
            cacheMiss_Insert++;
            LOOKUP_SYNC.remove(host);
            return null;
        }

        if (ip == null) {
            // add new entries
            NAME_CACHE_MISS.insertIfAbsent(host, PRESENT);
            cacheMiss_Insert++;
            LOOKUP_SYNC.remove(host);
            return null;
        }

        if (!ip.isLoopbackAddress() && !matchesList(host, nameCacheNoCachingPatterns)) {
            // add new ip cache entries
            NAME_CACHE_HIT.insertIfAbsent(host, ip);
            cacheHit_Insert++;

            // add also the isLocal host name caches
            final boolean localp = ip.isAnyLocalAddress() || ip.isLinkLocalAddress() || ip.isSiteLocalAddress();
            if (!localp) {
                if (globalHosts != null)
                    try {
                        globalHosts.add(host);
                    } catch (final IOException e) {
                    }
            }
        }
        LOOKUP_SYNC.remove(host);
        return ip;
    }
}

From source file:org.opendaylight.genius.itm.impl.ItmUtils.java

public static List<IpAddress> getExcludeIpAddresses(String excludeIpFilter, SubnetInfo subnetInfo) {
    final List<IpAddress> lstIpAddress = new ArrayList<>();
    if (StringUtils.isBlank(excludeIpFilter)) {
        return lstIpAddress;
    }/* w ww.ja  va2s  .co m*/
    final String[] arrIps = StringUtils.split(excludeIpFilter, ',');
    for (String ip : arrIps) {
        if (StringUtils.countMatches(ip, "-") == 1) {
            final String[] arrIpRange = StringUtils.split(ip, '-');
            String strStartIp = StringUtils.trim(arrIpRange[0]);
            String strEndIp = StringUtils.trim(arrIpRange[1]);
            Preconditions.checkArgument(InetAddresses.isInetAddress(strStartIp),
                    "Invalid exclude IP filter: invalid IP address value " + strStartIp);
            Preconditions.checkArgument(InetAddresses.isInetAddress(strEndIp),
                    "Invalid exclude IP filter: invalid IP address value " + strEndIp);
            Preconditions.checkArgument(subnetInfo.isInRange(strStartIp),
                    "Invalid exclude IP filter: IP address [" + strStartIp + "] not in subnet range "
                            + subnetInfo.getCidrSignature());
            Preconditions.checkArgument(subnetInfo.isInRange(strEndIp),
                    "Invalid exclude IP filter: IP address [" + strEndIp + "] not in subnet range "
                            + subnetInfo.getCidrSignature());
            int startIp = subnetInfo.asInteger(strStartIp);
            int endIp = subnetInfo.asInteger(strEndIp);

            Preconditions.checkArgument(startIp < endIp,
                    "Invalid exclude IP filter: Invalid range [" + ip + "] ");
            for (int iter = startIp; iter <= endIp; iter++) {
                String ipAddress = ipFormat(toIpArray(iter));
                validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ipAddress);
            }
        } else {
            validateAndAddIpAddressToList(subnetInfo, lstIpAddress, ip);
        }
    }
    return lstIpAddress;
}

From source file:org.opendaylight.genius.itm.impl.ItmUtils.java

private static void validateAndAddIpAddressToList(SubnetInfo subnetInfo, final List<IpAddress> lstIpAddress,
        String ipAddress) {/*  ww  w. j  av a 2  s. co  m*/
    String ip = StringUtils.trim(ipAddress);
    Preconditions.checkArgument(InetAddresses.isInetAddress(ip),
            "Invalid exclude IP filter: invalid IP address value " + ip);
    Preconditions.checkArgument(subnetInfo.isInRange(ip), "Invalid exclude IP filter: IP address [" + ip
            + "] not in subnet range " + subnetInfo.getCidrSignature());
    lstIpAddress.add(new IpAddress(ip.toCharArray()));
}

From source file:org.apache.hadoop.hdfs.server.blockmanagement.DatanodeManager.java

/**
 * Parse a DatanodeID from a hosts file entry
 *
 * @param hostLine/* w  ww.j a  v  a2 s . co m*/
 *     of form [hostname|ip][:port]?
 * @return DatanodeID constructed from the given string
 */
private DatanodeID parseDNFromHostsEntry(String hostLine) {
    DatanodeID dnId;
    String hostStr;
    int port;
    int idx = hostLine.indexOf(':');

    if (-1 == idx) {
        hostStr = hostLine;
        port = DFSConfigKeys.DFS_DATANODE_DEFAULT_PORT;
    } else {
        hostStr = hostLine.substring(0, idx);
        port = Integer.valueOf(hostLine.substring(idx + 1));
    }

    if (InetAddresses.isInetAddress(hostStr)) {
        // The IP:port is sufficient for listing in a report
        dnId = new DatanodeID(hostStr, "", "", port, DFSConfigKeys.DFS_DATANODE_HTTP_DEFAULT_PORT,
                DFSConfigKeys.DFS_DATANODE_HTTPS_DEFAULT_PORT, DFSConfigKeys.DFS_DATANODE_IPC_DEFAULT_PORT);
    } else {
        String ipAddr = "";
        try {
            ipAddr = InetAddress.getByName(hostStr).getHostAddress();
        } catch (UnknownHostException e) {
            LOG.warn("Invalid hostname " + hostStr + " in hosts file");
        }
        dnId = new DatanodeID(ipAddr, hostStr, "", port, DFSConfigKeys.DFS_DATANODE_HTTP_DEFAULT_PORT,
                DFSConfigKeys.DFS_DATANODE_HTTPS_DEFAULT_PORT, DFSConfigKeys.DFS_DATANODE_IPC_DEFAULT_PORT);
    }
    return dnId;
}

From source file:net.yacy.cora.protocol.Domains.java

/**
 * resolve a host address using a local DNS cache and a DNS lookup if necessary
 * @param clienthost/*from ww  w.  j a  v a2  s  .  c o  m*/
 * @return the hosts InetAddress or null if the address cannot be resolved
 */
public static InetAddress dnsResolve(final String host0) {
    // consider to call stripToHostName() before calling this
    if (host0 == null || host0.isEmpty())
        return null;
    final String host = host0.toLowerCase().trim();

    if (MemoryControl.shortStatus()) {
        NAME_CACHE_HIT.clear();
        NAME_CACHE_MISS.clear();
    }

    if (host0.endsWith(".yacyh")) {
        // that should not happen here
        return null;
    }

    // try to resolve host by doing a name cache lookup
    InetAddress ip = NAME_CACHE_HIT.get(host);
    if (ip != null) {
        //System.out.println("DNSLOOKUP-CACHE-HIT(CONC) " + host);
        cacheHit_Hit++;
        return ip;
    }
    cacheHit_Miss++;
    if (NAME_CACHE_MISS.containsKey(host)) {
        //System.out.println("DNSLOOKUP-CACHE-MISS(CONC) " + host);
        cacheMiss_Hit++;
        return null;
    }
    cacheMiss_Miss++;

    // call dnsResolveNetBased(host) using concurrency to interrupt execution in case of a time-out
    final Object sync_obj_new = new Object();
    Object sync_obj = LOOKUP_SYNC.putIfAbsent(host, sync_obj_new);
    if (sync_obj == null)
        sync_obj = sync_obj_new;
    synchronized (sync_obj) {
        // now look again if the host is in the cache where it may be meanwhile because of the synchronization

        ip = NAME_CACHE_HIT.get(host);
        if (ip != null) {
            //System.out.println("DNSLOOKUP-CACHE-HIT(SYNC) " + host);
            LOOKUP_SYNC.remove(host);
            cacheHit_Hit++;
            return ip;
        }
        cacheHit_Miss++;
        if (NAME_CACHE_MISS.containsKey(host)) {
            //System.out.println("DNSLOOKUP-CACHE-MISS(SYNC) " + host);
            LOOKUP_SYNC.remove(host);
            cacheMiss_Hit++;
            return null;
        }
        cacheMiss_Miss++;

        // do the dns lookup on the dns server
        //if (!matchesList(host, nameCacheNoCachingPatterns)) System.out.println("DNSLOOKUP " + host);
        try {
            //final long t = System.currentTimeMillis();
            String oldName = Thread.currentThread().getName();
            Thread.currentThread().setName("Domains: DNS resolve of '" + host + "'"); // thread dump show which host is resolved
            if (InetAddresses.isInetAddress(host)) {
                try {
                    ip = InetAddresses.forString(host);
                    log.info("using guava for host resolution:" + host);
                } catch (final IllegalArgumentException e) {
                    ip = null;
                }
            }
            Thread.currentThread().setName(oldName);
            if (ip == null)
                try {
                    ip = timeLimiter.callWithTimeout(new Callable<InetAddress>() {
                        @Override
                        public InetAddress call() throws Exception {
                            return InetAddress.getByName(host);
                        }
                    }, 3000L, TimeUnit.MILLISECONDS, false);
                    //ip = TimeoutRequest.getByName(host, 1000); // this makes the DNS request to backbone
                } catch (final UncheckedTimeoutException e) {
                    // in case of a timeout - maybe cause of massive requests - do not fill NAME_CACHE_MISS
                    LOOKUP_SYNC.remove(host);
                    return null;
                }
            //.out.println("DNSLOOKUP-*LOOKUP* " + host + ", time = " + (System.currentTimeMillis() - t) + "ms");
        } catch (final Throwable e) {
            // add new entries
            NAME_CACHE_MISS.insertIfAbsent(host, PRESENT);
            cacheMiss_Insert++;
            LOOKUP_SYNC.remove(host);
            return null;
        }

        if (ip == null) {
            // add new entries
            NAME_CACHE_MISS.insertIfAbsent(host, PRESENT);
            cacheMiss_Insert++;
            LOOKUP_SYNC.remove(host);
            return null;
        }

        if (!ip.isLoopbackAddress() && !matchesList(host, nameCacheNoCachingPatterns)) {
            // add new ip cache entries
            NAME_CACHE_HIT.insertIfAbsent(host, ip);
            cacheHit_Insert++;

            // add also the isLocal host name caches
            final boolean localp = ip.isAnyLocalAddress() || ip.isLinkLocalAddress() || ip.isSiteLocalAddress();
            if (!localp) {
                if (globalHosts != null)
                    try {
                        globalHosts.add(host);
                    } catch (final IOException e) {
                    }
            }
        }
        LOOKUP_SYNC.remove(host);
        return ip;
    }
}