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

@Override
public void openPortForwardingAndAdvertise(final EntityAndAttribute<Integer> source,
        final Optional<Integer> optionalPublicPort, final Protocol protocol, final Cidr accessingCidr,
        final EntityAndAttribute<String> whereToAdvertiseEndpoint) {
    Advertiser advertiser = new Advertiser() {
        @Override/*from  www . j  a  va  2 s . co m*/
        public void advertise(EntityAndAttribute<Integer> source, HostAndPort publicEndpoint) {
            String endpoint = publicEndpoint.getHostText() + ":" + publicEndpoint.getPort();
            whereToAdvertiseEndpoint.setValue(endpoint);
        }
    };
    doOpenPortForwardingAndAdvertise(source, optionalPublicPort, protocol, accessingCidr, advertiser);
}

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

protected boolean systemCreatePortForwarding(HostAndPort publicSide, HostAndPort targetSide, Cidr cidr) {
    checkNotNull(publicSide, "publicSide");
    checkArgument(publicSide.getHostText().equals(forwarderIp), "publicSide %s should match forwarderIp %s",
            publicSide, forwarderIp);//  w  w w  .  j av  a 2 s  .  c  o m
    checkNotNull(targetSide, "targetSide");

    try {
        List<String> commands = ImmutableList.of(
                sudo(String.format(
                        "/sbin/iptables -t nat -I PREROUTING -p tcp --dport %s -j DNAT --to-destination %s:%s",
                        publicSide.getPort(), targetSide.getHostText(), targetSide.getPort())),
                sudo("/sbin/iptables -t nat -I POSTROUTING -j MASQUERADE"),
                IptablesCommands.saveIptablesRules()); // note save already wrapped in sudo

        int result = forwarderMachine.execScript("port-forwarding " + publicSide + "->" + targetSide, commands);

        boolean opened = systemOpenFirewall(publicSide.getHostText(), publicSide.getPort(),
                publicSide.getPort(), Protocol.TCP, cidr);
        // targetPort doesn't need to be opened - assuming both on internal network, and already opened

        if (result != 0) {
            log.error("Failed creating port forwarding rule on {}: {} -> {}",
                    new Object[] { this, publicSide, targetSide });
            // it might already be created, so don't crash and burn too hard!
            return false;
        }
        if (!opened) {
            log.error("Failed opening forwarding port on {}: {} -> {}",
                    new Object[] { this, publicSide, targetSide });
            // it might already be created, so don't crash and burn too hard!
            return false;
        }
    } catch (Exception e) {
        log.error("Failed creating port forwarding rule on {}: {} -> {}",
                new Object[] { this, publicSide, targetSide });
        // it might already be created, so don't crash and burn too hard!
        return false;
    }

    return true;
}

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

/**
 * Create a TTransport for clients to the given address with the provided socket timeout and session-layer configuration
 *
 * @param address/*from w  w  w .j  a  v  a2  s .c o m*/
 *          Server address to connect to
 * @param timeout
 *          Client socket timeout
 * @param sslParams
 *          RPC options for SSL servers
 * @param saslParams
 *          RPC options for SASL servers
 * @return An open TTransport which must be closed when finished
 */
