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.facebook.swift.service.ThriftClientManager.java

private InetSocketAddress toSocksProxyAddress(HostAndPort socksProxy) {
    if (socksProxy == null) {
        return null;
    }/*www.  j  a va  2s  . c  o  m*/
    return new InetSocketAddress(socksProxy.getHostText(), socksProxy.getPortOrDefault(SOCKS_DEFAULT_PORT));
}

From source file:com.google.cloud.GrpcServiceOptions.java

/**
 * Returns a channel provider./*from   w  w  w  .j ava 2 s . co m*/
 */
protected ChannelProvider getChannelProvider() {
    HostAndPort hostAndPort = HostAndPort.fromString(getHost());
    InstantiatingChannelProvider.Builder builder = InstantiatingChannelProvider.newBuilder()
            .setServiceAddress(hostAndPort.getHostText()).setPort(hostAndPort.getPort())
            .setClientLibHeader(getGoogApiClientLibName(), firstNonNull(getLibraryVersion(), ""));
    Credentials scopedCredentials = getScopedCredentials();
    if (scopedCredentials != null && scopedCredentials != NoCredentials.getInstance()) {
        builder.setCredentialsProvider(FixedCredentialsProvider.create(scopedCredentials));
    }
    return builder.build();
}

From source file:com.pinterest.secor.common.KafkaClient.java

public SimpleConsumer createConsumer(TopicPartition topicPartition) {
    HostAndPort leader = findLeader(topicPartition);
    LOG.info("leader for topic {} partition {} is {}", topicPartition.getTopic(), topicPartition.getPartition(),
            leader.toString());//from ww  w.ja v  a  2s. co  m
    final String clientName = getClientName(topicPartition);
    return createConsumer(leader.getHostText(), leader.getPort(), clientName);
}

From source file:org.apache.brooklyn.entity.nosql.mongodb.MongoDBServerImpl.java

