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:brooklyn.util.internal.ssh.SshjTool.java

private SshjTool(Builder builder) {
    // TODO Does this need to be ported from SshJschTool?
    //        if (host && host==~ /[^@]+@[^@]+/) {
    //            (user,host) = (host=~/([^@]+)@([^@]+)/)[0][1,2]
    //        }//w  ww .j  av  a 2s  . com

    host = checkNotNull(builder.host, "host");
    port = builder.port;
    user = builder.user;
    password = builder.password;
    strictHostKeyChecking = builder.strictHostKeyChecking;
    allocatePTY = builder.allocatePTY;
    sshTries = builder.sshTries;
    backoffLimitedRetryHandler = new BackoffLimitedRetryHandler(sshTries, builder.sshRetryDelay);
    privateKeyPassphrase = builder.privateKeyPassphrase;
    privateKeyData = builder.privateKeyData;

    if (builder.privateKeyFiles.size() > 1) {
        throw new IllegalArgumentException("sshj supports only a single private key-file; "
                + "for defaults of ~/.ssh/id_rsa and ~/.ssh/id_dsa leave blank");
    } else if (builder.privateKeyFiles.size() == 1) {
        String privateKeyFileStr = Iterables.get(builder.privateKeyFiles, 0);
        String amendedKeyFile = privateKeyFileStr.startsWith("~")
                ? (System.getProperty("user.home") + privateKeyFileStr.substring(1))
                : privateKeyFileStr;
        privateKeyFile = new File(amendedKeyFile);
    } else {
        privateKeyFile = null;
    }

    checkArgument(host.length() > 0, "host value must not be an empty string");
    checkPortValid(port, "ssh port");

    toString = String.format("%s@%s:%d", user, host, port);

    sshClientConnection = SshjClientConnection.builder().hostAndPort(HostAndPort.fromParts(host, port))
            .username(user).password(password).privateKeyPassphrase(privateKeyPassphrase)
            .privateKeyData(privateKeyData).privateKeyFile(privateKeyFile)
            .strictHostKeyChecking(strictHostKeyChecking).connectTimeout(builder.connectTimeout)
            .sessionTimeout(builder.sessionTimeout).build();
}

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

/**
 * Creates a TTheadPoolServer for normal unsecure operation. Useful for comparing performance against SSL or SASL transports.
 *
 * @param address/*w  w  w .j a  v a2s .c om*/
 *          Address to bind to
 * @param processor
 *          TProcessor for the server
 * @param maxMessageSize
 *          Maximum size of a Thrift message allowed
 * @return A configured TThreadPoolServer and its bound address information
 */
public static ServerAddress createBlockingServer(HostAndPort address, TProcessor processor,
        TProtocolFactory protocolFactory, long maxMessageSize, String serverName, int numThreads,
        int numSimpleTimerThreads, long timeBetweenThreadChecks) throws TTransportException {

    TServerSocket transport = new TServerSocket(address.getPort());
    ThreadPoolExecutor pool = createSelfResizingThreadPool(serverName, numThreads, numSimpleTimerThreads,
            timeBetweenThreadChecks);
    TThreadPoolServer server = createTThreadPoolServer(transport, processor,
            ThriftUtil.transportFactory(maxMessageSize), protocolFactory, pool);

    if (address.getPort() == 0) {
        address = HostAndPort.fromParts(address.getHostText(), transport.getServerSocket().getLocalPort());
    }

    return new ServerAddress(server, address);

}

From source file:io.mandrel.transport.thrift.nifty.ThriftClientManager.java

/**
 * Returns the remote address that a Swift client is connected to
 *
 * @throws IllegalArgumentException// w  w w . jav  a2  s  .  c  om
 *             if the client is not a Swift client or is not connected
 *             through an internet socket
 */
public HostAndPort getRemoteAddress(Object client) {
    NiftyClientChannel niftyChannel = getNiftyChannel(client);

    try {
        Channel nettyChannel = niftyChannel.getNettyChannel();
        SocketAddress address = nettyChannel.getRemoteAddress();
        InetSocketAddress inetAddress = (InetSocketAddress) address;
        return HostAndPort.fromParts(inetAddress.getHostString(), inetAddress.getPort());
    } catch (NullPointerException | ClassCastException e) {
        throw new IllegalArgumentException("Invalid swift client object", e);
    }
}

From source file:me.itzg.testing.DockerRule.java

/**
 * Obtains the access information for the requested containerPort but in the form of a Guava
 * {@link HostAndPort} which makes it easy to create "host:port" references.
 *
 * @param containerPort the port to locate according to the <code>EXPOSE</code>d/internal container port
 * @return a socket address populated with
 * @throws DockerException      if an issue occurred containing the Docker daemon
 * @throws InterruptedException if interrupted while contacting the Docker daemon
 *//*  ww w .  j  av  a  2  s . c  o  m*/
