Example usage for com.google.common.net HostAndPort getHostText

List of usage examples for com.google.common.net HostAndPort getHostText

Introduction

In this page you can find the example usage for com.google.common.net HostAndPort getHostText.

Prototype

public String getHostText() 

Source Link

Document

Returns the portion of this HostAndPort instance that should represent the hostname or IPv4/IPv6 literal.

Usage

From source file:org.apache.brooklyn.entity.nosql.mongodb.MongoDBClientSupport.java

/**
 * Creates a {@link MongoDBClientSupport} instance in standalone mode.
 *//*from  w  w  w  .  ja  v a  2  s  . c  om*/
public static MongoDBClientSupport forServer(AbstractMongoDBServer standalone) throws UnknownHostException {
    HostAndPort hostAndPort = BrooklynAccessUtils.getBrooklynAccessibleAddress(standalone,
            standalone.getAttribute(MongoDBServer.PORT));
    ServerAddress address = new ServerAddress(hostAndPort.getHostText(), hostAndPort.getPort());
    if (MongoDBAuthenticationUtils.usesAuthentication(standalone)) {
        return new MongoDBClientSupport(address,
                standalone.sensors().get(MongoDBAuthenticationMixins.ROOT_USERNAME),
                standalone.sensors().get(MongoDBAuthenticationMixins.ROOT_PASSWORD),
                standalone.sensors().get(MongoDBAuthenticationMixins.AUTHENTICATION_DATABASE));
    } else {
        return new MongoDBClientSupport(address);
    }
}

From source file:brooklyn.util.net.Networking.java

public static boolean isReachable(HostAndPort endpoint) {
    try {/*from   www.  j av  a2 s. co  m*/
        Socket s = new Socket(endpoint.getHostText(), endpoint.getPort());
        try {
            s.close();
        } catch (Exception e) {
            log.debug("Error closing socket, opened temporarily to check reachability to " + endpoint
                    + " (continuing)", e);
        }
        return true;
    } catch (Exception e) {
        if (log.isTraceEnabled())
            log.trace("Error reaching " + endpoint + " during reachability check (return false)", e);
        return false;
    }
}

From source file:org.apache.brooklyn.location.jclouds.JcloudsUtil.java

public static String getFirstReachableAddress(NodeMetadata node, Duration timeout) {
    final int port = node.getLoginPort();
    List<HostAndPort> sockets = FluentIterable
            .from(Iterables.concat(node.getPublicAddresses(), node.getPrivateAddresses()))
            .transform(new Function<String, HostAndPort>() {
                @Override/* ww  w.  ja va 2s.c  o m*/
                public HostAndPort apply(String input) {
                    return HostAndPort.fromParts(input, port);
                }
            }).toList();

    ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
    try {
        ReachableSocketFinder finder = new ReachableSocketFinder(executor);
        HostAndPort result = finder.findOpenSocketOnNode(sockets, timeout);
        return result.getHostText();
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        throw new IllegalStateException("Unable to connect SshClient to " + node
                + "; check that the node is accessible and that the SSH key exists and is correctly configured, including any passphrase defined",
                e);
    } finally {
        executor.shutdownNow();
    }
}

From source file:net.myrrix.web.servlets.AbstractMyrrixServlet.java

private static String buildRedirectToPartitionURL(HttpServletRequest request, int toPartition,
        long unnormalizedPartitionToServe, List<List<HostAndPort>> thePartitions) {

    List<HostAndPort> replicas = thePartitions.get(toPartition);
    // Also determine (first) replica by hashing to preserve a predictable order of access
    // through the replicas for a given ID
    int chosenReplica = LangUtils.mod(RandomUtils.md5HashToLong(unnormalizedPartitionToServe), replicas.size());
    HostAndPort hostPort = replicas.get(chosenReplica);

    StringBuilder redirectURL = new StringBuilder();
    redirectURL.append(request.isSecure() ? "https" : "http").append("://");
    redirectURL.append(hostPort.getHostText()).append(':').append(hostPort.getPort());
    redirectURL.append(request.getRequestURI());
    String query = request.getQueryString();
    if (query != null) {
        redirectURL.append('?').append(query);
    }/*  w w  w  .  j  a  v a2s .  c om*/

    return redirectURL.toString();
}

From source file:com.facebook.presto.jdbc.ext.PrestoConnection.java

private static URI createHttpUri(HostAndPort address) {
    return uriBuilder().scheme("http").host(address.getHostText()).port(address.getPort()).build();
}

From source file:org.voltdb.utils.Collector.java

public static boolean uploadToServer(String collectionFilePath, String host, String username, String password)
        throws Exception {
    attemptConnect(host, username, password);

    SSHTools ssh = new SSHTools(username, null);
    SFTPSession sftp = null;//from w w  w.  j  av  a 2s .  c om

    HostAndPort hostAndPort = HostAndPort.fromString(host);
    if (hostAndPort.hasPort()) {
        sftp = ssh.getSftpSession(username, password, null, hostAndPort.getHostText(), hostAndPort.getPort(),
                null);
    } else {
        sftp = ssh.getSftpSession(username, password, null, host, null);
    }

    String rootpath = sftp.exec("pwd").trim();

    HashMap<File, File> files = new HashMap<File, File>();
    File src = new File(collectionFilePath);
    File dest = new File(rootpath + File.separator + new File(collectionFilePath).getName());
    files.put(src, dest);

    try {
        sftp.ensureDirectoriesExistFor(files.values());
        sftp.copyOverFiles(files);
    } finally {
        if (sftp != null) {
            sftp.terminate();
        }
    }

    return true;
}

