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.opennaas.extensions.router.junos.commandsets.digester.RoutingOptionsParser.java

public void setNextHop(String nextHop) {

    NextHopIPRoute nextHopIPRoute = (NextHopIPRoute) peek(0);
    // ***************************
    // Next hop is an IP address *
    // ***************************
    // creating IpEndPoint that will be the next hop
    IPProtocolEndpoint ipNextHop = new IPProtocolEndpoint();
    if (InetAddresses.isInetAddress(nextHop)) {
        if (IPUtilsHelper.validateIpAddressPattern(nextHop)) {
            ipNextHop.setProtocolIFType(ProtocolIFType.IPV4);
            ipNextHop.setIPv4Address(nextHop);
        } else {/*  www  .j a v  a 2 s .  co m*/
            ipNextHop.setProtocolIFType(ProtocolIFType.IPV6);
            ipNextHop.setIPv6Address(nextHop);
        }
    } else {
        // not an IP address, it must be an interface.unit
        addInterface(nextHop);
        return;
    }
    try {
        // adding association to IPProtocolEndpoint
        nextHopIPRoute.setProtocolEndpoint(ipNextHop);
    } catch (Exception e) {
        log.error(e.getMessage());
    }
}

From source file:com.lambdaworks.redis.resource.DirContextDnsResolver.java

/**
 * Perform hostname to address resolution.
 * //from w  w  w  .j  av  a 2s.  c om
 * @param host the hostname, must not be empty or {@literal null}.
 * @return array of one or more {@link InetAddress adresses}
 * @throws UnknownHostException
 */
@Override
public InetAddress[] resolve(String host) throws UnknownHostException {

    if (InetAddresses.isInetAddress(host)) {
        return new InetAddress[] { InetAddresses.forString(host) };
    }

    List<InetAddress> inetAddresses = new ArrayList<>();
    try {
        resolve(host, inetAddresses);
    } catch (NamingException e) {
        throw new UnknownHostException(String.format("Cannot resolve %s to a hostname because of %s", host, e));
    }

    if (inetAddresses.isEmpty()) {
        throw new UnknownHostException(String.format("Cannot resolve %s to a hostname", host));
    }

    return inetAddresses.toArray(new InetAddress[inetAddresses.size()]);
}

From source file:org.ngrinder.infra.config.DynamicCacheConfig.java

protected String createCacheProperties(List<String> replicatedCacheNames) {
    int clusterListenerPort = getCacheListenerPort();
    // rmiUrls=//10.34.223.148:40003/distributed_map|//10.34.63.28:40003/distributed_map
    List<String> uris = new ArrayList<String>();
    String currentIP = config.getCurrentIP();
    String current = currentIP + ":" + getCacheListenerPort();
    for (String ip : config.getClusterURIs()) {
        if (ip.equals(current)) {
            continue;
        }/*from w  ww.  ja v a  2s.co  m*/
        // Verify it's ip.
        String[] split = StringUtils.split(ip, ":");
        ip = split[0];
        int port = (split.length >= 2) ? NumberUtils.toInt(split[1], clusterListenerPort) : clusterListenerPort;
        if (!InetAddresses.isInetAddress(ip)) {
            try {
                ip = InetAddress.getByName(ip).getHostAddress();
            } catch (UnknownHostException e) {
                CoreLogger.LOGGER.error("{} is not valid ip or host name", ip);
                continue;
            }
        }

        for (String cacheName : replicatedCacheNames) {
            uris.add(String.format("//%s:%d/%s", ip, port, cacheName));
        }
    }
    return "peerDiscovery=manual,rmiUrls=" + StringUtils.join(uris, "|");
}

From source file:net.lethargiclion.informaban.InformaBanCommandExecutor.java

/**
 * Handles the /ipban command.//from   w  w w  .j  a  v a2s  .  c  o  m
 * 
 * @param sender
 *            The CommandSender executing this command.
 * @param args
 *            The command arguments.
 * @return False if a usage message should be displayed.
 */