@Override
protected void connectSensors() {
    super.connectSensors();
    connectServiceUpIsRunning();//from   w  w  w  . j  a v a 2 s .  c o  m

    int port = sensors().get(MongoDBServer.PORT);
    HostAndPort accessibleAddress = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port);
    sensors().set(MONGO_SERVER_ENDPOINT,
            String.format("%s:%d", accessibleAddress.getHostText(), accessibleAddress.getPort()));

    int httpConsolePort = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, sensors().get(HTTP_PORT))
            .getPort();
    sensors().set(HTTP_INTERFACE_URL,
            String.format("http://%s:%d", accessibleAddress.getHostText(), httpConsolePort));

    if (clientAccessEnabled()) {
        try {
            client = MongoDBClientSupport.forServer(this);
        } catch (UnknownHostException e) {
            LOG.warn("Unable to create client connection to {}, not connecting sensors: {} ", this,
                    e.getMessage());
            return;
        }

        serviceStats = FunctionFeed.builder().entity(this)
                .poll(new FunctionPollConfig<Object, BasicBSONObject>(STATUS_BSON).period(2, TimeUnit.SECONDS)
                        .callable(new Callable<BasicBSONObject>() {
                            @Override
                            public BasicBSONObject call() throws Exception {
                                return MongoDBServerImpl.this.sensors().get(SERVICE_UP)
                                        ? client.getServerStatus()
                                        : null;
                            }
                        }).onException(Functions.<BasicBSONObject>constant(null)))
                .build();

        if (isReplicaSetMember()) {
            replicaSetStats = FunctionFeed.builder().entity(this)
                    .poll(new FunctionPollConfig<Object, ReplicaSetMemberStatus>(REPLICA_SET_MEMBER_STATUS)
                            .period(2, TimeUnit.SECONDS).callable(new Callable<ReplicaSetMemberStatus>() {
                                /**
                                 * Calls {@link MongoDBClientSupport#getReplicaSetStatus} and
                                 * extracts <code>myState</code> from the response.
                                 * @return
                                 *      The appropriate {@link org.apache.brooklyn.entity.nosql.mongodb.ReplicaSetMemberStatus}
                                 *      if <code>myState</code> was non-null, {@link ReplicaSetMemberStatus#UNKNOWN} otherwise.
                                 */
                                @Override
                                public ReplicaSetMemberStatus call() {
                                    BasicBSONObject serverStatus = client.getReplicaSetStatus();
                                    int state = serverStatus.getInt("myState", -1);
                                    return ReplicaSetMemberStatus.fromCode(state);
                                }
                            }).onException(Functions.constant(ReplicaSetMemberStatus.UNKNOWN))
                            .suppressDuplicates(true))
                    .build();
        } else {
            sensors().set(IS_PRIMARY_FOR_REPLICA_SET, false);
            sensors().set(IS_SECONDARY_FOR_REPLICA_SET, false);
        }
    } else {
        LOG.info("Not monitoring " + this + " to retrieve state via client API");
    }

    // Take interesting details from STATUS.
    subscriptions().subscribe(this, STATUS_BSON, new SensorEventListener<BasicBSONObject>() {
        @Override
        public void onEvent(SensorEvent<BasicBSONObject> event) {
            BasicBSONObject map = event.getValue();
            if (map != null && !map.isEmpty()) {
                sensors().set(UPTIME_SECONDS, map.getDouble("uptime", 0));

                // Operations
                BasicBSONObject opcounters = (BasicBSONObject) map.get("opcounters");
                sensors().set(OPCOUNTERS_INSERTS, opcounters.getLong("insert", 0));
                sensors().set(OPCOUNTERS_QUERIES, opcounters.getLong("query", 0));
                sensors().set(OPCOUNTERS_UPDATES, opcounters.getLong("update", 0));
                sensors().set(OPCOUNTERS_DELETES, opcounters.getLong("delete", 0));
                sensors().set(OPCOUNTERS_GETMORE, opcounters.getLong("getmore", 0));
                sensors().set(OPCOUNTERS_COMMAND, opcounters.getLong("command", 0));

                // Network stats
                BasicBSONObject network = (BasicBSONObject) map.get("network");
                sensors().set(NETWORK_BYTES_IN, network.getLong("bytesIn", 0));
                sensors().set(NETWORK_BYTES_OUT, network.getLong("bytesOut", 0));
                sensors().set(NETWORK_NUM_REQUESTS, network.getLong("numRequests", 0));

                // Replica set stats
                BasicBSONObject repl = (BasicBSONObject) map.get("repl");
                if (isReplicaSetMember() && repl != null) {
                    sensors().set(IS_PRIMARY_FOR_REPLICA_SET, repl.getBoolean("ismaster"));
                    sensors().set(IS_SECONDARY_FOR_REPLICA_SET, repl.getBoolean("secondary"));
                    sensors().set(REPLICA_SET_PRIMARY_ENDPOINT, repl.getString("primary"));
                }
            }
        }
    });
}

From source file:brooklyn.entity.webapp.jboss.JBoss7ServerImpl.java

@Override
protected void connectSensors() {
    super.connectSensors();

    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this,
            getAttribute(MANAGEMENT_HTTP_PORT) + getConfig(PORT_INCREMENT));

    String managementUri = String.format("http://%s:%s/management/subsystem/web/connector/http/read-resource",
            hp.getHostText(), hp.getPort());
    setAttribute(MANAGEMENT_URL, managementUri);
    log.debug("JBoss sensors for " + this + " reading from " + managementUri);
    Map<String, String> includeRuntimeUriVars = ImmutableMap.of("include-runtime", "true");

    httpFeed = HttpFeed.builder().entity(this).period(200).baseUri(managementUri)
            .credentials(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD))
            .poll(new HttpPollConfig<Integer>(MANAGEMENT_STATUS).onSuccess(HttpValueFunctions.responseCode()))
            .poll(new HttpPollConfig<Boolean>(MANAGEMENT_URL_UP)
                    .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(false)))
            .poll(new HttpPollConfig<Integer>(REQUEST_COUNT).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("requestCount", Integer.class)))
            .poll(new HttpPollConfig<Integer>(ERROR_COUNT).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("errorCount", Integer.class)))
            .poll(new HttpPollConfig<Integer>(TOTAL_PROCESSING_TIME).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("processingTime", Integer.class)))
            .poll(new HttpPollConfig<Integer>(MAX_PROCESSING_TIME).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("maxTime", Integer.class)))
            .poll(new HttpPollConfig<Long>(BYTES_RECEIVED).vars(includeRuntimeUriVars)
                    // jboss seems to report 0 even if it has received lots of requests; dunno why.
                    .onSuccess(HttpValueFunctions.jsonContents("bytesReceived", Long.class)))
            .poll(new HttpPollConfig<Long>(BYTES_SENT).vars(includeRuntimeUriVars)
                    .onSuccess(HttpValueFunctions.jsonContents("bytesSent", Long.class)))
            .build();//from   w w w. ja  va  2 s.c  o  m

    connectServiceUp();
}

