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.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   www.j a v  a2 s.  com*/
    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: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.
 *///from   ww w. j  av  a  2  s.com
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.rpc.TServerUtils.java

/**
 * Creates a TTheadPoolServer for normal unsecure operation. Useful for comparing performance against SSL or SASL transports.
 *
 * @param address//from w ww  . jav  a  2s  .  c o  m
 *          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:ezbake.thrift.ThriftUtils.java

protected static TTransport getTransport(Properties configuration, HostAndPort hostAndPort, String securityId,
        TTransportFactory transportFactory) throws TTransportException {
    TTransport transport;//from   w ww . j  a v a2s.c o  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.accumulo.server.rpc.TServerUtils.java

/**
 * Create a Thrift SSL server./* w  w w .j  ava2s .com*/
 *
 * @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);
}

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 . ja va2s.c om
        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  a va2s  .c  o  m
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:com.facebook.nifty.client.AbstractClientConnector.java

public AbstractClientConnector(HostAndPort address) {
    this(new InetSocketAddress(address.getHostText(), address.getPort()));
}

From source file:com.streamsets.pipeline.destination.aerospike.AerospikeValidationUtil.java

public List<Host> validateConnectionString(List<Stage.ConfigIssue> issues, String connectionString,
        String configGroupName, String configName, Stage.Context context) {
    List<Host> clusterNodesList = new ArrayList<>();
    if (connectionString == null || connectionString.isEmpty()) {
        issues.add(context.createConfigIssue(configGroupName, configName, AerospikeErrors.AEROSPIKE_01,
                configName));//from  w ww.  ja  v a  2s  .  c o m
    } else {
        String[] nodes = connectionString.split(",");
        for (String node : nodes) {
            try {
                HostAndPort hostAndPort = HostAndPort.fromString(node);
                if (!hostAndPort.hasPort() || hostAndPort.getPort() < 0) {
                    issues.add(context.createConfigIssue(configGroupName, configName,
                            AerospikeErrors.AEROSPIKE_02, connectionString));
                } else {
                    clusterNodesList.add(new Host(hostAndPort.getHostText(), hostAndPort.getPort()));
                }
            } catch (IllegalArgumentException e) {
                issues.add(context.createConfigIssue(configGroupName, configName, AerospikeErrors.AEROSPIKE_02,
                        connectionString));
            }
        }
    }
    return clusterNodesList;
}

From source file:com.bazaarvoice.dropwizard.caching.memcached.MemcachedResponseStoreFactory.java

/**
 * InetSocketAddress deserialization is broken in jackson 2.3.3, so using HostAndPort instead.
 * See: https://github.com/FasterXML/jackson-databind/issues/444
 * Fix will be in 2.3.4, but not released yet (as of 2014-Jul-10).
 *//*  ww  w .  ja  v a 2  s  .c  om*/
@JsonProperty
void setServers(HostAndPort[] servers) {
    checkNotNull(servers);

    _servers = FluentIterable.from(Arrays.asList(servers))
            .transform(new Function<HostAndPort, InetSocketAddress>() {
                public InetSocketAddress apply(HostAndPort input) {
                    return new InetSocketAddress(input.getHostText(), input.getPort());
                }
            }).toList();
}