From source file:zipkin.elasticsearch.ElasticsearchSpanStore.java

private static Client createClient(List<String> hosts, String clusterName) {
    Settings settings = Settings.builder().put("cluster.name", clusterName).put("client.transport.sniff", true)
            .build();//ww  w  . j a  v  a2 s .c om

    TransportClient client = TransportClient.builder().settings(settings).build();
    for (String host : hosts) {
        HostAndPort hostAndPort = HostAndPort.fromString(host);
        try {
            client.addTransportAddress(new InetSocketTransportAddress(
                    InetAddress.getByName(hostAndPort.getHostText()), hostAndPort.getPort()));
        } catch (UnknownHostException e) {
            // Hosts may be down transiently, we should still try to connect. If all of them happen
            // to be down we will fail later when trying to use the client when checking the index
            // template.
            continue;
        }
    }
    return client;
}

From source file:org.voltdb.utils.Collector.java

public static void attemptConnect(String host, String username, String password) throws Exception {
    SSHTools ssh = new SSHTools(username, null);

    try {/*  ww w.  ja  v  a 2s  .c o  m*/
        HostAndPort hostAndPort = HostAndPort.fromString(host);
        if (hostAndPort.hasPort()) {
            ssh.getSftpSession(username, password, null, hostAndPort.getHostText(), hostAndPort.getPort(),
                    null);
        } else {
            ssh.getSftpSession(username, password, null, host, null);
        }
    } catch (SFTPException e) {
        String errorMsg = e.getCause().getMessage();

        /*
         * e.getCause() is JSchException and the java exception class name only appears in message
         * hide java class name and extract error message
         */
        Pattern pattern = Pattern.compile("(java.*Exception: )(.*)");
        Matcher matcher = pattern.matcher(errorMsg);

        if (matcher.matches()) {
            if (errorMsg.startsWith("java.net.UnknownHostException")) {
                throw new Exception("Unknown host: " + matcher.group(2));
            } else {
                throw new Exception(matcher.group(2));
            }
        } else {
            if (errorMsg.equals("Auth cancel") || errorMsg.equals("Auth fail")) {
                // "Auth cancel" appears when username doesn't exist or password is wrong
                throw new Exception("Authorization rejected");
            } else {
                throw new Exception(errorMsg.substring(0, 1).toUpperCase() + errorMsg.substring(1));
            }
        }
    } catch (Exception e) {
        String errorMsg = e.getMessage();

        throw new Exception(errorMsg.substring(0, 1).toUpperCase() + errorMsg.substring(1));
    }
}

From source file:io.druid.server.lookup.cache.LookupCoordinatorManager.java

static URL getLookupsURL(HostAndPort druidNode) throws MalformedURLException {
    return new URL("http", druidNode.getHostText(), druidNode.getPortOrDefault(-1),
            ListenerResource.BASE_PATH + "/" + LOOKUP_LISTEN_ANNOUNCE_KEY);
}

From source file:org.apache.hadoop.hive.metastore.tools.Util.java

/**
 * Get server URI.<p>/*  w w w  .ja va 2s . c o m*/
 * HMS host is obtained from
 * <ol>
 * <li>Argument</li>
 * <li>HMS_HOST environment parameter</li>
 * <li>hms.host Java property</li>
 * <li>use 'localhost' if above fails</li>
 * </ol>
 * HMS Port is obtained from
 * <ol>
 * <li>Argument</li>
 * <li>host:port string</li>
 * <li>HMS_PORT environment variable</li>
 * <li>hms.port Java property</li>
 * <li>default port value</li>
 * </ol>
 *
 * @param host       HMS host string.
 * @param portString HMS port
 * @return HMS URI
 * @throws URISyntaxException if URI is is invalid
 */
public static @Nullable URI getServerUri(@Nullable String host, @Nullable String portString)
        throws URISyntaxException {
    if (host == null) {
        host = System.getenv(ENV_SERVER);
    }
    if (host == null) {
        host = System.getProperty(PROP_HOST);
    }
    if (host == null) {
        host = DEFAULT_HOST;
    }
    host = host.trim();

    if ((portString == null || portString.isEmpty() || portString.equals("0")) && !host.contains(":")) {
        portString = System.getenv(ENV_PORT);
        if (portString == null) {
            portString = System.getProperty(PROP_PORT);
        }
    }
    Integer port = Constants.HMS_DEFAULT_PORT;
    if (portString != null) {
        port = Integer.parseInt(portString);
    }

    HostAndPort hp = HostAndPort.fromString(host).withDefaultPort(port);

    LOG.info("Connecting to {}:{}", hp.getHostText(), hp.getPort());

    return new URI(THRIFT_SCHEMA, null, hp.getHostText(), hp.getPort(), null, null, null);
}