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.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader.java

/**
 * Parse additional header from a formatted string
 *///w  w  w  .j a v  a  2 s.co  m
public static NetconfHelloMessageAdditionalHeader fromString(String additionalHeader) {
    String additionalHeaderTrimmed = additionalHeader.trim();
    Matcher matcher = PATTERN.matcher(additionalHeaderTrimmed);
    Matcher matcher2 = CUSTOM_HEADER_PATTERN.matcher(additionalHeaderTrimmed);
    Preconditions.checkArgument(matcher.matches(), "Additional header in wrong format %s, expected %s",
            additionalHeaderTrimmed, PATTERN);

    String username = matcher.group("username");
    String address = matcher.group("address");
    Preconditions.checkArgument(InetAddresses.isInetAddress(address));
    String port = matcher.group("port");
    String transport = matcher.group("transport");
    String sessionIdentifier = "client";
    if (matcher2.matches()) {
        sessionIdentifier = matcher2.group("sessionIdentifier");
    }
    return new NetconfHelloMessageAdditionalHeader(username, address, port, transport, sessionIdentifier);
}

From source file:org.apache.streams.elasticsearch.ElasticsearchClientManager.java

private synchronized void start() {

    try {//from  w ww. java2 s  .c om
        // We are currently using lazy loading to start the elasticsearch cluster, however.
        LOGGER.info("Creating a new TransportClient: {}", this.config.getHosts());

        Settings settings = Settings.settingsBuilder().put("cluster.name", this.config.getClusterName())
                .put("client.transport.ping_timeout", "90s")
                .put("client.transport.nodes_sampler_interval", "60s").build();

        // Create the client
        client = TransportClient.builder().settings(settings).build();
        for (String h : config.getHosts()) {
            LOGGER.info("Adding Host: {}", h);
            InetAddress address;

            if (InetAddresses.isInetAddress(h)) {
                LOGGER.info("{} is an IP address", h);
                address = InetAddresses.forString(h);
            } else {
                LOGGER.info("{} is a hostname", h);
                address = InetAddress.getByName(h);
            }
            client.addTransportAddress(new InetSocketTransportAddress(address, config.getPort().intValue()));
        }
    } catch (Exception ex) {
        LOGGER.error("Could not Create elasticsearch Transport Client: {}", ex);
    }

}

From source file:io.smartspaces.util.net.InetAddressFactory.java

/**
 * Creates an {@link InetAddress} with both an IP and a host set so that no
 * further resolving will take place./*from  w  ww . j a v a  2s.  com*/
 *
 * If an IP address string is specified, this method ensures that it will be
 * used in place of a host name.
 *
 * If a host name other than {@code Address.LOCALHOST} is specified, this
 * method trys to find a non-loopback IP associated with the supplied host
 * name.
 *
 * If the specified host name is {@code Address.LOCALHOST}, this method
 * returns a loopback address.
 *
 * @param host
 * @return an {@link InetAddress} with both an IP and a host set (no further
 *         resolving will take place)
 */
public static InetAddress newFromHostString(String host) {
    try {
        if (InetAddresses.isInetAddress(host)) {
            return InetAddress.getByAddress(host, InetAddresses.forString(host).getAddress());
        }
        if (host.equals(LOCALHOST)) {
            return InetAddress.getByAddress(LOCALHOST, InetAddresses.forString(LOOPBACK).getAddress());
        }
    } catch (UnknownHostException e) {
        throw new SmartSpacesException("Can't get new host from host name " + host, e);
    }
    Collection<InetAddress> allAddressesByName = getAllInetAddressesByName(host);
    // First, try to find a non-loopback IPv4 address.
    for (InetAddress address : allAddressesByName) {
        if (!address.isLoopbackAddress() && isIpv4(address)) {
            return address;
        }
    }
    // Return a loopback IPv4 address as a last resort.
    for (InetAddress address : allAddressesByName) {
        if (isIpv4(address)) {
            return address;
        }
    }
    throw new SmartSpacesException("Unable to construct InetAddress for host: " + host);
}

From source file:fr.evercraft.essentials.command.EESeen.java

