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:brooklyn.networking.common.subnet.PortForwarderAsyncImpl.java

@Override
public void openPortForwardingAndAdvertise(final EntityAndAttribute<Integer> source,
        final Optional<Integer> optionalPublicPort, final Protocol protocol, final Cidr accessingCidr) {
    Advertiser advertiser = new Advertiser() {
        @Override//from   w w  w. ja  v  a2  s. c o m
        public void advertise(EntityAndAttribute<Integer> source, HostAndPort publicEndpoint) {
            String sourceSensor = source.getAttribute().getName();
            Entity entity = source.getEntity();
            AttributeSensor<String> mappedSensor = Sensors.newStringSensor("mapped." + sourceSensor);
            AttributeSensor<String> mappedEndpointSensor = Sensors
                    .newStringSensor("mapped.endpoint." + sourceSensor);
            AttributeSensor<Integer> mappedPortSensor = Sensors
                    .newIntegerSensor("mapped.portPart." + sourceSensor);
            String endpoint = publicEndpoint.getHostText() + ":" + publicEndpoint.getPort();
            entity.sensors().set(mappedSensor, endpoint);
            entity.sensors().set(mappedEndpointSensor, endpoint);
            entity.sensors().set(mappedPortSensor, publicEndpoint.getPort());
        }
    };
    doOpenPortForwardingAndAdvertise(source, optionalPublicPort, protocol, accessingCidr, advertiser);
}

From source file:io.airlift.drift.transport.netty.client.ConnectionFactory.java

@Override
public Future<Channel> getConnection(ConnectionParameters connectionParameters, HostAndPort address) {
    try {//from  w w w.j a  va2  s  .  co m
        Bootstrap bootstrap = new Bootstrap().group(group).channel(NioSocketChannel.class)
                .option(ALLOCATOR, allocator)
                .option(CONNECT_TIMEOUT_MILLIS,
                        saturatedCast(connectionParameters.getConnectTimeout().toMillis()))
                .handler(new ThriftClientInitializer(connectionParameters.getTransport(),
                        connectionParameters.getProtocol(), connectionParameters.getMaxFrameSize(),
                        connectionParameters.getRequestTimeout(), connectionParameters.getSocksProxy(),
                        connectionParameters.getSslContextParameters().map(sslContextFactory::get)));

        Promise<Channel> promise = group.next().newPromise();
        promise.setUncancellable();
        bootstrap.connect(new InetSocketAddress(address.getHost(), address.getPort()))
                .addListener((ChannelFutureListener) future -> notifyConnect(future, promise));
        return promise;
    } catch (Throwable e) {
        return group.next().newFailedFuture(new TTransportException(e));
    }
}

From source file:com.yahoo.omid.tsoclient.TSOClientImpl.java

TSOClientImpl(Configuration conf, MetricRegistry metrics) {

    this.metrics = metrics;

    // Start client with Nb of active threads = 3 as maximum.
    int tsoExecutorThreads = conf.getInt(TSO_EXECUTOR_THREAD_NUM_CONFKEY, DEFAULT_TSO_EXECUTOR_THREAD_NUM);

    factory = new NioClientSocketChannelFactory(
            Executors// w w  w .  jav a2  s  .  co m
                    .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()),
            tsoExecutorThreads);
    // Create the bootstrap
    bootstrap = new ClientBootstrap(factory);

    requestTimeoutMs = conf.getInt(REQUEST_TIMEOUT_IN_MS_CONFKEY, DEFAULT_REQUEST_TIMEOUT_MS);
    requestMaxRetries = conf.getInt(REQUEST_MAX_RETRIES_CONFKEY, DEFAULT_TSO_MAX_REQUEST_RETRIES);
    retryDelayMs = conf.getInt(TSO_RETRY_DELAY_MS_CONFKEY, DEFAULT_TSO_RETRY_DELAY_MS);

    LOG.info("Connecting to TSO...");
    // Try to connect to TSO from ZK. If fails, go through host:port config
    try {
        connectToZK(conf);
        configureCurrentTSOServerZNodeCache();
        HostAndPort hp = getCurrentTSOHostAndPortFoundInZK();
        LOG.info("\t* Current TSO host:port found in ZK: {}", hp);
        setTSOAddress(hp.getHostText(), hp.getPort());
    } catch (ZKException e) {
        LOG.warn("A problem connecting to TSO was found ({}). Trying to connect directly with host:port",
                e.getMessage());
        String host = conf.getString(TSO_HOST_CONFKEY);
        int port = conf.getInt(TSO_PORT_CONFKEY, DEFAULT_TSO_PORT);
        if (host == null) {
            throw new IllegalArgumentException("tso.host missing from configuration");
        }
        setTSOAddress(host, port);
    }

    fsmExecutor = Executors
            .newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("tsofsm-%d").build());
    fsm = new FsmImpl(fsmExecutor);
    fsm.setInitState(new DisconnectedState(fsm));

    ChannelPipeline pipeline = bootstrap.getPipeline();
    pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
    pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
    pipeline.addLast("protobufdecoder", new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
    pipeline.addLast("protobufencoder", new ProtobufEncoder());
    pipeline.addLast("handler", new Handler(fsm));

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("connectTimeoutMillis", 100);
}