From source file:com.pinterest.secor.tools.ProgressMonitor.java

/**
 * Helper to publish stats to statsD client
 *//* w w  w  . j  a  v a 2  s .c  om*/
private void exportToStatsD(List<Stat> stats) {
    HostAndPort hostPort = HostAndPort.fromString(mConfig.getStatsDHostPort());

    // group stats by kafka group
    NonBlockingStatsDClient client = new NonBlockingStatsDClient(mConfig.getKafkaGroup(),
            hostPort.getHostText(), hostPort.getPort());

    for (Stat stat : stats) {
        @SuppressWarnings("unchecked")
        Map<String, String> tags = (Map<String, String>) stat.get(Stat.STAT_KEYS.TAGS.getName());
        String aspect = new StringBuilder((String) stat.get(Stat.STAT_KEYS.METRIC.getName())).append(PERIOD)
                .append(tags.get(Stat.STAT_KEYS.TOPIC.getName())).append(PERIOD)
                .append(tags.get(Stat.STAT_KEYS.PARTITION.getName())).toString();
        client.recordGaugeValue(aspect, Long.parseLong((String) stat.get(Stat.STAT_KEYS.VALUE.getName())));
    }
}

From source file:com.payu.ratel.config.beans.ServiceRegisterPostProcessorFactory.java

@SuppressWarnings("PMD.EmptyCatchBlock")
public ServiceRegisterPostProcessor create(ConfigurableListableBeanFactory beanFactory,
        RegisterStrategy registerStrategy) {

    SelfAddressProviderChain selfAddressProvider = beanFactory.getBean(SelfAddressProviderChain.class);
    if (selfAddressProvider == null) {
        throw new IllegalStateException("No SelfAddressProvider bean in context");
    }/*from ww w . java  2s.  c  o  m*/
    final HostAndPort hostAndPort = selfAddressProvider.getHostAndPort();

    ServletContext servletContext = null;
    try {
        servletContext = beanFactory.getBean(ServletContext.class);
    } catch (NoSuchBeanDefinitionException e) {

    }
    final String contextRoot = servletContext != null ? servletContext.getContextPath() : "";

    final String address = String.format("http://%s:%s%s%s", hostAndPort.getHostText(), hostAndPort.getPort(),
            contextRoot, RATEL_PATH);

    return new ServiceRegisterPostProcessor(beanFactory, registerStrategy, address);
}

From source file:org.wso2.mb.platform.tests.clustering.OrderGuaranteeTestCase.java

/**
 * Publish message to a single node and receive from the same node and check for any out of
 * order delivery and message duplication.
 *
 * @param messageCount  Number of message to send and receive
 * @throws XPathExpressionException/*from  w ww  .j a  v a 2 s  . c om*/
 * @throws AndesClientConfigurationException
 * @throws NamingException
 * @throws JMSException
 * @throws IOException
 * @throws AndesClientException
 */
