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:org.apache.slider.providers.accumulo.AccumuloProviderService.java

@Override
public Map<String, String> buildMonitorDetails(ClusterDescription clusterDesc) {
    Map<String, String> details = super.buildMonitorDetails(clusterDesc);

    details.put(/*from  w  ww  . j  a v  a 2 s  . c  o m*/
            "Active Accumulo Master (RPC): " + getInfoAvoidingNull(clusterDesc, AccumuloKeys.MASTER_ADDRESS),
            null);

    String monitorKey = "Active Accumulo Monitor: ";
    String monitorAddr = getInfoAvoidingNull(clusterDesc, AccumuloKeys.MONITOR_ADDRESS);
    if (!StringUtils.isBlank(monitorAddr)) {
        try {
            HostAndPort hostPort = HostAndPort.fromString(monitorAddr);
            details.put(monitorKey, String.format("http://%s:%d", hostPort.getHostText(), hostPort.getPort()));
        } catch (Exception e) {
            details.put(monitorKey + "N/A", null);
        }
    } else {
        details.put(monitorKey + "N/A", null);
    }

    return details;
}

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

/**
 * Publish messages to a single node and receive from random nodes while reconnecting 4 times.
 *
 * @param messageCount  Number of message to send and receive
 * @throws XPathExpressionException/* ww  w  . jav  a2  s . com*/
 * @throws org.wso2.mb.integration.common.clients.exceptions.AndesClientConfigurationException
 * @throws NamingException
 * @throws JMSException
 * @throws IOException
 * @throws CloneNotSupportedException
 */
@Test(groups = "wso2.mb", description = "Random node subscription reconnecting test")
@Parameters({ "messageCount" })
public void testDifferentNodeSubscriptionReconnecting(long messageCount)
        throws XPathExpressionException, AndesClientConfigurationException, NamingException, JMSException,
        IOException, CloneNotSupportedException, AndesClientException, DataAccessUtilException {
    long sendCount = messageCount;
    long expectedCount = sendCount / 4;
    long printDivider = 10L;
    String queueName = "singleQueueSubscription2";

    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");

    AndesJMSConsumerClientConfiguration consumerConfig2 = consumerConfig.clone();
    HostAndPort randomAMQPBrokerAddress = getRandomAMQPBrokerAddress();
    consumerConfig2.setHostName(randomAMQPBrokerAddress.getHostText());
    consumerConfig2.setPort(randomAMQPBrokerAddress.getPort());
    AndesClient consumerClient2 = new AndesClient(consumerConfig2, true);
    consumerClient2.startClient();

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient2, AndesClientConstants.DEFAULT_RUN_TIME);

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

    AndesJMSConsumerClientConfiguration consumerConfig3 = consumerConfig.clone();
    randomAMQPBrokerAddress = getRandomAMQPBrokerAddress();
    consumerConfig3.setHostName(randomAMQPBrokerAddress.getHostText());
    consumerConfig3.setPort(randomAMQPBrokerAddress.getPort());
    AndesClient consumerClient3 = new AndesClient(consumerConfig3, true);
    consumerClient3.startClient();

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient3, AndesClientConstants.DEFAULT_RUN_TIME);

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

    AndesJMSConsumerClientConfiguration consumerConfig4 = consumerConfig.clone();
    randomAMQPBrokerAddress = getRandomAMQPBrokerAddress();
    consumerConfig4.setHostName(randomAMQPBrokerAddress.getHostText());
    consumerConfig4.setPort(randomAMQPBrokerAddress.getPort());
    AndesClient consumerClient4 = new AndesClient(consumerConfig4, 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.apache.brooklyn.entity.nosql.couchbase.CouchbaseNodeImpl.java

protected void renameServerToPublicHostname() {
    // http://docs.couchbase.com/couchbase-manual-2.5/cb-install/#couchbase-getting-started-hostnames
    URI apiUri = null;//from   ww w .j  a v  a  2 s . c  om
    try {
        HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this,
                getAttribute(COUCHBASE_WEB_ADMIN_PORT));
        apiUri = URI.create(String.format("http://%s:%d/node/controller/rename", accessible.getHostText(),
                accessible.getPort()));
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                getConfig(COUCHBASE_ADMIN_USERNAME), getConfig(COUCHBASE_ADMIN_PASSWORD));
        HttpToolResponse response = HttpTool.httpPost(
                // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials
                HttpTool.httpClientBuilder().uri(apiUri).credentials(credentials).build(), apiUri,
                MutableMap.of(HttpHeaders.CONTENT_TYPE, MediaType.FORM_DATA.toString(), HttpHeaders.ACCEPT,
                        "*/*",
                        // this appears needed; without it we get org.apache.http.NoHttpResponseException !?
                        HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)),
                Charsets.UTF_8.encode("hostname=" + Urls.encode(accessible.getHostText())).array());
        log.debug("Renamed Couchbase server " + this + " via " + apiUri + ": " + response);
        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            log.warn("Invalid response code, renaming {} ({}): {}",
                    new Object[] { apiUri, response.getResponseCode(), response.getContentAsString() });
        }
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.warn("Error renaming server, using " + apiUri + ": " + e, e);
    }
}

