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.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// ww  w  .  j a v a 2  s.  c  o m
 * @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//  www .  jav  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.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 av a2  s  .c om*/
            "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.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   w w  w  . j  a v a  2 s  . com*/

        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: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/*  w  w w .ja va  2  s.  c om*/
 * @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.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./*from  w ww .j ava  2 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");
}

From source file:org.apache.druid.server.DruidNode.java

private void init(String serviceName, String host, Integer plainTextPort, Integer tlsPort,
        boolean enablePlaintextPort, boolean enableTlsPort) {
    Preconditions.checkNotNull(serviceName);

    if (!enableTlsPort && !enablePlaintextPort) {
        throw new IAE("At least one of the druid.enablePlaintextPort or druid.enableTlsPort needs to be true.");
    }/*  ww  w  .  j a  v  a 2s . c  o  m*/

    this.enablePlaintextPort = enablePlaintextPort;
    this.enableTlsPort = enableTlsPort;

    final boolean nullHost = host == null;
    HostAndPort hostAndPort;
    Integer portFromHostConfig;
    if (host != null) {
        hostAndPort = HostAndPort.fromString(host);
        host = hostAndPort.getHostText();
        portFromHostConfig = hostAndPort.hasPort() ? hostAndPort.getPort() : null;
        if (plainTextPort != null && portFromHostConfig != null && !plainTextPort.equals(portFromHostConfig)) {
            throw new IAE("Conflicting host:port [%s] and port [%d] settings", host, plainTextPort);
        }
        if (portFromHostConfig != null) {
            plainTextPort = portFromHostConfig;
        }
    } else {
        host = getDefaultHost();
    }

    if (enablePlaintextPort && enableTlsPort
            && ((plainTextPort == null || tlsPort == null) || plainTextPort.equals(tlsPort))) {
        // If both plainTExt and tls are enabled then do not allow plaintextPort to be null or
        throw new IAE(
                "plaintextPort and tlsPort cannot be null or same if both http and https connectors are enabled");
    }
    if (enableTlsPort && (tlsPort == null || tlsPort < 0)) {
        throw new IAE("A valid tlsPort needs to specified when druid.enableTlsPort is set");
    }

    if (enablePlaintextPort) {
        // to preserve backwards compatible behaviour
        if (nullHost && plainTextPort == null) {
            plainTextPort = -1;
        } else {
            if (plainTextPort == null) {
                plainTextPort = SocketUtil.findOpenPort(8080);
            }
        }
        this.plaintextPort = plainTextPort;
    } else {
        this.plaintextPort = -1;
    }
    if (enableTlsPort) {
        this.tlsPort = tlsPort;
    } else {
        this.tlsPort = -1;
    }

    this.serviceName = serviceName;
    this.host = host;
}

From source file:org.sfs.integration.java.BaseTestVerticle.java