public HostAndPort getHostAndPort(int containerPort) throws DockerException, InterruptedException {
    final InetSocketAddress socketAddress = getAccessToPort(containerPort);

    return HostAndPort.fromParts(socketAddress.getHostName(), socketAddress.getPort());
}

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

public static ServerAddress createSslThreadPoolServer(HostAndPort address, TProcessor processor,
        long socketTimeout, SslConnectionParams sslParams) throws TTransportException {
    org.apache.thrift.transport.TServerSocket transport;
    try {/*  w w  w  .j av a  2  s  .  co  m*/
        transport = ThriftUtil.getServerSocket(address.getPort(), (int) socketTimeout,
                InetAddress.getByName(address.getHostText()), sslParams);
    } catch (UnknownHostException e) {
        throw new TTransportException(e);
    }
    if (address.getPort() == 0) {
        address = HostAndPort.fromParts(address.getHostText(), transport.getServerSocket().getLocalPort());
    }
    return new ServerAddress(createThreadPoolServer(transport, processor), address);
}

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

/**
 * Returns the hosts and ports that should be considered when determining the address
 * to use when connecting to the location by assessing the following criteria:
 * <ol>/*from   ww  w  .jav  a2  s. c om*/
 *     <li>Use the hostAndPortOverride set in options.</li>
 *     <li>If the machine is connectable, user credentials are given and the machine is provisioned
 *     in AWS then use {@link JcloudsLocation#getHostnameAws(NodeMetadata, Optional, Supplier, ConfigBag)}.</li>
 *     <li>If the machine is connectable and pollForFirstReachableAddress is set in options then use all
 *     {@link #getReachableAddresses reachable} addresses.</li>
 *     <li>Use the first address that is resolvable with {@link #isAddressResolvable}.</li>
 *     <li>Use the first address in the node's public then private addresses.</li>
 * </ol>
 */
protected Iterable<HostAndPort> getManagementCandidates(JcloudsLocation location, NodeMetadata node,
        ConfigBag config, ConnectivityResolverOptions options) {
    final Optional<HostAndPort> portForwardSshOverride = options.portForwardSshOverride();

    if (portForwardSshOverride.isPresent()) {
        // Don't try to resolve it; just use it
        int port = portForwardSshOverride.get().hasPort() ? portForwardSshOverride.get().getPort()
                : options.defaultLoginPort();
        final HostAndPort override = HostAndPort.fromParts(portForwardSshOverride.get().getHostText(), port);
        switch (getNetworkMode()) {
        case ONLY_PRIVATE:
            LOG.info(
                    "Ignoring mode {} in favour of port forwarding override for management candidates of {}: {}",
                    new Object[] { NetworkMode.ONLY_PRIVATE.name(), location, override });
            break;
        default:
            LOG.debug("Using host and port override for management candidates of {}: {}", location, override);
        }
        return ImmutableList.of(override);
    }

    if (options.pollForReachableAddresses() && options.reachableAddressPredicate() != null) {
        LOG.debug("Using reachable addresses for management candidates of {}", location);
        try {
            final Predicate<? super HostAndPort> predicate = options.reachableAddressPredicate();
            return getReachableAddresses(node, predicate, options.reachableAddressTimeout());
        } catch (RuntimeException e) {
            if (options.propagatePollForReachableFailure()) {
                throw Exceptions.propagate(e);
            } else {
                LOG.warn(
                        "No reachable address ({}/{}); falling back to any advertised address; may cause future failures",
                        location.getCreationString(config), node);
            }
        }
    } else if (options.pollForReachableAddresses()) {
        throw new IllegalStateException(this + " was configured to expect " + node + " to be reachable "
                + "and to poll for its reachable addresses but the predicate to determine reachability was null");
    }

    Iterable<String> addresses = getResolvableAddressesWithMode(node);
    LOG.debug("Using first resolvable address in {} for management candidates of {}",
            Iterables.toString(addresses), location);
    for (String address : addresses) {
        if (isAddressResolvable(address)) {
            return ImmutableList.of(HostAndPort.fromParts(address, options.defaultLoginPort()));
        } else {
            LOG.debug("Unresolvable address: " + address);
        }
    }

    LOG.warn("No resolvable address in {} ({}/{}); using first; may cause future failures",
            new Object[] { addresses, location.getCreationString(config), node });
    String host = Iterables.getFirst(addresses, null);
    if (host != null) {
        return ImmutableList.of(HostAndPort.fromParts(host, options.defaultLoginPort()));
    } else {
        return ImmutableList.of();
    }
}

From source file:com.spotify.folsom.MemcacheClientBuilder.java

/**
 * Connect a raw memcached client without any protocol specific methods.
 * This should rarely be needed.//from ww  w.  ja  v a  2 s .  c  om
 * @param binary whether to use the binary protocol or not.
 * @return A raw memcached client.
 */
protected RawMemcacheClient connectRaw(boolean binary) {
    List<HostAndPort> addresses = this.addresses;
    RawMemcacheClient client;
    if (srvRecord != null) {
        if (addresses != null) {
            throw new IllegalStateException("You may not specify both srvRecord and addresses");
        }
        client = createSRVClient(binary);
    } else {
        if (addresses == null) {
            addresses = ImmutableList.of(HostAndPort.fromParts(DEFAULT_HOSTNAME, DEFAULT_PORT));
        }

        final List<RawMemcacheClient> clients = createClients(addresses, binary);
        if (addresses.size() > 1) {
            checkState(clients.size() == addresses.size());

            final List<AddressAndClient> aac = Lists.newArrayListWithCapacity(clients.size());
            for (int i = 0; i < clients.size(); i++) {
                final HostAndPort address = addresses.get(i);
                aac.add(new AddressAndClient(address, clients.get(i)));
            }

            client = new KetamaMemcacheClient(aac);
        } else {
            client = clients.get(0);
        }
    }

    if (retry) {
        return new RetryingClient(client);
    }
    return client;
}

From source file:org.jclouds.gogrid.GoGridLiveTestDisabled.java

@Test(enabled = true)
public void testShellAccess() throws IOException {
    final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6);
    serversToDeleteAfterTheTests.add(nameOfServer);

    Set<Ip> availableIps = api.getIpServices().getUnassignedIpList();
    Ip availableIp = Iterables.getLast(availableIps);

    Server createdServer = api.getServerServices().addServer(nameOfServer,
            "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", "1", availableIp.getIp());
    assertNotNull(createdServer);//from w w w  .  j  a va 2  s.  c  om
    assert serverLatestJobCompleted.apply(createdServer);

    // get server by name
    Set<Server> response = api.getServerServices().getServersByName(nameOfServer);
    assert (response.size() == 1);
    createdServer = Iterables.getOnlyElement(response);

    Map<String, Credentials> credsMap = api.getServerServices().getServerCredentialsList();
    LoginCredentials instanceCredentials = LoginCredentials
            .fromCredentials(credsMap.get(createdServer.getName()));
    assertNotNull(instanceCredentials);

    HostAndPort socket = HostAndPort.fromParts(createdServer.getIp().getIp(), 22);
    SocketOpen socketOpen = Guice.createInjector().getInstance(SocketOpen.class);
    Predicate<HostAndPort> socketTester = retry(socketOpen, 180, 5, SECONDS);
    socketTester.apply(socket);

    // check that the get credentials call is the same as this
    assertEquals(api.getServerServices().getServerCredentials(createdServer.getId()), instanceCredentials);

    try {
        assertEquals(api.getServerServices().getServerCredentials(Long.MAX_VALUE), null);
    } catch (AssertionError e) {
        e.printStackTrace();
    }

    // delete the server
    api.getServerServices().deleteByName(nameOfServer);
}

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/*from w ww. j  a  v a  2 s  .  c  om*/
                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:org.apache.accumulo.server.util.TServerUtils.java

public static ServerAddress startTServer(HostAndPort address, TimedProcessor processor, String serverName,
        String threadName, int numThreads, long timeBetweenThreadChecks, long maxMessageSize,
        SslConnectionParams sslParams, long sslSocketTimeout) throws TTransportException {

    ServerAddress serverAddress;//from   w w w  .ja  v  a  2s .  c  om
    if (sslParams != null) {
        serverAddress = createSslThreadPoolServer(address, processor, sslSocketTimeout, sslParams);
    } else {
        serverAddress = createHsHaServer(address, processor, serverName, threadName, numThreads,
                timeBetweenThreadChecks, maxMessageSize);
    }
    final TServer finalServer = serverAddress.server;
    Runnable serveTask = new Runnable() {
        @Override
        public void run() {
            try {
                finalServer.serve();
            } catch (Error e) {
                Halt.halt("Unexpected error in TThreadPoolServer " + e + ", halting.");
            }
        }
    };
    serveTask = new LoggingRunnable(TServerUtils.log, serveTask);
    Thread thread = new Daemon(serveTask, threadName);
    thread.start();
    // check for the special "bind to everything address"
    if (serverAddress.address.getHostText().equals("0.0.0.0")) {
        // can't get the address from the bind, so we'll do our best to invent our hostname
        try {
            serverAddress = new ServerAddress(finalServer, HostAndPort
                    .fromParts(InetAddress.getLocalHost().getHostName(), serverAddress.address.getPort()));
        } catch (UnknownHostException e) {
            throw new TTransportException(e);
        }
    }
    return serverAddress;
}