From source file:brooklyn.entity.nosql.couchbase.CouchbaseNodeImpl.java

protected void renameServerToPublicHostname() {
    // http://docs.couchbase.com/couchbase-manual-2.5/cb-install/#couchbase-getting-started-hostnames
    URI apiUri = null;//from  w w w .  j a va2  s.com
    try {
        HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this,
                getAttribute(COUCHBASE_WEB_ADMIN_PORT));
        apiUri = URI.create(String.format("http://%s:%d/node/controller/rename", accessible.getHostText(),
                accessible.getPort()));
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                getConfig(COUCHBASE_ADMIN_USERNAME), getConfig(COUCHBASE_ADMIN_PASSWORD));
        HttpToolResponse response = HttpTool.httpPost(
                // the uri is required by the HttpClientBuilder in order to set the AuthScope of the credentials
                HttpTool.httpClientBuilder().uri(apiUri).credentials(credentials).build(), apiUri,
                MutableMap.of(HttpHeaders.CONTENT_TYPE, MediaType.FORM_DATA.toString(), HttpHeaders.ACCEPT,
                        "*/*",
                        // this appears needed; without it we get org.apache.http.NoHttpResponseException !?
                        HttpHeaders.AUTHORIZATION, HttpTool.toBasicAuthorizationValue(credentials)),
                Charsets.UTF_8.encode("hostname=" + Urls.encode(accessible.getHostText())).array());
        log.debug("Renamed Couchbase server " + this + " via " + apiUri + ": " + response);
        if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
            log.warn("Invalid response code, renaming " + apiUri + ": " + response);
        }
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        log.warn("Error renaming server, using " + apiUri + ": " + e, e);
    }
}

From source file:org.apache.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());
    sensors().set(MANAGEMENT_URL, managementUri);

    if (isHttpMonitoringEnabled()) {
        log.debug("JBoss sensors for " + this + " reading from " + managementUri);
        Map<String, String> includeRuntimeUriVars = ImmutableMap.of("include-runtime", "true");
        boolean retrieveUsageMetrics = getConfig(RETRIEVE_USAGE_METRICS);

        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()).suppressDuplicates(true))
                .poll(new HttpPollConfig<Boolean>(MANAGEMENT_URL_UP)
                        .onSuccess(HttpValueFunctions.responseCodeEquals(200))
                        .onFailureOrException(Functions.constant(false)).suppressDuplicates(true))
                .poll(new HttpPollConfig<Integer>(REQUEST_COUNT).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("requestCount", Integer.class))
                        .onFailureOrException(EntityFunctions.attribute(this, REQUEST_COUNT))
                        .enabled(retrieveUsageMetrics))
                .poll(new HttpPollConfig<Integer>(ERROR_COUNT).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("errorCount", Integer.class))
                        .enabled(retrieveUsageMetrics))
                .poll(new HttpPollConfig<Integer>(TOTAL_PROCESSING_TIME).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("processingTime", Integer.class))
                        .enabled(retrieveUsageMetrics))
                .poll(new HttpPollConfig<Integer>(MAX_PROCESSING_TIME).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("maxTime", Integer.class))
                        .enabled(retrieveUsageMetrics))
                .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))
                        .enabled(retrieveUsageMetrics))
                .poll(new HttpPollConfig<Long>(BYTES_SENT).vars(includeRuntimeUriVars)
                        .onSuccess(HttpValueFunctions.jsonContents("bytesSent", Long.class))
                        .enabled(retrieveUsageMetrics))
                .build();/*from  ww w  . j  av  a 2s.c  o  m*/

        enrichers().add(Enrichers.builder().updatingMap(Attributes.SERVICE_NOT_UP_INDICATORS)
                .from(MANAGEMENT_URL_UP)
                .computing(Functionals.ifNotEquals(true).value("Management URL not reachable")).build());
    }

    connectServiceUpIsRunning();
}