@Test(groups = "wso2.mb", description = "Same node ordered delivery test case")
@Parameters({ "messageCount" })
public void testSameNodeOrderedDelivery(long messageCount)
        throws XPathExpressionException, AndesClientConfigurationException, NamingException, JMSException,
        IOException, AndesClientException, AndesException, DataAccessUtilException, InterruptedException {
    // Number of messages expected
    long expectedCount = messageCount;
    // Number of messages send
    long sendCount = messageCount;
    long printDivider = 10L;
    String queueName = "singleQueueOrder1";

    HostAndPort brokerAddress = getRandomAMQPBrokerAddress();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(
            brokerAddress.getHostText(), brokerAddress.getPort(), ExchangeType.QUEUE, queueName);
    consumerConfig.setMaximumMessagesToReceived(expectedCount * 2);
    consumerConfig.setPrintsPerMessageCount(expectedCount / printDivider);
    consumerConfig
            .setFilePathToWriteReceivedMessages(AndesClientConstants.FILE_PATH_TO_WRITE_RECEIVED_MESSAGES);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            brokerAddress.getHostText(), brokerAddress.getPort(), ExchangeType.QUEUE, queueName);
    publisherConfig.setNumberOfMessagesToSend(sendCount);
    publisherConfig.setPrintsPerMessageCount(sendCount / printDivider);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    consumerClient.startClient();

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    publisherClient.startClient();

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    // Wait until consumers are closed
    Thread.sleep(AndesClientConstants.DEFAULT_RUN_TIME);

    Assert.assertEquals(publisherClient.getSentMessageCount(), sendCount, "Message sending failed.");
    Assert.assertEquals(consumerClient.getReceivedMessageCount(), expectedCount, "Message receiving failed.");

    // Evaluating
    Assert.assertTrue(consumerClient.checkIfMessagesAreInOrder(), "Messages did not receive in order.");
    Assert.assertEquals(consumerClient.checkIfMessagesAreDuplicated().size(), 0,
            "Messages are not duplicated.");

    // Evaluate messages left in database
    Assert.assertEquals(dataAccessUtil.getMessageCountForQueue(queueName), 0, "Messages left in database");
    // Evaluate slots left in database
    Assert.assertEquals(dataAccessUtil.getAssignedSlotCountForQueue(queueName), 0, "Slots left in database");

}

From source file:org.wso2.mb.platform.tests.clustering.SubscriptionDisconnectingTestCase.java

/**
 * Publish messages to a single node and receive from the same node while reconnecting 4 times.
 *
 * @param messageCount  Number of message to send and receive
 * @throws XPathExpressionException/*  w ww. ja v  a 2s. c o  m*/
 * @throws org.wso2.mb.integration.common.clients.exceptions.AndesClientConfigurationException
 * @throws NamingException
 * @throws JMSException
 * @throws IOException
 */
@Test(groups = "wso2.mb", description = "Same node subscription reconnecting test")
@Parameters({ "messageCount" })
public void testSameNodeSubscriptionReconnecting(long messageCount)
        throws XPathExpressionException, AndesClientConfigurationException, NamingException, JMSException,
        IOException, AndesClientException, DataAccessUtilException {

    long sendCount = messageCount;
    long expectedCount = sendCount / 4;
    long printDivider = 10L;
    String queueName = "singleQueueSubscription1";

    HostAndPort brokerAddress = getRandomAMQPBrokerAddress();

    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(
            brokerAddress.getHostText(), brokerAddress.getPort(), ExchangeType.QUEUE, queueName);
    consumerConfig.setMaximumMessagesToReceived(expectedCount);
    consumerConfig.setPrintsPerMessageCount(expectedCount / printDivider);

    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            brokerAddress.getHostText(), brokerAddress.getPort(), ExchangeType.QUEUE, queueName);
    publisherConfig.setNumberOfMessagesToSend(sendCount);
    publisherConfig.setPrintsPerMessageCount(sendCount / printDivider);

    AndesClient consumerClient1 = new AndesClient(consumerConfig, true);
    consumerClient1.startClient();

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    publisherClient.startClient();

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient1, AndesClientConstants.DEFAULT_RUN_TIME);

    Assert.assertEquals(consumerClient1.getReceivedMessageCount(), expectedCount,
            "Message receiving failed for consumerClient1");

    AndesClient consumerClient2 = new AndesClient(consumerConfig, true);
    consumerClient2.startClient();

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient2, AndesClientConstants.DEFAULT_RUN_TIME);

    Assert.assertEquals(consumerClient2.getReceivedMessageCount(), expectedCount,
            "Message receiving failed for consumerClient2");

    AndesClient consumerClient3 = new AndesClient(consumerConfig, true);
    consumerClient3.startClient();

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient3, AndesClientConstants.DEFAULT_RUN_TIME);

    Assert.assertEquals(consumerClient3.getReceivedMessageCount(), expectedCount,
            "Message receiving failed for consumerClient3");

    AndesClient consumerClient4 = new AndesClient(consumerConfig, true);
    consumerClient4.startClient();

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient4, AndesClientConstants.DEFAULT_RUN_TIME);

    Assert.assertEquals(consumerClient4.getReceivedMessageCount(), expectedCount,
            "Message receiving failed for consumerClient4");

    long totalMessagesReceived = consumerClient1.getReceivedMessageCount()
            + consumerClient2.getReceivedMessageCount() + consumerClient3.getReceivedMessageCount()
            + consumerClient4.getReceivedMessageCount();

    Assert.assertEquals(publisherClient.getSentMessageCount(), sendCount, "Message sending failed.");
    Assert.assertEquals(totalMessagesReceived, expectedCount * 4, "Message receiving failed.");

    // Evaluate messages left in database
    Assert.assertEquals(dataAccessUtil.getMessageCountForQueue(queueName), 0, "Messages left in database");
    // Evaluate slots left in database
    Assert.assertEquals(dataAccessUtil.getAssignedSlotCountForQueue(queueName), 0, "Slots left in database");
}