From source file:org.apache.omid.tso.client.TSOClient.java

@Override
public void nodeChanged() throws Exception {

    String tsoInfo = getCurrentTSOInfoFoundInZK(zkCurrentTsoPath);
    // TSO info includes the new TSO host:port address and epoch
    String[] currentTSOAndEpochArray = tsoInfo.split("#");
    HostAndPort hp = HostAndPort.fromString(currentTSOAndEpochArray[0]);
    setTSOAddress(hp.getHostText(), hp.getPort());
    epoch = Long.parseLong(currentTSOAndEpochArray[1]);
    LOG.info("CurrentTSO ZNode changed. New TSO Host & Port {}/Epoch {}", hp, getEpoch());
    if (currentChannel != null && currentChannel.isConnected()) {
        LOG.info("\tClosing channel with previous TSO {}", currentChannel);
        currentChannel.close();//from   w  w  w .ja va2  s.co  m
    }

}

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

private URI getDefaultHttpUri(String path) {
    final HostAndPort bindAddress = getHttpBindAddress();

    final URI publishUri;
    final InetAddress inetAddress = toInetAddress(bindAddress.getHost());
    if (inetAddress != null && Tools.isWildcardInetAddress(inetAddress)) {
        final InetAddress guessedAddress;
        try {/*from  w w w  .  j  ava 2  s  .  c om*/
            guessedAddress = Tools.guessPrimaryNetworkAddress(inetAddress instanceof Inet4Address);

            if (guessedAddress.isLoopbackAddress()) {
                LOG.debug("Using loopback address {}", guessedAddress);
            }
        } catch (Exception e) {
            LOG.error(
                    "Could not guess primary network address for \"http_publish_uri\". Please configure it in your Graylog configuration.",
                    e);
            throw new ParameterException("No http_publish_uri.", e);
        }

        try {
            publishUri = new URI(getUriScheme(), null, guessedAddress.getHostAddress(), bindAddress.getPort(),
                    path, null, null);
        } catch (URISyntaxException e) {
            throw new RuntimeException("Invalid http_publish_uri.", e);
        }
    } else {
        try {
            publishUri = new URI(getUriScheme(), null, getHttpBindAddress().getHost(),
                    getHttpBindAddress().getPort(), path, null, null);
        } catch (URISyntaxException e) {
            throw new RuntimeException("Invalid http_publish_uri.", e);
        }
    }

    return publishUri;
}

From source file:org.sfs.SfsSingletonServer.java

protected Observable<HttpServer> createHttpServer(VertxContext<Server> vertxContext, HostAndPort hostAndPort,
        int verticleMaxHeaderSize, Router router) {
    ObservableFuture<HttpServer> handler = RxHelper.observableFuture();
    HttpServerOptions httpServerOptions = new HttpServerOptions().setMaxHeaderSize(verticleMaxHeaderSize)
            .setCompressionSupported(false).setUsePooledBuffers(true).setAcceptBacklog(10000)
            .setReuseAddress(true).setHandle100ContinueAutomatically(true);
    vertxContext.vertx().createHttpServer(httpServerOptions).requestHandler(router::accept)
            .listen(hostAndPort.getPort(), hostAndPort.getHostText(), handler.toHandler());
    return handler;
}

From source file:org.apache.beam.runners.dataflow.worker.windmill.GrpcWindmillServer.java

private Channel remoteChannel(HostAndPort endpoint) throws IOException {
    return NettyChannelBuilder.forAddress(endpoint.getHostText(), endpoint.getPort())
            .maxInboundMessageSize(java.lang.Integer.MAX_VALUE).negotiationType(NegotiationType.TLS)
            // Set ciphers(null) to not use GCM, which is disabled for Dataflow
            // due to it being horribly slow.
            .sslContext(GrpcSslContexts.forClient().ciphers(null).build()).build();
}

From source file:org.apache.beam.runners.dataflow.worker.windmill.GrpcWindmillServer.java

private synchronized void initializeWindmillService(Set<HostAndPort> endpoints) throws IOException {
    LOG.info("Initializing Streaming Engine GRPC client for endpoints: {}", endpoints);
    this.stubList.clear();
    this.syncStubList.clear();
    this.endpoints = ImmutableSet.<HostAndPort>copyOf(endpoints);
    for (HostAndPort endpoint : this.endpoints) {
        if ("localhost".equals(endpoint.getHostText())) {
            initializeLocalHost(endpoint.getPort());
        } else {/*from www.  j av a  2 s. c  o  m*/
            CallCredentials creds = MoreCallCredentials
                    .from(new VendoredCredentialsAdapter(options.getGcpCredential()));
            this.stubList.add(CloudWindmillServiceV1Alpha1Grpc.newStub(remoteChannel(endpoint))
                    .withCallCredentials(creds));
            this.syncStubList.add(CloudWindmillServiceV1Alpha1Grpc.newBlockingStub(remoteChannel(endpoint))
                    .withCallCredentials(creds));
        }
    }
}