public static TTransport createClientTransport(HostAndPort address, int timeout, SslConnectionParams sslParams,
        SaslConnectionParams saslParams) throws TTransportException {
    boolean success = false;
    TTransport transport = null;
    try {
        if (sslParams != null) {
            // The check in AccumuloServerContext ensures that servers are brought up with sane configurations, but we also want to validate clients
            if (null != saslParams) {
                throw new IllegalStateException("Cannot use both SSL and SASL");
            }

            log.trace("Creating SSL client transport");

            // TSSLTransportFactory handles timeout 0 -> forever natively
            if (sslParams.useJsse()) {
                transport = TSSLTransportFactory.getClientSocket(address.getHostText(), address.getPort(),
                        timeout);
            } else {
                // JDK6's factory doesn't appear to pass the protocol onto the Socket properly so we have
                // to do some magic to make sure that happens. Not an issue in JDK7

                // Taken from thrift-0.9.1 to make the SSLContext
                SSLContext sslContext = createSSLContext(sslParams);

                // Create the factory from it
                SSLSocketFactory sslSockFactory = sslContext.getSocketFactory();

                // Wrap the real factory with our own that will set the protocol on the Socket before returning it
                ProtocolOverridingSSLSocketFactory wrappingSslSockFactory = new ProtocolOverridingSSLSocketFactory(
                        sslSockFactory, new String[] { sslParams.getClientProtocol() });

                // Create the TSocket from that
                transport = createClient(wrappingSslSockFactory, address.getHostText(), address.getPort(),
                        timeout);
                // TSSLTransportFactory leaves transports open, so no need to open here
            }

            transport = ThriftUtil.transportFactory().getTransport(transport);
        } else if (null != saslParams) {
            if (!UserGroupInformation.isSecurityEnabled()) {
                throw new IllegalStateException("Expected Kerberos security to be enabled if SASL is in use");
            }

            log.trace("Creating SASL connection to {}:{}", address.getHostText(), address.getPort());

            // Make sure a timeout is set
            try {
                transport = TTimeoutTransport.create(address, timeout);
            } catch (IOException e) {
                log.warn("Failed to open transport to {}", address);
                throw new TTransportException(e);
            }

            try {
                // Log in via UGI, ensures we have logged in with our KRB credentials
                final UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();

                // Is this pricey enough that we want to cache it?
                final String hostname = InetAddress.getByName(address.getHostText()).getCanonicalHostName();

                final SaslMechanism mechanism = saslParams.getMechanism();

                log.trace("Opening transport to server as {} to {}/{} using {}", currentUser,
                        saslParams.getKerberosServerPrimary(), hostname, mechanism);

                // Create the client SASL transport using the information for the server
                // Despite the 'protocol' argument seeming to be useless, it *must* be the primary of the server being connected to
                transport = new TSaslClientTransport(mechanism.getMechanismName(), null,
                        saslParams.getKerberosServerPrimary(), hostname, saslParams.getSaslProperties(),
                        saslParams.getCallbackHandler(), transport);

                // Wrap it all in a processor which will run with a doAs the current user
                transport = new UGIAssumingTransport(transport, currentUser);

                // Open the transport
                transport.open();
            } catch (TTransportException e) {
                log.warn("Failed to open SASL transport", e);

                // We might have had a valid ticket, but it expired. We'll let the caller retry, but we will attempt to re-login to make the next attempt work.
                // Sadly, we have no way to determine the actual reason we got this TTransportException other than inspecting the exception msg.
                log.debug(
                        "Caught TTransportException opening SASL transport, checking if re-login is necessary before propagating the exception.");
                attemptClientReLogin();

                throw e;
            } catch (IOException e) {
                log.warn("Failed to open SASL transport", e);
                throw new TTransportException(e);
            }
        } else {
            log.trace("Opening normal transport");
            if (timeout == 0) {
                transport = new TSocket(address.getHostText(), address.getPort());
                transport.open();
            } else {
                try {
                    transport = TTimeoutTransport.create(address, timeout);
                } catch (IOException ex) {
                    log.warn("Failed to open transport to " + address);
                    throw new TTransportException(ex);
                }

                // Open the transport
                transport.open();
            }
            transport = ThriftUtil.transportFactory().getTransport(transport);
        }
        success = true;
    } finally {
        if (!success && transport != null) {
            transport.close();
        }
    }
    return transport;
}

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

@Deprecated
public List<ServerAddress> getReplicaSet() {
    if (replicaSet == null || replicaSet.isEmpty()) {
        return null;
    }/*from w  w  w  .  ja va  2  s  . co  m*/

    final List<ServerAddress> replicaServers = new ArrayList<>(replicaSet.size());
    for (String host : replicaSet) {
        try {
            final HostAndPort hostAndPort = HostAndPort.fromString(host).withDefaultPort(27017);
            replicaServers.add(
                    new ServerAddress(InetAddress.getByName(hostAndPort.getHostText()), hostAndPort.getPort()));
        } catch (IllegalArgumentException e) {
            LOG.error("Malformed mongodb_replica_set configuration.", e);
            return null;
        } catch (UnknownHostException e) {
            LOG.error("Unknown host in mongodb_replica_set", e);
            return null;
        }
    }

    return replicaServers;
}

