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:com.torodb.mongodb.commands.pojos.ReplicaSetConfig.java

private static final boolean isLocalhost(HostAndPort hostAndPort) {
    String host = hostAndPort.getHostText();
    return host.equals("localhost") || host.startsWith("127.") || host.equals("::1")
            || host.equals("anonymous unix socket") || host.charAt(0) == '/'; // unix socket
}

From source file:org.apache.accumulo.core.util.ThriftUtil.java

public static TTransport createClientTransport(HostAndPort address, int timeout, SslConnectionParams sslParams)
        throws TTransportException {
    boolean success = false;
    TTransport transport = null;//from w  w  w .  j av a2s . c om
    try {
        if (sslParams != null) {
            // TSSLTransportFactory handles timeout 0 -> forever natively
            if (sslParams.useJsse()) {
                transport = TSSLTransportFactory.getClientSocket(address.getHostText(), address.getPort(),
                        timeout);
            } else {
                transport = TSSLTransportFactory.getClientSocket(address.getHostText(), address.getPort(),
                        timeout, sslParams.getTTransportParams());
            }
            // TSSLTransportFactory leaves transports open, so no need to open here
        } else if (timeout == 0) {
            transport = new TSocket(address.getHostText(), address.getPort());
            transport.open();
        } else {
            try {
                transport = TTimeoutTransport.create(address, timeout);
            } catch (IOException ex) {
                throw new TTransportException(ex);
            }
            transport.open();
        }
        transport = ThriftUtil.transportFactory().getTransport(transport);
        success = true;
    } finally {
        if (!success && transport != null) {
            transport.close();
        }
    }
    return transport;
}

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 {/*from  w w w. j  a va2s .  c  om*/
        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.accumulo.server.util.TServerUtils.java

public static ServerAddress createHsHaServer(HostAndPort address, TProcessor processor, final String serverName,
        String threadName, final int numThreads, long timeBetweenThreadChecks, long maxMessageSize)
        throws TTransportException {
    TNonblockingServerSocket transport = new TNonblockingServerSocket(
            new InetSocketAddress(address.getHostText(), address.getPort()));
    THsHaServer.Args options = new THsHaServer.Args(transport);
    options.protocolFactory(ThriftUtil.protocolFactory());
    options.transportFactory(ThriftUtil.transportFactory(maxMessageSize));
    options.maxReadBufferBytes = maxMessageSize;
    options.stopTimeoutVal(5);//from   w  ww  .  j  ava2 s  .  c  o  m
    /*
     * Create our own very special thread pool.
     */
    final ThreadPoolExecutor pool = new SimpleThreadPool(numThreads, "ClientPool");
    // periodically adjust the number of threads we need by checking how busy our threads are
    SimpleTimer.getInstance().schedule(new Runnable() {
        @Override
        public void run() {
            if (pool.getCorePoolSize() <= pool.getActiveCount()) {
                int larger = pool.getCorePoolSize() + Math.min(pool.getQueue().size(), 2);
                log.info("Increasing server thread pool size on " + serverName + " to " + larger);
                pool.setMaximumPoolSize(larger);
                pool.setCorePoolSize(larger);
            } else {
                if (pool.getCorePoolSize() > pool.getActiveCount() + 3) {
                    int smaller = Math.max(numThreads, pool.getCorePoolSize() - 1);
                    if (smaller != pool.getCorePoolSize()) {
                        // there is a race condition here... the active count could be higher by the time
                        // we decrease the core pool size... so the active count could end up higher than
                        // the core pool size, in which case everything will be queued... the increase case
                        // should handle this and prevent deadlock
                        log.info("Decreasing server thread pool size on " + serverName + " to " + smaller);
                        pool.setCorePoolSize(smaller);
                    }
                }
            }
        }
    }, timeBetweenThreadChecks, timeBetweenThreadChecks);
    options.executorService(pool);
    options.processorFactory(new TProcessorFactory(processor));
    if (address.getPort() == 0) {
        address = HostAndPort.fromParts(address.getHostText(), transport.getPort());
    }
    return new ServerAddress(new THsHaServer(options), address);
}

From source file:co.cask.cdap.explore.security.JobHistoryServerTokenUtils.java

/**
 * Gets a JHS delegation token and stores it in the given Credentials.
 *
 * @return the same Credentials instance as the one given in parameter.
 *//* www  .  j  a  v  a  2s  .  c om*/
public static Credentials obtainToken(Configuration configuration, Credentials credentials) {
    if (!UserGroupInformation.isSecurityEnabled()) {
        return credentials;
    }

    String historyServerAddress = configuration.get("mapreduce.jobhistory.address");
    HostAndPort hostAndPort = HostAndPort.fromString(historyServerAddress);
    try {
        LOG.info("Obtaining delegation token for JHS");

        ResourceMgrDelegate resourceMgrDelegate = new ResourceMgrDelegate(new YarnConfiguration(configuration));
        MRClientCache clientCache = new MRClientCache(configuration, resourceMgrDelegate);
        MRClientProtocol hsProxy = clientCache.getInitializedHSProxy();
        GetDelegationTokenRequest request = new GetDelegationTokenRequestPBImpl();
        request.setRenewer(YarnUtils.getYarnTokenRenewer(configuration));

        InetSocketAddress address = new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort());
        Token<TokenIdentifier> token = ConverterUtils
                .convertFromYarn(hsProxy.getDelegationToken(request).getDelegationToken(), address);

        credentials.addToken(new Text(token.getService()), token);
        return credentials;
    } catch (Exception e) {
        LOG.error("Failed to get secure token for JHS at {}.", hostAndPort, e);
        throw Throwables.propagate(e);
    }
}

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

