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

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

Introduction

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

Prototype

public int getPort() 

Source Link

Document

Get the current port number, failing if no port is defined.

Usage

From source file:org.apache.bookkeeper.stats.CodahaleMetricsProvider.java

@Override
public void start(Configuration conf) {
    initIfNecessary();/*www  . jav  a  2 s  .com*/

    int metricsOutputFrequency = conf.getInt("codahaleStatsOutputFrequencySeconds", 60);
    String prefix = conf.getString("codahaleStatsPrefix", "");
    String graphiteHost = conf.getString("codahaleStatsGraphiteEndpoint");
    String csvDir = conf.getString("codahaleStatsCSVEndpoint");
    String slf4jCat = conf.getString("codahaleStatsSlf4jEndpoint");
    String jmxDomain = conf.getString("codahaleStatsJmxEndpoint");

    if (!Strings.isNullOrEmpty(graphiteHost)) {
        LOG.info("Configuring stats with graphite");
        HostAndPort addr = HostAndPort.fromString(graphiteHost);
        final Graphite graphite = new Graphite(new InetSocketAddress(addr.getHostText(), addr.getPort()));
        reporters.add(
                GraphiteReporter.forRegistry(getMetrics()).prefixedWith(prefix).convertRatesTo(TimeUnit.SECONDS)
                        .convertDurationsTo(TimeUnit.MILLISECONDS).filter(MetricFilter.ALL).build(graphite));
    }
    if (!Strings.isNullOrEmpty(csvDir)) {
        // NOTE: 1/ metrics output files are exclusive to a given process
        // 2/ the output directory must exist
        // 3/ if output files already exist they are not overwritten and there is no metrics output
        File outdir;
        if (!Strings.isNullOrEmpty(prefix)) {
            outdir = new File(csvDir, prefix);
        } else {
            outdir = new File(csvDir);
        }
        LOG.info("Configuring stats with csv output to directory [{}]", outdir.getAbsolutePath());
        reporters.add(CsvReporter.forRegistry(getMetrics()).convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS).build(outdir));
    }
    if (!Strings.isNullOrEmpty(slf4jCat)) {
        LOG.info("Configuring stats with slf4j");
        reporters.add(Slf4jReporter.forRegistry(getMetrics()).outputTo(LoggerFactory.getLogger(slf4jCat))
                .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build());
    }
    if (!Strings.isNullOrEmpty(jmxDomain)) {
        LOG.info("Configuring stats with jmx");
        jmx = JmxReporter.forRegistry(getMetrics()).inDomain(jmxDomain).convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS).build();
        jmx.start();
    }

    for (ScheduledReporter r : reporters) {
        r.start(metricsOutputFrequency, TimeUnit.SECONDS);
    }
}

From source file:org.apache.brooklyn.core.location.access.PortMapping.java

public PortMapping(String publicIpId, HostAndPort publicEndpoint, Location target, int privatePort) {
    this.publicIpId = checkNotNull(publicIpId, "publicIpId");
    this.publicEndpoint = checkNotNull(publicEndpoint, "publicEndpoint");
    this.publicPort = publicEndpoint.getPort();
    this.target = target;
    this.privatePort = privatePort;
}

From source file:org.apache.sentry.core.common.transport.SentryTransportFactory.java

/**
 * Connect to the endpoint and return a connected Thrift transport.
 * @return Connection to the endpoint/*  w w  w. j av  a 2s .  c  o  m*/
 * @throws IOException
 */
@Override
public TTransportWrapper getTransport(HostAndPort endpoint) throws Exception {
    return new TTransportWrapper(
            connectToServer(new InetSocketAddress(endpoint.getHostText(), endpoint.getPort())), endpoint);
}

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));
    }/* w w  w  .  j a v  a2s  . c om*/

    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:brooklyn.entity.nosql.mongodb.ReplicaSetConfig.java

/** Removes the first entity with host and port matching the given address. */
public ReplicaSetConfig remove(HostAndPort address) {
    return remove(address.getHostText(), address.getPort());
}

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);/*  w  ww.j  av a2  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.
 *//*w w  w  . ja  v a2 s  . c  o m*/
public ReplicaSetConfig member(HostAndPort address, Integer id) {
    return member(address.getHostText(), address.getPort(), id);
}

From source file:ratpack.server.internal.DefaultPublicAddress.java

public URI getAddress(Context context) {
    return publicAddress.orElseGet(() -> {
        String scheme;/*from w  w  w  .j  av  a 2s  . c o m*/
        String host;
        int port;
        HostAndPort forwardedHostData = getForwardedHostData(context);
        if (forwardedHostData != null) {
            scheme = determineScheme(context, this.scheme);
            host = forwardedHostData.getHostText();
            port = forwardedHostData.getPortOrDefault(-1);
        } else {
            URI absoluteRequestURI = getAbsoluteRequestUri(context);
            if (absoluteRequestURI != null) {
                scheme = determineScheme(context, absoluteRequestURI.getScheme());
                host = absoluteRequestURI.getHost();
                port = absoluteRequestURI.getPort();
            } else {
                scheme = determineScheme(context, this.scheme);
                HostAndPort hostData = getHostData(context);
                if (hostData != null) {
                    host = hostData.getHostText();
                    port = hostData.getPortOrDefault(-1);
                } else {
                    HostAndPort localAddress = context.getRequest().getLocalAddress();
                    host = localAddress.getHostText();
                    port = ProtocolUtil.isDefaultPortForScheme(localAddress.getPort(), this.scheme) ? -1
                            : localAddress.getPort();
                }
            }
        }
        try {
            return new URI(scheme, null, host, port, null, null, null);
        } catch (URISyntaxException ex) {
            throw Exceptions.uncheck(ex);
        }
    });
}

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 {//  www .  ja  v a2s.c  o  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.spotify.helios.testing.HeliosDeploymentResource.java

/** Ensure that the HeliosDeployment is up. */
@Override//from   w w w.  jav  a  2s  .  c om
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;
                }
            });
}