From source file:org.apache.omid.tso.client.TSOClient.java

private TSOClient(OmidClientConfiguration omidConf) throws IOException {

    // Start client with Nb of active threads = 3 as maximum.
    int tsoExecutorThreads = omidConf.getExecutorThreads();

    factory = new NioClientSocketChannelFactory(
            Executors/*from w w w  .  j  a  v a2s. co m*/
                    .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()),
            tsoExecutorThreads);
    // Create the bootstrap
    bootstrap = new ClientBootstrap(factory);

    requestTimeoutInMs = omidConf.getRequestTimeoutInMs();
    requestMaxRetries = omidConf.getRequestMaxRetries();
    tsoReconnectionDelayInSecs = omidConf.getReconnectionDelayInSecs();

    LOG.info("Connecting to TSO...");
    HostAndPort hp;
    switch (omidConf.getConnectionType()) {
    case HA:
        zkClient = ZKUtils.initZKClient(omidConf.getConnectionString(), omidConf.getZkNamespace(),
                omidConf.getZkConnectionTimeoutInSecs());
        zkCurrentTsoPath = omidConf.getZkCurrentTsoPath();
        configureCurrentTSOServerZNodeCache(zkCurrentTsoPath);
        String tsoInfo = getCurrentTSOInfoFoundInZK(zkCurrentTsoPath);
        // TSO info includes the new TSO host:port address and epoch
        String[] currentTSOAndEpochArray = tsoInfo.split("#");
        hp = HostAndPort.fromString(currentTSOAndEpochArray[0]);
        setTSOAddress(hp.getHostText(), hp.getPort());
        epoch = Long.parseLong(currentTSOAndEpochArray[1]);
        LOG.info("\t* Current TSO host:port found in ZK: {} Epoch {}", hp, getEpoch());
        break;
    case DIRECT:
    default:
        hp = HostAndPort.fromString(omidConf.getConnectionString());
        setTSOAddress(hp.getHostText(), hp.getPort());
        LOG.info("\t* TSO host:port {} will be connected directly", hp);
        break;
    }

    fsmExecutor = Executors
            .newSingleThreadScheduledExecutor(new ThreadFactoryBuilder().setNameFormat("tsofsm-%d").build());
    fsm = new StateMachine.FsmImpl(fsmExecutor);
    fsm.setInitState(new DisconnectedState(fsm));

    ChannelPipeline pipeline = bootstrap.getPipeline();
    pipeline.addLast("lengthbaseddecoder", new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
    pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
    pipeline.addLast("protobufdecoder", new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
    pipeline.addLast("protobufencoder", new ProtobufEncoder());
    pipeline.addLast("handler", new Handler(fsm));

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("connectTimeoutMillis", 100);
}

From source file:net.myrrix.client.ClientRecommender.java

/**
 * @param replica host and port of replica to connect to
 * @param path URL to access (relative to context root)
 * @param method HTTP method to use/* w ww.  ja v  a 2s . co m*/
 * @param doOutput if true, will need to write data into the request body
 * @param chunkedStreaming if true, use chunked streaming to accommodate a large upload, if possible
 * @param requestProperties additional request key/value pairs or {@code null} for none
 */
private HttpURLConnection buildConnectionToReplica(HostAndPort replica, String path, String method,
        boolean doOutput, boolean chunkedStreaming, Map<String, String> requestProperties) throws IOException {
    String contextPath = config.getContextPath();
    if (contextPath != null) {
        path = '/' + contextPath + path;
    }
    String protocol = config.isSecure() ? "https" : "http";
    URL url;
    try {
        url = new URL(protocol, replica.getHostText(), replica.getPort(), path);
    } catch (MalformedURLException mue) {
        // can't happen
        throw new IllegalStateException(mue);
    }
    log.debug("{} {}", method, url);

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(method);
    connection.setDoInput(true);
    connection.setDoOutput(doOutput);
    connection.setUseCaches(false);
    connection.setAllowUserInteraction(false);
    connection.setRequestProperty(HttpHeaders.ACCEPT, DESIRED_RESPONSE_CONTENT_TYPE);
    if (closeConnection) {
        connection.setRequestProperty(HttpHeaders.CONNECTION, "close");
    }
    if (chunkedStreaming) {
        if (needAuthentication) {
            // Must buffer in memory if using authentication since it won't handle the authorization challenge
            log.debug("Authentication is enabled, so ingest data must be buffered in memory");
        } else {
            connection.setChunkedStreamingMode(0); // Use default buffer size
        }
    }
    if (requestProperties != null) {
        for (Map.Entry<String, String> entry : requestProperties.entrySet()) {
            connection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }
    return connection;
}