From source file:com.pingcap.tikv.TiSession.java

public synchronized ManagedChannel getChannel(String addressStr) {
    ManagedChannel channel = connPool.get(addressStr);
    if (channel == null) {
        HostAndPort address;
        try {/*  w ww.j a v a  2s  . co  m*/
            address = HostAndPort.fromString(addressStr);
        } catch (Exception e) {
            throw new IllegalArgumentException("failed to form address");
        }
        // Channel should be lazy without actual connection until first call
        // So a coarse grain lock is ok here
        channel = ManagedChannelBuilder.forAddress(address.getHostText(), address.getPort())
                .maxInboundMessageSize(conf.getMaxFrameSize()).usePlaintext(true)
                .idleTimeout(60, TimeUnit.SECONDS).build();
        connPool.put(addressStr, channel);
    }
    return channel;
}

From source file:brooklyn.qa.load.SimulatedJBoss7ServerImpl.java

@Override
protected void connectSensors() {
    boolean simulateEntity = getConfig(SIMULATE_ENTITY);
    boolean simulateExternalMonitoring = getConfig(SIMULATE_EXTERNAL_MONITORING);

    if (!simulateEntity && !simulateExternalMonitoring) {
        super.connectSensors();
        return;//from w w w .j a  v a 2  s.c om
    }

    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);

    if (simulateExternalMonitoring) {
        // TODO What would set this normally, if not doing connectServiceUpIsRunning?
        setAttribute(SERVICE_PROCESS_IS_RUNNING, true);
    } else {
        // if simulating entity, then simulate work of periodic HTTP request; TODO but not parsing JSON response
        String uriToPoll = (simulateEntity) ? "http://localhost:8081" : managementUri;

        httpFeed = HttpFeed.builder().entity(this).period(200).baseUri(uriToPoll)
                .credentials(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD))
                .poll(new HttpPollConfig<Integer>(MANAGEMENT_STATUS)
                        .onSuccess(HttpValueFunctions.responseCode()))
                .build();

        // Polls over ssh for whether process is running
        connectServiceUpIsRunning();
    }

    functionFeed = FunctionFeed.builder().entity(this).period(5000)
            .poll(new FunctionPollConfig<Boolean, Boolean>(MANAGEMENT_URL_UP).callable(new Callable<Boolean>() {
                private int counter = 0;

                public Boolean call() {
                    setAttribute(REQUEST_COUNT, (counter++ % 100));
                    setAttribute(ERROR_COUNT, (counter++ % 100));
                    setAttribute(TOTAL_PROCESSING_TIME, (counter++ % 100));
                    setAttribute(MAX_PROCESSING_TIME, (counter++ % 100));
                    setAttribute(BYTES_RECEIVED, (long) (counter++ % 100));
                    setAttribute(BYTES_SENT, (long) (counter++ % 100));
                    return true;
                }
            })).build();

    addEnricher(Enrichers.builder().updatingMap(Attributes.SERVICE_NOT_UP_INDICATORS).from(MANAGEMENT_URL_UP)
            .computing(Functionals.ifNotEquals(true).value("Management URL not reachable")).build());
}

From source file:org.apache.brooklyn.qa.load.SimulatedJBoss7ServerImpl.java

