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

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

Introduction

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

Prototype

public static HostAndPort fromParts(String host, int port) 

Source Link

Document

Build a HostAndPort instance from separate host and port values.

Usage

From source file:org.sfs.integration.java.BaseTestVerticle.java

@Before
public void before(TestContext context) {
    vertx = rule.vertx();//from   ww w  . ja  v a 2 s .c  om
    Async async = context.async();
    aVoid().flatMap(aVoid -> {
        String clusteruuid = UUID.randomUUID().toString();
        try {
            rootTmpDir = createTempDirectory("");
            esTempDir = createTempDirectory(rootTmpDir, format("test-cluster-%s", clusteruuid));
            tmpDir = createTempDirectory(rootTmpDir, valueOf(currentTimeMillis()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        int esPort = findFreePort(9300, 9400);
        esHost = "127.0.0.1:" + esPort;
        esClusterName = format("test-cluster-%s", clusteruuid);
        esNodeName = format("test-server-node-%s", clusteruuid);

        Builder settings = settingsBuilder();
        settings.put("script.groovy.sandbox.enabled", false);
        settings.put("cluster.name", esClusterName);
        settings.put("node.name", esNodeName);
        settings.put("http.enabled", false);
        settings.put("discovery.zen.ping.multicast.enabled", false);
        settings.put("discovery.zen.ping.unicast.hosts", esHost);
        settings.put("transport.tcp.port", esPort);
        settings.put("network.host", "127.0.0.1");
        settings.put("node.data", true);
        settings.put("node.master", true);
        settings.put("path.home", esTempDir);
        esNode = nodeBuilder().settings(settings).node();
        esClient = esNode.client();

        JsonObject verticleConfig;

        Buffer buffer = vertx.fileSystem().readFileBlocking(
                currentThread().getContextClassLoader().getResource("intgtestconfig.json").getFile());
        verticleConfig = new JsonObject(buffer.toString(UTF_8));
        verticleConfig.put("fs.home", tmpDir.toString());

        if (!verticleConfig.containsKey("elasticsearch.cluster.name")) {
            verticleConfig.put("elasticsearch.cluster.name", esClusterName);
        }

        if (!verticleConfig.containsKey("elasticsearch.node.name")) {
            verticleConfig.put("elasticsearch.node.name", esNodeName);
        }

        if (!verticleConfig.containsKey("elasticsearch.discovery.zen.ping.unicast.hosts")) {
            verticleConfig.put("elasticsearch.discovery.zen.ping.unicast.hosts", new JsonArray().add(esHost));
        }

        if (!verticleConfig.containsKey("http.listen.addresses")) {
            int freePort = findFreePort(6677, 7777);
            verticleConfig.put("http.listen.addresses",
                    new JsonArray().add(HostAndPort.fromParts("127.0.0.1", freePort).toString()));
        }

        HostAndPort hostAndPort = HostAndPort
                .fromString(verticleConfig.getJsonArray("http.listen.addresses").getString(0));

        HttpClientOptions httpClientOptions = new HttpClientOptions();
        httpClientOptions.setDefaultPort(hostAndPort.getPort()).setDefaultHost(hostAndPort.getHostText())
                .setMaxPoolSize(25).setConnectTimeout(1000).setKeepAlive(false).setLogActivity(true);

        HttpClientOptions httpsClientOptions = new HttpClientOptions();
        httpsClientOptions.setDefaultPort(hostAndPort.getPort()).setDefaultHost(hostAndPort.getHostText())
                .setMaxPoolSize(25).setConnectTimeout(1000).setKeepAlive(false).setLogActivity(true)
                .setSsl(true);
        httpClient = vertx.createHttpClient(httpClientOptions);
        httpsClient = vertx.createHttpClient(httpsClientOptions);

        SfsServer sfsServer = new SfsServer();

        ObservableFuture<String> handler = RxHelper.observableFuture();
        vertx.deployVerticle(sfsServer, new DeploymentOptions().setConfig(verticleConfig), handler.toHandler());
        return handler.map(new ToVoid<>()).doOnNext(aVoid1 -> {
            vertxContext = sfsServer.vertxContext();
            checkState(vertxContext != null, "VertxContext was null on Verticle %s", sfsServer);
        }).onErrorResumeNext(throwable -> {
            throwable.printStackTrace();
            return cleanup().flatMap(aVoid1 -> Observable.<Void>error(throwable));
        });
    }).subscribe(new TestSubscriber(context, async));
}

From source file:brooklyn.networking.portforwarding.DockerPortForwarder.java

@Override
public HostAndPort openPortForwarding(MachineLocation targetMachine, int targetPort,
        Optional<Integer> optionalPublicPort, Protocol protocol, Cidr accessingCidr) {

    String targetIp = targetMachine.getAddress().getHostAddress();
    if (targetIp == null) {
        throw new IllegalStateException("Failed to open port-forwarding for machine " + targetMachine
                + " because its" + " location has no target ip: " + targetMachine);
    }/*from   ww w  .ja v a  2 s  .c  o  m*/
    HostAndPort targetSide = HostAndPort.fromParts(targetIp, targetPort);
    HostAndPort newFrontEndpoint = openPortForwarding(targetSide, optionalPublicPort, protocol, accessingCidr);
    log.debug("Enabled port-forwarding for {} port {} (VM {}), via {}",
            new Object[] { targetMachine, targetPort, targetMachine, newFrontEndpoint });
    return newFrontEndpoint;
}

From source file:org.jclouds.ssh.jsch.JschSshClient.java

public JschSshClient(ProxyConfig proxyConfig, BackoffLimitedRetryHandler backoffLimitedRetryHandler,
        HostAndPort socket, LoginCredentials loginCredentials, int timeout) {
    this.user = checkNotNull(loginCredentials, "loginCredentials").getUser();
    this.host = checkNotNull(socket, "socket").getHostText();
    checkArgument(socket.getPort() > 0, "ssh port must be greater then zero" + socket.getPort());
    checkArgument(loginCredentials.getPassword() != null || loginCredentials.getPrivateKey() != null,
            "you must specify a password or a key");
    this.backoffLimitedRetryHandler = checkNotNull(backoffLimitedRetryHandler, "backoffLimitedRetryHandler");
    if (loginCredentials.getPrivateKey() == null) {
        this.toString = String.format("%s:pw[%s]@%s:%d", loginCredentials.getUser(),
                base16().lowerCase().encode(md5().hashString(loginCredentials.getPassword(), UTF_8).asBytes()),
                host, socket.getPort());
    } else {/*from   w  w w.  j a  va 2s . com*/
        String fingerPrint = fingerprintPrivateKey(loginCredentials.getPrivateKey());
        String sha1 = sha1PrivateKey(loginCredentials.getPrivateKey());
        this.toString = String.format("%s:rsa[fingerprint(%s),sha1(%s)]@%s:%d", loginCredentials.getUser(),
                fingerPrint, sha1, host, socket.getPort());
    }
    sessionConnection = SessionConnection.builder().hostAndPort(HostAndPort.fromParts(host, socket.getPort()))
            .loginCredentials(loginCredentials).proxy(checkNotNull(proxyConfig, "proxyConfig"))
            .connectTimeout(timeout).sessionTimeout(timeout).build();
}

From source file:com.netflix.simianarmy.client.vsphere.VSphereClient.java

@Override
/**/*from w w w.  ja v a  2s  . c om*/
 * Set up ssh connection to the virtual machine.  This is to make SriptChaosType to also run in vSphere.
 * @param instanceId Virtual machine ID
 * @param credentials SSH credential
 * @return SSH client
 */
public SshClient connectSsh(String instanceId, LoginCredentials credentials) {
    String ipAddress = null;
    try {
        connection.connect();
        VirtualMachine virtualMachine = connection.getVirtualMachineById(instanceId);
        ipAddress = virtualMachine.getGuest().getIpAddress();
    } catch (RemoteException e) {
        throw new AmazonServiceException("cannot destroy & recreate " + instanceId, e);
    } finally {
        connection.disconnect();
    }
    JschSshClient ssh = new JschSshClient(new GuiceProxyConfig(), BackoffLimitedRetryHandler.INSTANCE,
            HostAndPort.fromParts(ipAddress, PORT), credentials, TIME_OUT);
    ssh.connect();
    return ssh;
}

From source file:com.netflix.priam.defaultimpl.PriamGuiceModule.java

@Provides
@Singleton/* w  w w  .  jav  a2 s .  c  o m*/
HostAndPort providePort(PriamConfiguration configuration) {
    ServerFactory serverFactory = configuration.getServerFactory();

    // Our method for obtaining connector factories from the server factory varies depending on the latter's type
    List<ConnectorFactory> connectorFactories;
    if (serverFactory instanceof DefaultServerFactory) {
        connectorFactories = ((DefaultServerFactory) serverFactory).getApplicationConnectors();
    } else if (serverFactory instanceof SimpleServerFactory) {
        connectorFactories = Collections.singletonList(((SimpleServerFactory) serverFactory).getConnector());
    } else {
        throw new IllegalStateException("Encountered an unexpected ServerFactory type");
    }

    // Find the first connector that matches and return its port information (in practice there should
    // be one, and just one, match)
    try {
        HttpConnectorFactory httpConnectorFactory = (HttpConnectorFactory) Iterables.find(connectorFactories,
                Predicates.instanceOf(HttpConnectorFactory.class));

        String host = httpConnectorFactory.getBindHost();
        if (host == null) {
            host = InetAddress.getLocalHost().getHostAddress();
        }

        int port = httpConnectorFactory.getPort();
        return HostAndPort.fromParts(host, port);
    } catch (UnknownHostException ex) {
        throw new IllegalStateException("Unable to determine the local host address for the server", ex);
    } catch (NoSuchElementException ex) {
        throw new IllegalStateException("Did not find a valid HttpConnector for the server", ex);
    }
}

From source file:org.apache.accumulo.server.rpc.TServerUtils.java

/**
 * Start a server, at the given port, or higher, if that port is not available.
 *
 * @param service/*  w w  w  . j a v  a2  s  . c  om*/
 *          RPC configuration
 * @param portHintProperty
 *          the port to attempt to open, can be zero, meaning "any available port"
 * @param processor
 *          the service to be started
 * @param serverName
 *          the name of the class that is providing the service
 * @param threadName
 *          name this service's thread for better debugging
 * @param portSearchProperty
 *          A boolean Property to control if port-search should be used, or null to disable
 * @param minThreadProperty
 *          A Property to control the minimum number of threads in the pool
 * @param timeBetweenThreadChecksProperty
 *          A Property to control the amount of time between checks to resize the thread pool
 * @param maxMessageSizeProperty
 *          A Property to control the maximum Thrift message size accepted
 * @return the server object created, and the port actually used
 * @throws UnknownHostException
 *           when we don't know our own address
 */
public static ServerAddress startServer(AccumuloServerContext service, String hostname,
        Property portHintProperty, TProcessor processor, String serverName, String threadName,
        Property portSearchProperty, Property minThreadProperty, Property timeBetweenThreadChecksProperty,
        Property maxMessageSizeProperty) throws UnknownHostException {
    final AccumuloConfiguration config = service.getConfiguration();

    final int portHint = config.getPort(portHintProperty);

    int minThreads = 2;
    if (minThreadProperty != null)
        minThreads = config.getCount(minThreadProperty);

    long timeBetweenThreadChecks = 1000;
    if (timeBetweenThreadChecksProperty != null)
        timeBetweenThreadChecks = config.getTimeInMillis(timeBetweenThreadChecksProperty);

    long maxMessageSize = 10 * 1000 * 1000;
    if (maxMessageSizeProperty != null)
        maxMessageSize = config.getMemoryInBytes(maxMessageSizeProperty);

    boolean portSearch = false;
    if (portSearchProperty != null)
        portSearch = config.getBoolean(portSearchProperty);

    final int simpleTimerThreadpoolSize = config.getCount(Property.GENERAL_SIMPLETIMER_THREADPOOL_SIZE);
    final ThriftServerType serverType = service.getThriftServerType();

    if (ThriftServerType.SASL == serverType) {
        processor = updateSaslProcessor(serverType, processor);
    }

    // create the TimedProcessor outside the port search loop so we don't try to register the same metrics mbean more than once
    TimedProcessor timedProcessor = new TimedProcessor(config, processor, serverName, threadName);

    Random random = new Random();
    for (int j = 0; j < 100; j++) {

        // Are we going to slide around, looking for an open port?
        int portsToSearch = 1;
        if (portSearch)
            portsToSearch = 1000;

        for (int i = 0; i < portsToSearch; i++) {
            int port = portHint + i;
            if (portHint != 0 && i > 0)
                port = 1024 + random.nextInt(65535 - 1024);
            if (port > 65535)
                port = 1024 + port % (65535 - 1024);
            try {
                HostAndPort addr = HostAndPort.fromParts(hostname, port);
                return TServerUtils.startTServer(addr, serverType, timedProcessor, serverName, threadName,
                        minThreads, simpleTimerThreadpoolSize, timeBetweenThreadChecks, maxMessageSize,
                        service.getServerSslParams(), service.getSaslParams(),
                        service.getClientTimeoutInMillis());
            } catch (TTransportException ex) {
                log.error("Unable to start TServer", ex);
                if (ex.getCause() == null || ex.getCause().getClass() == BindException.class) {
                    // Note: with a TNonblockingServerSocket a "port taken" exception is a cause-less
                    // TTransportException, and with a TSocket created by TSSLTransportFactory, it
                    // comes through as caused by a BindException.
                    log.info("Unable to use port {}, retrying. (Thread Name = {})", port, threadName);
                    sleepUninterruptibly(250, TimeUnit.MILLISECONDS);
                } else {
                    // thrift is passing up a nested exception that isn't a BindException,
                    // so no reason to believe retrying on a different port would help.
                    log.error("Unable to start TServer", ex);
                    break;
                }
            }
        }
    }
    throw new UnknownHostException("Unable to find a listen port");
}

From source file:brooklyn.location.access.PortForwardManagerAuthority.java

/** {@inheritDoc} */
@Override/*from w  w w . j a v a 2s . c om*/
public HostAndPort getPublicHostAndPort(PortMapping m) {
    String hostname = getPublicIpHostname(m.publicIpId);
    if (hostname == null)
        throw new IllegalStateException(
                "No public hostname associated with " + m.publicIpId + " (mapping " + m + ")");
    return HostAndPort.fromParts(hostname, m.publicPort);
}

From source file:ratpack.http.internal.DefaultRequest.java

@Override
public HostAndPort getRemoteAddress() {
    return HostAndPort.fromParts(remoteSocket.getHostString(), remoteSocket.getPort());
}

From source file:ratpack.http.internal.DefaultRequest.java

@Override
public HostAndPort getLocalAddress() {
    return HostAndPort.fromParts(localSocket.getHostString(), localSocket.getPort());
}

From source file:brooklyn.location.docker.DockerContainerLocation.java

@Override
public HostAndPort getSocketEndpointFor(Cidr accessor, int privatePort) {
    String dockerHost = getAddress().getHostAddress();
    int hostPort = getMappedPort(privatePort);
    return HostAndPort.fromParts(dockerHost, hostPort);
}