public static ServerAddress createThreadPoolServer(HostAndPort address, TProcessor processor, String serverName,
        String threadName, int numThreads) throws TTransportException {

    // if port is zero, then we must bind to get the port number
    ServerSocket sock;//from  w  ww.  ja va 2  s.  c om
    try {
        sock = ServerSocketChannel.open().socket();
        sock.setReuseAddress(true);
        sock.bind(new InetSocketAddress(address.getHostText(), address.getPort()));
        address = HostAndPort.fromParts(address.getHostText(), sock.getLocalPort());
    } catch (IOException ex) {
        throw new TTransportException(ex);
    }
    TServerTransport transport = new TBufferedServerSocket(sock, 32 * 1024);
    return new ServerAddress(createThreadPoolServer(transport, processor), address);
}

From source file:ezbake.thrift.ThriftUtils.java

protected static TTransport getTransport(Properties configuration, HostAndPort hostAndPort, String securityId,
        TTransportFactory transportFactory) throws TTransportException {
    TTransport transport;//w  w  w.j a  va  2  s  . co  m
    ThriftConfigurationHelper thriftConfiguration = new ThriftConfigurationHelper(configuration);

    logger.debug("getTransport for hostAndPort {}", hostAndPort);

    if (thriftConfiguration.getServerMode() == ThriftConfigurationHelper.ThriftServerMode.HsHa) {
        logger.debug("opening framed transport to {}", hostAndPort);
        transport = new TFramedTransport(new TSocket(hostAndPort.getHostText(), hostAndPort.getPort()));
    } else {
        if (thriftConfiguration.useSSL()) {
            logger.debug("opening SSL connection to {}", hostAndPort);
            transport = ThriftUtils.getSslClientSocket(hostAndPort.getHostText(), hostAndPort.getPort(),
                    configuration);
            transport = new EzSecureClientTransport(transport, configuration, securityId);
        } else {
            logger.debug("opening connection in the clear (without SSL) to {}", hostAndPort);
            transport = new TSocket(hostAndPort.getHostText(), hostAndPort.getPort());
        }
    }

    // Wrap the transport using the transportFactory (if provided)
    if (transportFactory != null) {
        transport = transportFactory.getTransport(transport);
    }

    return transport;
}

From source file:org.apache.brooklyn.util.net.Networking.java

public static boolean isReachable(HostAndPort endpoint) {
    // TODO Should we create an unconnected socket, and then use the calls below (see jclouds' InetSocketAddressConnect):
    //      socket.setReuseAddress(false);
    //      socket.setSoLinger(false, 1);
    //      socket.setSoTimeout(timeout);
    //      socket.connect(socketAddress, timeout);

    try {//from   w  ww . jav  a2s. c o m
        Socket s = new Socket(endpoint.getHostText(), endpoint.getPort());
        closeQuietly(s);
        return true;
    } catch (Exception e) {
        if (log.isTraceEnabled())
            log.trace("Error reaching " + endpoint + " during reachability check (return false)", e);
        return false;
    }
}

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

/**
 * Create a NonBlockingServer with a custom thread pool that can dynamically resize itself.
 *///from www .j  av  a  2 s.c om
public static ServerAddress createNonBlockingServer(HostAndPort address, TProcessor processor,
        TProtocolFactory protocolFactory, final String serverName, String threadName, final int numThreads,
        final int numSTThreads, long timeBetweenThreadChecks, long maxMessageSize) throws TTransportException {

    final TNonblockingServerSocket transport = new TNonblockingServerSocket(
            new InetSocketAddress(address.getHostText(), address.getPort()));
    final CustomNonBlockingServer.Args options = new CustomNonBlockingServer.Args(transport);

    options.protocolFactory(protocolFactory);
    options.transportFactory(ThriftUtil.transportFactory(maxMessageSize));
    options.maxReadBufferBytes = maxMessageSize;
    options.stopTimeoutVal(5);

    // Create our own very special thread pool.
    ThreadPoolExecutor pool = createSelfResizingThreadPool(serverName, numThreads, numSTThreads,
            timeBetweenThreadChecks);

    options.executorService(pool);
    options.processorFactory(new TProcessorFactory(processor));

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

    return new ServerAddress(new CustomNonBlockingServer(options), address);
}

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

/**
 * Create a Thrift SSL server.//w w w  .  j  ava  2 s  . c om
 *
 * @param address
 *          host and port to bind to
 * @param processor
 *          TProcessor for the server
 * @param socketTimeout
 *          Socket timeout
 * @param sslParams
 *          SSL parameters
 * @return A ServerAddress with the bound-socket information and the Thrift server
 */
public static ServerAddress createSslThreadPoolServer(HostAndPort address, TProcessor processor,
        TProtocolFactory protocolFactory, long socketTimeout, SslConnectionParams sslParams, String serverName,
        int numThreads, int numSimpleTimerThreads, long timeBetweenThreadChecks) throws TTransportException {
    TServerSocket transport;
    try {
        transport = getSslServerSocket(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());
    }

    ThreadPoolExecutor pool = createSelfResizingThreadPool(serverName, numThreads, numSimpleTimerThreads,
            timeBetweenThreadChecks);

    return new ServerAddress(
            createTThreadPoolServer(transport, processor, ThriftUtil.transportFactory(), protocolFactory, pool),
            address);
}