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.hazelcast.HazelcastNodeImpl.java

@Override
protected void connectSensors() {
    super.connectSensors();

    if (LOG.isDebugEnabled()) {
        LOG.debug("Connecting sensors for node: {} ", getAttribute(Attributes.HOSTNAME));
    }/*from   ww w .  j ava  2 s  .co m*/

    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getNodePort());

    String nodeUri = String.format("http://%s:%d/hazelcast/rest/cluster", hp.getHostText(), hp.getPort());
    sensors().set(Attributes.MAIN_URI, URI.create(nodeUri));

    if (LOG.isDebugEnabled()) {
        LOG.debug("Node {} is using {} as a main URI", this, nodeUri);
    }

    httpFeed = HttpFeed.builder().entity(this).period(3000, TimeUnit.MILLISECONDS).baseUri(nodeUri)
            .poll(new HttpPollConfig<Boolean>(SERVICE_UP).onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(false)))
            .build();
}

From source file:de.qaware.playground.zwitscher.util.configuration.Cfg4JConfigurationProvider.java

/**
 * CDI producer for cfg4j configuration providers.
 *
 * @return a ready-to-use cfg4j configuration provider.
 *///w  w w .  j  ava 2  s  .c  o m
@Produces
public ConfigurationProvider produceLogger() {

    if (cfgProvider == null) {
        //file configuration source
        ConfigFilesProvider configFilesProvider = () -> Arrays.asList(Paths.get(CONFIG_FILE));
        ConfigurationSource fileSource = new ClasspathConfigurationSource(configFilesProvider);

        //consul configuration source
        HostAndPort consulHost = ConsulFabioServiceDiscovery.getConsulHostAndPort();
        ConfigurationSource consulSource = new ConsulConfigurationSourceBuilder()
                .withHost(consulHost.getHostText()).withPort(consulHost.getPort()).build();

        //fallback to config file if consul is not reachable
        FallbackConfigurationSource fallbackConfigSource = new FallbackConfigurationSource(consulSource,
                fileSource);
        //config values first from Consul and then lookup in file
        MergeConfigurationSource mergedConfigSource = new MergeConfigurationSource(fileSource,
                fallbackConfigSource);

        String configEnv = System.getenv(CONFIG_ENV);
        if (configEnv == null)
            configEnv = System.getProperty(CONFIG_ENV);
        if (configEnv == null)
            configEnv = DEFAULT_CONFIG_ENV;

        cfgProvider = new ConfigurationProviderBuilder().withConfigurationSource(mergedConfigSource)
                .withMetrics(MetricsProvider.getMetricRegistry(), "cfg4j")
                .withReloadStrategy(new PeriodicalReloadStrategy(2, TimeUnit.SECONDS))
                .withEnvironment(new ImmutableEnvironment(configEnv)).build();
    }

    return cfgProvider;
}

From source file:me.j360.trace.storage.elasticsearch.LazyClient.java

@Override
protected Client compute() {
    Settings settings = Settings.builder().put("cluster.name", clusterName)
            .put("lazyClient.transport.sniff", true).build();

    TransportClient client = TransportClient.builder().settings(settings).build();
    for (String host : hosts) {
        HostAndPort hostAndPort = HostAndPort.fromString(host).withDefaultPort(9300);
        try {//  w  w  w . j  a v a 2 s .  co m
            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;
        }
    }
    checkForIndexTemplate(client, indexTemplate);
    return client;
}

From source file:com.eightkdata.mongowp.client.wrapper.MongoClientWrapper.java

private void testAddress(HostAndPort address, MongoClientOptions options)
        throws UnreachableMongoServerException {
    SocketAddress sa = new InetSocketAddress(address.getHostText(), address.getPort());
    try (Socket s = options.getSocketFactory().createSocket()) {
        s.connect(sa, 3000);//from w  w  w  . j  a  va  2  s .  c  o  m
    } catch (IOException ex) {
        throw new UnreachableMongoServerException(address, ex);
    }
}

From source file:brooklyn.entity.nosql.mongodb.ReplicaSetConfig.java

/**
 * Adds a new member to the replica set config using the given {@link HostAndPort} for hostname and port.
 * Doesn't attempt to check that the id is free.
 *///from ww  w. jav  a 2 s.  c o m
public ReplicaSetConfig member(HostAndPort address, Integer id) {
    return member(address.getHostText(), address.getPort(), id);
}

From source file:ratpack.handling.internal.NcsaRequestLogger.java

String ncsaLogFormat(HostAndPort client, String rfc1413Ident, Optional<CharSequence> userId, Instant timestamp,
        HttpMethod method, String uri, String httpProtocol, Status status, String responseSize) {
    return String.format("%s %s %s [%s] \"%s %s %s\" %d %s", client.getHostText(), rfc1413Ident,
            userId.orElse("-"), FORMATTER.format(timestamp), method.getName(), uri, httpProtocol,
            status.getCode(), responseSize);
}