private boolean commandIPBan(CommandSender sender, String[] args) {

    if (args.length == 1)
        sender.sendMessage(plugin.messages.getString("command.ban.reasonRequired"));

    String subject = null, ip = null;
    UUID uuid = null;

    if (args.length > 1) {
        if (InetAddresses.isInetAddress(args[0])) {
            ip = subject = args[0];
        } else {
            // Assume it is a player name and try to get their IP address
            Player p = sender.getServer().getPlayer(args[0]);
            subject = p.getName();
            uuid = p.getUniqueId();
            ip = p.getAddress().getAddress().getHostAddress();
        }

        // Check for existing IP ban
        if (Bukkit.getIPBans().contains(subject)) {
            sender.sendMessage(plugin.messages.getString("error.IPAlreadyBanned"));
            return true;
        }

        if (subject != null) {
            // Set up ban message
            String banReason = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), ' ');

            // Log ban to console
            plugin.getLogger().info(MessageFormat.format(plugin.messages.getString("command.ban.consoleLog"),
                    new Object[] { sender.getName(), subject }));

            // Do the ban and record it
            IPBan b = new IPBan();
            b.apply(plugin.messages, uuid, subject, sender, banReason, Ban.PERMANENT);
            b.setSubjectIP(ip);
            plugin.getDatabase().insert(b); // Record the banning event
            plugin.getDatabase().insert(b.makeActiveEvent()); // Set the actual ban
        } else
            sender.sendMessage(plugin.messages.getString("error.playerNotFound"));
        return true;
    }
    return false;
}

From source file:crossbear.messaging.Message.java

/**
 * Check if a String implements either a valid IPv4-Address or a valid IPv6-Address
 * /*from   w w w. j a  v  a  2  s .c o m*/
 * @param stringToCheck The string to check
 * @return True if stringToCheck is either a valid IPv4-Address or a valid IPv6-Address else false
 */
public static boolean isValidIPAddress(String stringToCheck) {
    return InetAddresses.isInetAddress(stringToCheck);
}

From source file:org.apache.stratos.autoscaler.kubernetes.KubernetesManager.java

private void validateKubernetesHost(KubernetesHost kubernetesHost) throws InvalidKubernetesHostException {
    if (kubernetesHost == null) {
        throw new InvalidKubernetesHostException("Kubernetes host can not be null");
    }//from w w  w.j  a v a 2s . co m
    if (StringUtils.isEmpty(kubernetesHost.getHostId())) {
        throw new InvalidKubernetesHostException("Kubernetes host id can not be empty");
    }
    if (kubernetesHost.getHostIpAddress() == null) {
        throw new InvalidKubernetesHostException("Mandatory field Kubernetes host IP address has not been set "
                + "for [hostId] " + kubernetesHost.getHostId());
    }
    if (!InetAddresses.isInetAddress(kubernetesHost.getHostIpAddress())) {
        throw new InvalidKubernetesHostException(
                "Kubernetes host ip address is invalid: " + kubernetesHost.getHostIpAddress());
    }
}

From source file:controllers.Setup.java

/**
 * Tests the SMTP settings from the initial setup form, rendering the result as JSON.
 * //  w  w w.  j a va2 s. c o  m
 * @param setup
 *            the initial setup form.
 */
@Restrictions({ @Restrict({ "SYSTEM_ADMIN", "SECURITY_ADMIN" }),
        @Restrict({ "RESTRICTED_SYSTEM_ADMIN", "RESTRICTED_SECURITY_ADMIN" }) })
public static void testSmtpSettings(SetupForm setup) {
    setup.validateSmtp();
    Validation.required("setup.smtpTo", setup.smtpTo);
    Validation.email("setup.smtpTo", setup.smtpTo);
    if (Validation.hasErrors()) {
        renderJSON(ValidationResponse.collectErrors());
    }

    MailSettingsValidator.Settings settings = new MailSettingsValidator.Settings();

    if (StringUtils.isNotEmpty(setup.nameservers) && !InetAddresses.isInetAddress(setup.smtpServer)) {
        Set<String> ips = Sets.newHashSet(setup.nameservers.split(","));

        try {
            settings.server = DnsUtils.getHostIpAddress(ips, setup.smtpServer).getHostAddress();
        } catch (ViPRException e) {
            renderJSON(ValidationResponse.invalid(e.getMessage()));
        }
    } else {
        settings.server = setup.smtpServer;
    }
    settings.port = ConfigProperties.getPort(setup.smtpPort, setup.smtpEnableTls);
    settings.username = setup.smtpUsername;
    settings.password = PasswordUtil.decryptedValue(setup.smtpPassword);
    settings.channel = StringUtils.equals("yes", setup.smtpEnableTls) ? "starttls" : "clear";
    settings.authType = setup.smtpAuthType;
    settings.fromAddress = setup.smtpFrom;

    try {
        MailSettingsValidator.validate(settings, setup.smtpTo);
    } catch (RuntimeException e) {
        Logger.error(e, "Failed to send email");
        Validation.addError(null, "setup.testEmail.failure", e.getMessage());
        if (StringUtils.isEmpty(setup.nameservers)) {
            Validation.addError(null, "setup.smtpServer.invalidEmptyNameserver");
        }
    }

    if (Validation.hasErrors()) {
        renderJSON(ValidationResponse.collectErrors());
    } else {
        renderJSON(ValidationResponse.valid(MessagesUtils.get("setup.testEmail.success")));
    }
}