@Override
public boolean execute(final CommandSource source, final List<String> args) throws CommandException {
    // Rsultat de la commande :
    boolean resultat = false;

    // Si on ne connait pas le joueur
    if (args.size() == 0) {

        // Si la source est un joueur
        if (source instanceof EPlayer) {
            resultat = this.commandSeen((EPlayer) source);
            // La source n'est pas un joueur
        } else {/*from   w  ww.  j a  v  a2 s  .  c  om*/
            EAMessages.COMMAND_ERROR_FOR_PLAYER.sender().prefix(EEMessages.PREFIX).sendTo(source);
        }

        // On connais le joueur
    } else if (args.size() == 1) {
        if (InetAddresses.isInetAddress(args.get(0))) {
            resultat = this.commandSeenOthers(source, args.get(0));
        } else {
            Optional<EUser> optUser = this.plugin.getEServer().getEUser(args.get(0));
            // Le joueur existe
            if (optUser.isPresent()) {
                resultat = this.commandSeenOthers(source, optUser.get());
                // Le joueur est introuvable
            } else {
                EAMessages.PLAYER_NOT_FOUND.sender().prefix(EEMessages.PREFIX).sendTo(source);
            }
        }

        // Nombre d'argument incorrect
    } else {
        source.sendMessage(this.help(source));
    }

    return resultat;
}

From source file:org.sonar.process.NetworkUtilsImpl.java

@Override
public InetAddress toInetAddress(String hostOrAddress) throws UnknownHostException {
    if (InetAddresses.isInetAddress(hostOrAddress)) {
        return InetAddresses.forString(hostOrAddress);
    }/*from   w  w w  . j av a  2 s.  c om*/
    return InetAddress.getByName(hostOrAddress);
}

From source file:org.apache.hadoop.util.StringUtils.java

/**
 * Given a full hostname, return the word upto the first dot.
 * @param fullHostname the full hostname
 * @return the hostname to the first dot
 *///from  w w w.  j av a  2  s.  com
public static String simpleHostname(String fullHostname) {
    if (InetAddresses.isInetAddress(fullHostname)) {
        return fullHostname;
    }
    int offset = fullHostname.indexOf('.');
    if (offset != -1) {
        return fullHostname.substring(0, offset);
    }
    return fullHostname;
}

From source file:org.dcache.http.HttpsTransferService.java

@Override
protected URI getUri(HttpProtocolInfo protocolInfo, int port, UUID uuid)
        throws SocketException, CacheException, URISyntaxException {

    URI plainUrl = super.getUri(protocolInfo, port, uuid);
    String host = getHost(plainUrl);
    try {// w w w  . j a  va  2s .  c om
        if (InetAddresses.isInetAddress(host)) {
            // An IP address is unlikely to be in the X.509 host credential.
            host = InetAddress.getByName(host).getCanonicalHostName();
        }
        if (InetAddresses.isInetAddress(host)) {
            LOGGER.warn("Unable to resolve IP address {} to a canonical name", host);
        }
    } catch (UnknownHostException e) {
        // This should not happen as getByName should never throw this
        // exception for a valid IP address
        LOGGER.warn("Unable to resolve IP address {}: {}", host, e.toString());
    }
    return new URI(PROTOCOL_HTTPS, plainUrl.getUserInfo(), host, plainUrl.getPort(), plainUrl.getPath(),
            plainUrl.getQuery(), plainUrl.getFragment());
}

From source file:org.opendaylight.groupbasedpolicy.renderer.opflex.Identity.java

private boolean idIsIp(String id) {
    return InetAddresses.isInetAddress(id);
}

From source file:org.jclouds.glesys.compute.options.GleSYSTemplateOptions.java

/**
 * Sets the IP address to assign to the new server instance. If set to "
 * <code>any</code>" the server will be automatically assigned a free IP
 * address.//from   w  w  w  . j a  va  2s  .c o m
 * 
 * @see ServerApi#createWithHostnameAndRootPassword
 * @see InetAddresses#isInetAddress
 */
public GleSYSTemplateOptions ip(String ip) {
    checkNotNull(ip);
    checkArgument("any".equals(ip) || InetAddresses.isInetAddress(ip), "ip %s is not valid", ip);
    this.ip = ip;
    return this;
}

From source file:org.apache.hadoop.hbase.ServerName.java

/**
 * @param hostname// w  ww.  j  a  v  a  2s  .com
 * @return hostname minus the domain, if there is one (will do pass-through on ip addresses)
 */
static String getHostNameMinusDomain(final String hostname) {
    if (InetAddresses.isInetAddress(hostname))
        return hostname;
    String[] parts = hostname.split("\\.");
    if (parts == null || parts.length == 0)
        return hostname;
    return parts[0];
}