From source file:com.spotify.helios.testing.HeliosDeploymentResource.java

/** Ensure that the HeliosDeployment is up. */
@Override/* w  w w  .ja  va2  s .  c o  m*/
public void before() throws Throwable {
    super.before();

    // wait for the helios master to be available
    Polling.awaitUnchecked(30, TimeUnit.SECONDS,
            "Could not connect to HeliosDeployment at " + deployment.address() + " after %d %s",
            new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    final HostAndPort hap = deployment.address();
                    final SocketAddress address = new InetSocketAddress(hap.getHostText(), hap.getPort());
                    log.debug("attempting to connect to {}", address);

                    try {
                        final Socket s = new Socket();
                        s.connect(address, 100);
                        log.info("successfully connected to address {} for {}", address, deployment);
                        return true;
                    } catch (SocketTimeoutException | ConnectException e) {
                        log.debug("could not yet connect to HeliosDeployment: {}", e.toString());
                        return null;
                    }
                }
            });

    // Ensure that at least one agent is available and UP in this HeliosDeployment.
    // This prevents continuing with the test when starting up helios-solo before the agent is
    // registered.
    final HeliosClient client = client();
    Polling.awaitUnchecked(30, TimeUnit.SECONDS,
            "No agents were available at HeliosDeployment at " + deployment.address() + " after %d %s",
            new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    final ListenableFuture<List<String>> future = client.listHosts();

                    final List<String> hosts;
                    try {
                        // use a short timeout to allow this request to be retried a few times by the
                        // Polling.await loop
                        hosts = future.get(1, TimeUnit.SECONDS);
                    } catch (TimeoutException | InterruptedException e) {
                        log.debug("timed out waiting for listHosts request to finish, will retry");
                        return null;
                    }

                    if (hosts.isEmpty()) {
                        log.debug("0 agents in {}, will retry", deployment);
                        return null;
                    }

                    // Check that at least one host is UP (is maintaining a reasonably reliable
                    // connection to ZK) in addition to registering.
                    final ListenableFuture<Map<String, HostStatus>> statusFuture = client.hostStatuses(hosts);
                    final Map<String, HostStatus> hostStatuses;
                    try {
                        hostStatuses = statusFuture.get(1, TimeUnit.SECONDS);
                    } catch (TimeoutException | InterruptedException e) {
                        log.debug("timed out waiting for hostStatuses to finish, will retry");
                        return null;
                    }

                    for (final HostStatus hostStatus : hostStatuses.values()) {
                        if (hostStatus != null && hostStatus.getStatus() == HostStatus.Status.UP) {
                            log.info("Ensured that at least one agent is UP in this HeliosDeployment, "
                                    + "continuing with test!");
                            return true;
                        }
                    }

                    return null;
                }
            });
}

From source file:ratpack.handling.internal.DefaultRequestLog.java

String ncsaLogFormat(HostAndPort client, String rfc1413Ident, Optional<UserIdentifier> userId,
        Instant timestamp, HttpMethod method, String uri, String httpProtocol, Status status,
        String responseSize) {/*from   ww w  .  ja v a  2s.co  m*/
    return String.format("%s %s %s [%s] \"%s %s %s\" %d %s", client.getHostText(), rfc1413Ident,
            userId.isPresent() ? userId.get().getUserIdentifier() : "-", formatter.format(timestamp),
            method.getName(), uri, httpProtocol, status.getCode(), responseSize);
}

From source file:com.twitter.aurora.scheduler.http.LeaderRedirect.java

/**
 * Gets the optional redirect URI target in the event that this process is not the leading
 * scheduler.//from  w w  w  . j a v a  2  s.  co m
 *
 * @param req HTTP request.
 * @return An optional redirect destination to route the request to the leading scheduler.
 */
public Optional<String> getRedirectTarget(HttpServletRequest req) {
    Optional<HostAndPort> redirectTarget = getRedirect();
    if (redirectTarget.isPresent()) {
        HostAndPort target = redirectTarget.get();
        StringBuilder redirect = new StringBuilder().append(req.getScheme()).append("://")
                .append(target.getHostText()).append(":").append(target.getPort()).append(req.getRequestURI());

        String queryString = req.getQueryString();
        if (queryString != null) {
            redirect.append("?").append(queryString);
        }

        return Optional.of(redirect.toString());
    } else {
        return Optional.absent();
    }
}

From source file:com.groupon.mesos.util.UPID.java

private UPID(final String id, final HostAndPort hostAndPort, final Integer ip) {
    this.id = id;
    this.hostAndPort = hostAndPort;
    this.ip = ip;

    this.pidAsString = format("%s@%s:%d", id, hostAndPort.getHostText(), hostAndPort.getPort());
}