@Override
protected void connectSensors() {
    boolean simulateEntity = getConfig(SIMULATE_ENTITY);
    boolean simulateExternalMonitoring = getConfig(SIMULATE_EXTERNAL_MONITORING);

    if (!simulateEntity && !simulateExternalMonitoring) {
        super.connectSensors();
        return;//from  w  w w. j av  a 2 s  . com
    }

    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());
    sensors().set(MANAGEMENT_URL, managementUri);

    if (simulateExternalMonitoring) {
        // TODO What would set this normally, if not doing connectServiceUpIsRunning?
        sensors().set(SERVICE_PROCESS_IS_RUNNING, true);
    } else {
        // if simulating entity, then simulate work of periodic HTTP request; TODO but not parsing JSON response
        String uriToPoll = (simulateEntity) ? "http://localhost:8081" : managementUri;

        httpFeed = HttpFeed.builder().entity(this).period(200).baseUri(uriToPoll)
                .credentials(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD))
                .poll(new HttpPollConfig<Integer>(MANAGEMENT_STATUS)
                        .onSuccess(HttpValueFunctions.responseCode()))
                .build();

        // Polls over ssh for whether process is running
        connectServiceUpIsRunning();
    }

    functionFeed = FunctionFeed.builder().entity(this).period(5000)
            .poll(new FunctionPollConfig<Boolean, Boolean>(MANAGEMENT_URL_UP).callable(new Callable<Boolean>() {
                private int counter = 0;

                public Boolean call() {
                    sensors().set(REQUEST_COUNT, (counter++ % 100));
                    sensors().set(ERROR_COUNT, (counter++ % 100));
                    sensors().set(TOTAL_PROCESSING_TIME, (counter++ % 100));
                    sensors().set(MAX_PROCESSING_TIME, (counter++ % 100));
                    sensors().set(BYTES_RECEIVED, (long) (counter++ % 100));
                    sensors().set(BYTES_SENT, (long) (counter++ % 100));
                    return true;
                }
            })).build();

    enrichers()
            .add(Enrichers.builder().updatingMap(Attributes.SERVICE_NOT_UP_INDICATORS).from(MANAGEMENT_URL_UP)
                    .computing(Functionals.ifNotEquals(true).value("Management URL not reachable")).build());
}

From source file:com.intellij.util.net.HttpProxySettingsUi.java

private boolean isValid() {
    if (myUseHTTPProxyRb.isSelected()) {
        String host = getText(myProxyHostTextField);
        if (host == null) {
            return false;
        }//  w  ww  .j  a v  a  2  s  .c om

        try {
            HostAndPort parsedHost = HostAndPort.fromString(host);
            if (parsedHost.hasPort()) {
                return false;
            }
            host = parsedHost.getHostText();

            try {
                InetAddresses.forString(host);
                return true;
            } catch (IllegalArgumentException e) {
                // it is not an IPv4 or IPv6 literal
            }

            InternetDomainName.from(host);
        } catch (IllegalArgumentException e) {
            return false;
        }

        if (myProxyAuthCheckBox.isSelected()) {
            return !StringUtil.isEmptyOrSpaces(myProxyLoginTextField.getText())
                    && myProxyPasswordTextField.getPassword().length > 0;
        }
    }
    return true;
}

From source file:org.apache.accumulo.server.monitor.servlets.TServersServlet.java

private void doDetailTable(HttpServletRequest req, StringBuilder sb, HostAndPort address, int numTablets,
        TabletStats total, TabletStats historical) {
    Table detailTable = new Table("tServerDetail", "Details");
    detailTable.setSubCaption(address.getHostText() + ":" + address.getPort());
    detailTable.addSortableColumn("Hosted&nbsp;Tablets", new NumberType<Integer>(), null);
    detailTable.addSortableColumn("Entries", new NumberType<Long>(), null);
    detailTable.addSortableColumn("Minor&nbsp;Compacting", new NumberType<Integer>(), null);
    detailTable.addSortableColumn("Major&nbsp;Compacting", new NumberType<Integer>(), null);
    detailTable.addSortableColumn("Splitting", new NumberType<Integer>(), null);
    detailTable.addRow(numTablets, total.numEntries, total.minors.status, total.majors.status,
            historical.splits.status);//from www. j  a v a2 s.c o  m
    detailTable.generate(req, sb);
}