From source file:com.spotify.docker.client.DockerHost.java

private DockerHost(final String endpoint, final String certPath) {
    if (endpoint.startsWith("unix://")) {
        this.port = 0;
        this.address = DEFAULT_ADDRESS;
        this.host = endpoint;
        this.uri = URI.create(endpoint);
        this.bindUri = URI.create(endpoint);
    } else {/*from w ww.j a va2  s . c om*/
        final String stripped = endpoint.replaceAll(".*://", "");
        final HostAndPort hostAndPort = HostAndPort.fromString(stripped);
        final String hostText = hostAndPort.getHostText();
        final String scheme = isNullOrEmpty(certPath) ? "http" : "https";

        this.port = hostAndPort.getPortOrDefault(defaultPort());
        this.address = isNullOrEmpty(hostText) ? DEFAULT_ADDRESS : hostText;
        this.host = address + ":" + port;
        this.uri = URI.create(scheme + "://" + address + ":" + port);
        this.bindUri = URI.create("tcp://" + address + ":" + port);
    }

    this.certPath = certPath;
}

From source file:org.graylog2.logback.appender.Graylog2Plugin.java

public Graylog2Plugin(Application app) {
    final Configuration config = app.configuration();
    this.pluginEnabled = config.getBoolean("graylog2.enable.plugin", false);
    if (!this.pluginEnabled) {
        return;//from w ww.j av  a 2  s  .c  o  m
    }
    accessLogEnabled = config.getBoolean("graylog2.appender.send-access-log", false);
    queueCapacity = config.getInt("graylog2.appender.queue-size", 512);
    reconnectInterval = config.getMilliseconds("graylog2.appender.reconnect-interval", 500L);
    connectTimeout = config.getMilliseconds("graylog2.appender.connect-timeout", 1000L);
    isTcpNoDelay = config.getBoolean("graylog2.appender.tcp-nodelay", false);
    sendBufferSize = config.getInt("graylog2.appender.sendbuffersize", 0); // causes the socket default to be used
    try {
        canonicalHostName = config.getString("graylog2.appender.sourcehost",
                InetAddress.getLocalHost().getCanonicalHostName());
    } catch (UnknownHostException e) {
        canonicalHostName = "localhost";
        log.error("Unable to resolve canonical localhost name. "
                + "Please set it manually via graylog2.appender.sourcehost or fix your lookup service, falling back to {}",
                canonicalHostName);
    }
    // TODO make this a list and dynamically accessible from the application
    final String hostString = config.getString("graylog2.appender.host", "127.0.0.1:12201");
    final String protocol = config.getString("graylog2.appender.protocol", "tcp");

    final HostAndPort hostAndPort = HostAndPort.fromString(hostString);

    final GelfTransports gelfTransport = GelfTransports.valueOf(protocol.toUpperCase());

    final GelfConfiguration gelfConfiguration = new GelfConfiguration(hostAndPort.getHostText(),
            hostAndPort.getPort()).transport(gelfTransport).reconnectDelay(reconnectInterval.intValue())
                    .queueSize(queueCapacity).connectTimeout(connectTimeout.intValue()).tcpNoDelay(isTcpNoDelay)
                    .sendBufferSize(sendBufferSize);

    this.transport = GelfTransports.create(gelfConfiguration);

    final LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
    rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME);

    gelfAppender = new GelfclientAppender(transport, getLocalHostName());
    gelfAppender.setContext(lc);
}

From source file:com.stratio.ingestion.sink.cassandra.CassandraSink.java