From source file:org.wso2.mb.platform.tests.clustering.OrderGuaranteeTestCase.java

/**
 * Publish message to a single node and receive from another node and check for any out of order
 * delivery and message duplication.//ww  w . j av  a2  s  .  c o m
 *
 * @param messageCount  Number of message to send and receive
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws JMSException
 * @throws NamingException
 * @throws IOException
 * @throws AndesClientException
 */
@Test(groups = "wso2.mb", description = "Different node ordered delivery test case")
@Parameters({ "messageCount" })
public void testDifferentNodeOrderedDelivery(long messageCount)
        throws AndesClientConfigurationException, XPathExpressionException, JMSException, NamingException,
        IOException, AndesClientException, DataAccessUtilException, InterruptedException {
    // Number of messages expected
    long expectedCount = messageCount;
    // Number of messages send
    long sendCount = messageCount;
    long printDivider = 10L;
    String queueName = "singleQueueOrder2";

    HostAndPort consumerBrokerAddress = getRandomAMQPBrokerAddress();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(
            consumerBrokerAddress.getHostText(), consumerBrokerAddress.getPort(), ExchangeType.QUEUE,
            queueName);
    consumerConfig.setMaximumMessagesToReceived(expectedCount * 2);
    consumerConfig.setPrintsPerMessageCount(expectedCount / printDivider);
    consumerConfig
            .setFilePathToWriteReceivedMessages(AndesClientConstants.FILE_PATH_TO_WRITE_RECEIVED_MESSAGES);

    HostAndPort publisherBrokerAddress = getRandomAMQPBrokerAddress();

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            publisherBrokerAddress.getHostText(), publisherBrokerAddress.getPort(), ExchangeType.QUEUE,
            queueName);
    publisherConfig.setNumberOfMessagesToSend(sendCount);
    publisherConfig.setPrintsPerMessageCount(sendCount / printDivider);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    consumerClient.startClient();

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    publisherClient.startClient();

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    // Wait until consumers are closed
    Thread.sleep(AndesClientConstants.DEFAULT_RUN_TIME);

    Assert.assertEquals(publisherClient.getSentMessageCount(), sendCount, "Message sending failed.");
    Assert.assertEquals(consumerClient.getReceivedMessageCount(), expectedCount, "Message receiving failed.");

    // Evaluating
    Assert.assertTrue(consumerClient.checkIfMessagesAreInOrder(), "Messages did not receive in order.");
    Assert.assertEquals(consumerClient.checkIfMessagesAreDuplicated().size(), 0,
            "Messages are not duplicated.");

    // Evaluate messages left in database
    Assert.assertEquals(dataAccessUtil.getMessageCountForQueue(queueName), 0, "Messages left in database");
    // Evaluate slots left in database
    Assert.assertEquals(dataAccessUtil.getAssignedSlotCountForQueue(queueName), 0, "Slots left in database");
}