From source file:org.graylog2.configuration.HttpConfiguration.java

@ValidatorMethod
@SuppressWarnings("unused")
public void validateHttpBindAddress() throws ValidationException {
    try {/*from  w w w  .  ja  va 2s .  c o m*/
        final String host = getHttpBindAddress().getHost();
        if (!InetAddresses.isInetAddress(host)) {
            final InetAddress inetAddress = InetAddress.getByName(host);
        }
    } catch (IllegalArgumentException | UnknownHostException e) {
        throw new ValidationException(e);
    }
}

From source file:org.apache.hadoop.net.DNS.java

/**
 * Returns all the host names associated by the provided nameserver with the
 * address bound to the specified network interface
 *
 * @param strInterface//from   w ww.j a va 2s  .co m
 *            The name of the network interface or subinterface to query
 *            (e.g. eth0 or eth0:0)
 * @param nameserver
 *            The DNS host name
 * @param tryfallbackResolution
 *            if true and if reverse DNS resolution fails then attempt to
 *            resolve the hostname with
 *            {@link InetAddress#getCanonicalHostName()} which includes
 *            hosts file resolution.
 * @return A string vector of all host names associated with the IPs tied to
 *         the specified interface
 * @throws UnknownHostException if the given interface is invalid
 */
public static String[] getHosts(String strInterface, @Nullable String nameserver, boolean tryfallbackResolution)
        throws UnknownHostException {
    final List<String> hosts = new Vector<String>();
    final List<InetAddress> addresses = getIPsAsInetAddressList(strInterface, true);
    for (InetAddress address : addresses) {
        try {
            hosts.add(reverseDns(address, nameserver));
        } catch (NamingException ignored) {
        }
    }
    if (hosts.isEmpty() && tryfallbackResolution) {
        for (InetAddress address : addresses) {
            final String canonicalHostName = address.getCanonicalHostName();
            // Don't use the result if it looks like an IP address.
            if (!InetAddresses.isInetAddress(canonicalHostName)) {
                hosts.add(canonicalHostName);
            }
        }
    }

    if (hosts.isEmpty()) {
        LOG.warn("Unable to determine hostname for interface " + strInterface);
        hosts.add(cachedHostname);
    }
    return hosts.toArray(new String[hosts.size()]);
}

From source file:org.rhq.enterprise.server.cloud.StorageNodeManagerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.NEVER)
public void linkResource(Resource resource) {
    Configuration pluginConfig = configurationManager.getPluginConfiguration(resource.getId());
    String address = pluginConfig.getSimpleValue(RHQ_STORAGE_ADDRESS_PROPERTY);

    if (log.isInfoEnabled()) {
        log.info("Linking " + resource + " to storage node at " + address);
    }//  w  w  w. jav a2s.c  o m
    try {
        StorageNode storageNode = storageNodeManager.findStorageNodeByAddress(address);
        if (storageNode == null) {
            if (InetAddresses.isInetAddress(address)) {
                String hostName = InetAddresses.forString(address).getHostName();
                log.info("Did not find storage node with address [" + address + "]. Searching by hostname ["
                        + hostName + "]");
                storageNode = storageNodeManager.findStorageNodeByAddress(hostName);
            } else {
                String ipAddress = InetAddress.getByName(address).getHostAddress();
                log.info("Did not find storage node with address [" + address + "] Searching by IP address ["
                        + ipAddress + "]");
                storageNode = storageNodeManager.findStorageNodeByAddress(ipAddress);
            }
        }

        if (storageNode != null) {
            if (log.isInfoEnabled()) {
                log.info(storageNode + " is an existing storage node. No cluster maintenance is necessary.");
            }
            storageNode.setAddress(address);
            storageNode.setResource(resource);
            storageNode.setOperationMode(OperationMode.NORMAL);
            storageNodeManager.linkExistingStorageNodeToResource(storageNode);

        } else {
            StorageClusterSettings clusterSettings = storageClusterSettingsManager
                    .getClusterSettings(subjectManager.getOverlord());
            storageNode = storageNodeManager.createStorageNode(resource, clusterSettings);

            if (log.isInfoEnabled()) {
                log.info("Scheduling cluster maintenance to deploy " + storageNode
                        + " into the storage cluster...");
            }
            if (clusterSettings.getAutomaticDeployment()) {
                log.info("Deploying " + storageNode);
                storageNodeManager.deployStorageNode(subjectManager.getOverlord(), storageNode);
            } else {
                log.info("Automatic deployment is disabled. " + storageNode + " will not become part of the "
                        + "cluster until it is deployed.");
            }
        }
    } catch (UnknownHostException e) {
        throw new RuntimeException("Could not resolve address [" + address + "]. The resource " + resource
                + " cannot be linked to a storage node", e);
    }
}