@Override
public void configure(Context context) {
    contactPoints = new ArrayList<InetSocketAddress>();
    final String hosts = context.getString(CONF_HOSTS, DEFAULT_HOST);
    for (final String host : Splitter.on(',').split(hosts)) {
        try {//  ww w  . jav a2  s  .c  o m
            final HostAndPort hostAndPort = HostAndPort.fromString(host).withDefaultPort(DEFAULT_PORT);
            contactPoints.add(new InetSocketAddress(hostAndPort.getHostText(), hostAndPort.getPort()));
        } catch (IllegalArgumentException ex) {
            throw new ConfigurationException("Could not parse host: " + host, ex);
        }
    }

    this.username = context.getString(CONF_USERNAME);
    this.password = context.getString(CONF_PASSWORD);
    this.consistency = context.getString(CONF_CONSISTENCY_LEVEL, DEFAULT_CONSISTENCY_LEVEL);
    this.bodyColumn = context.getString(CONF_BODY_COLUMN, DEFAULT_BODY_COLUMN);

    final String tablesString = StringUtils.trimToNull(context.getString(CONF_TABLES));
    if (tablesString == null) {
        throw new ConfigurationException(String.format("%s is mandatory", CONF_TABLES));
    }
    this.tableStrings = Arrays.asList(tablesString.split(","));

    final String cqlFile = StringUtils.trimToNull(context.getString(CONF_CQL_FILE));
    if (cqlFile != null) {
        try {
            this.initCql = IOUtils.toString(new FileInputStream(cqlFile));
        } catch (IOException ex) {
            throw new ConfigurationException("Cannot read CQL file: " + cqlFile, ex);
        }
    }

    this.batchSize = context.getInteger(CONF_BATCH_SIZE, DEFAULT_BATCH_SIZE);
    this.sinkCounter = new SinkCounter(this.getName());
}

From source file:com.github.jcustenborder.kafka.connect.utils.config.validators.ValidHostAndPort.java

void validate(final String setting, final String input) {
    HostAndPort hostAndPort = HostAndPort.fromString(input);
    if (this.requireBracketsForIPv6) {
        hostAndPort = hostAndPort.requireBracketsForIPv6();
    }/*from   ww  w.ja v  a2  s. co m*/
    if (null != this.defaultPort) {
        hostAndPort.withDefaultPort(this.defaultPort);
    }

    if (Strings.isNullOrEmpty(hostAndPort.getHostText())) {
        throw new ConfigException(String.format("'%s'(%s) host cannot be blank or null.", setting, input));
    }

    if (this.portRequired && !hostAndPort.hasPort()) {
        throw new ConfigException(String.format("'%s'(%s) must specify a port.", setting, input));
    }

}

From source file:com.basho.riak.presto.RiakClient.java

@Inject
public RiakClient(RiakConfig config, ObjectMapper objectMapper) //}, JsonCodec<Map<String, List<PRTable>>> catalogCodec)
        throws IOException, InterruptedException {
    this.config = checkNotNull(config, "config is null");
    this.objectMapper = checkNotNull(objectMapper, "om is null");

    this.hosts = checkNotNull(config.getHost());
    log.info("Riak Config: %s", hosts);

    HostAndPort hp = HostAndPort.fromString(hosts);

    RiakNode node = new RiakNode.Builder().withRemoteAddress(hp.getHostText())
            .withRemotePort(hp.getPortOrDefault(config.getPort())).withMaxConnections(10)
            .withConnectionTimeout(CONNECTION_TIMEOUT_MIL).build();
    cluster = RiakCluster.builder(Arrays.asList(node)).build();

    //final String hosts = config.getHosts();
    this.schemas = Arrays.asList("md", "t");
    //String json = Resources.toString(metadataUri.toURL(), Charsets.UTF_8);
    //Map<String, List<PRTable>> catalog = catalogCodec.fromJson(json);
    //this.schemas = ImmutableMap.copyOf(transformValues(catalog, resolveAndIndexTables(metadataUri)));
    cluster.start();// w w  w  .  ja va 2s. c  o  m
    // insert your names;
    // TODO: how do we unregister when presto node shuts down?
    // register();
}

From source file:com.lambdaworks.redis.cluster.models.slots.ClusterSlotRange.java

private RedisClusterNode toRedisClusterNode(HostAndPort hostAndPort, String slaveOf,
        Set<RedisClusterNode.NodeFlag> flags) {
    RedisClusterNode redisClusterNode = new RedisClusterNode();
    redisClusterNode.setUri(RedisURI.create(hostAndPort.getHostText(),
            hostAndPort.getPortOrDefault(RedisURI.DEFAULT_REDIS_PORT)));
    redisClusterNode.setSlaveOf(slaveOf);
    redisClusterNode.setFlags(flags);/*from  w  w w .  j  ava  2  s .  c  o m*/
    return redisClusterNode;
}