@Before
public void before(TestContext context) {
    vertx = rule.vertx();//w  w w  . j  av  a 2 s  . c  o m
    Async async = context.async();
    aVoid().flatMap(aVoid -> {
        String clusteruuid = UUID.randomUUID().toString();
        try {
            rootTmpDir = createTempDirectory("");
            esTempDir = createTempDirectory(rootTmpDir, format("test-cluster-%s", clusteruuid));
            tmpDir = createTempDirectory(rootTmpDir, valueOf(currentTimeMillis()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        int esPort = findFreePort(9300, 9400);
        esHost = "127.0.0.1:" + esPort;
        esClusterName = format("test-cluster-%s", clusteruuid);
        esNodeName = format("test-server-node-%s", clusteruuid);

        Builder settings = settingsBuilder();
        settings.put("script.groovy.sandbox.enabled", false);
        settings.put("cluster.name", esClusterName);
        settings.put("node.name", esNodeName);
        settings.put("http.enabled", false);
        settings.put("discovery.zen.ping.multicast.enabled", false);
        settings.put("discovery.zen.ping.unicast.hosts", esHost);
        settings.put("transport.tcp.port", esPort);
        settings.put("network.host", "127.0.0.1");
        settings.put("node.data", true);
        settings.put("node.master", true);
        settings.put("path.home", esTempDir);
        esNode = nodeBuilder().settings(settings).node();
        esClient = esNode.client();

        JsonObject verticleConfig;

        Buffer buffer = vertx.fileSystem().readFileBlocking(
                currentThread().getContextClassLoader().getResource("intgtestconfig.json").getFile());
        verticleConfig = new JsonObject(buffer.toString(UTF_8));
        verticleConfig.put("fs.home", tmpDir.toString());

        if (!verticleConfig.containsKey("elasticsearch.cluster.name")) {
            verticleConfig.put("elasticsearch.cluster.name", esClusterName);
        }

        if (!verticleConfig.containsKey("elasticsearch.node.name")) {
            verticleConfig.put("elasticsearch.node.name", esNodeName);
        }

        if (!verticleConfig.containsKey("elasticsearch.discovery.zen.ping.unicast.hosts")) {
            verticleConfig.put("elasticsearch.discovery.zen.ping.unicast.hosts", new JsonArray().add(esHost));
        }

        if (!verticleConfig.containsKey("http.listen.addresses")) {
            int freePort = findFreePort(6677, 7777);
            verticleConfig.put("http.listen.addresses",
                    new JsonArray().add(HostAndPort.fromParts("127.0.0.1", freePort).toString()));
        }

        HostAndPort hostAndPort = HostAndPort
                .fromString(verticleConfig.getJsonArray("http.listen.addresses").getString(0));

        HttpClientOptions httpClientOptions = new HttpClientOptions();
        httpClientOptions.setDefaultPort(hostAndPort.getPort()).setDefaultHost(hostAndPort.getHostText())
                .setMaxPoolSize(25).setConnectTimeout(1000).setKeepAlive(false).setLogActivity(true);

        HttpClientOptions httpsClientOptions = new HttpClientOptions();
        httpsClientOptions.setDefaultPort(hostAndPort.getPort()).setDefaultHost(hostAndPort.getHostText())
                .setMaxPoolSize(25).setConnectTimeout(1000).setKeepAlive(false).setLogActivity(true)
                .setSsl(true);
        httpClient = vertx.createHttpClient(httpClientOptions);
        httpsClient = vertx.createHttpClient(httpsClientOptions);

        SfsServer sfsServer = new SfsServer();

        ObservableFuture<String> handler = RxHelper.observableFuture();
        vertx.deployVerticle(sfsServer, new DeploymentOptions().setConfig(verticleConfig), handler.toHandler());
        return handler.map(new ToVoid<>()).doOnNext(aVoid1 -> {
            vertxContext = sfsServer.vertxContext();
            checkState(vertxContext != null, "VertxContext was null on Verticle %s", sfsServer);
        }).onErrorResumeNext(throwable -> {
            throwable.printStackTrace();
            return cleanup().flatMap(aVoid1 -> Observable.<Void>error(throwable));
        });
    }).subscribe(new TestSubscriber(context, async));
}

From source file:org.apache.brooklyn.core.network.AbstractOnNetworkEnricher.java

protected Maybe<String> transformHostAndPort(Entity source, MachineLocation machine, String sensorVal) {
    HostAndPort hostAndPort = HostAndPort.fromString(sensorVal);
    if (hostAndPort.hasPort()) {
        int port = hostAndPort.getPort();
        Optional<HostAndPort> mappedEndpoint = getMappedEndpoint(source, machine, port);
        if (!mappedEndpoint.isPresent()) {
            LOG.debug(//from  ww  w .ja v  a 2s  . c  o  m
                    "network-facing enricher not transforming {} host-and-port {}, because no port-mapping for {}",
                    new Object[] { source, sensorVal, machine });
            return Maybe.absent();
        }
        if (!mappedEndpoint.get().hasPort()) {
            LOG.debug(
                    "network-facing enricher not transforming {} host-and-port {}, because no port in target {} for {}",
                    new Object[] { source, sensorVal, mappedEndpoint, machine });
            return Maybe.absent();
        }
        return Maybe.of(mappedEndpoint.get().toString());
    } else {
        LOG.debug("network-facing enricher not transforming {} host-and-port {} because defines no port",
                source, hostAndPort);
        return Maybe.absent();
    }
}

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 w w. j av a  2 s.  c  o 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;
}