Example usage for com.google.common.net HostAndPort getPort

List of usage examples for com.google.common.net HostAndPort getPort

Introduction

In this page you can find the example usage for com.google.common.net HostAndPort getPort.

Prototype

public int getPort() 

Source Link

Document

Get the current port number, failing if no port is defined.

Usage

From source file:org.apache.druid.firehose.kafka.KafkaSimpleConsumer.java

private PartitionMetadata findLeader() throws InterruptedException {
    for (HostAndPort broker : replicaBrokers) {
        SimpleConsumer consumer = null;//from w  w w  .  j  av a2s . c o m
        try {
            log.info("Finding new leader from Kafka brokers, try broker [%s]", broker.toString());
            consumer = new SimpleConsumer(broker.getHostText(), broker.getPort(), SO_TIMEOUT_MILLIS,
                    BUFFER_SIZE, leaderLookupClientId);
            TopicMetadataResponse resp = consumer
                    .send(new TopicMetadataRequest(Collections.singletonList(topic)));

            List<TopicMetadata> metaData = resp.topicsMetadata();
            for (TopicMetadata item : metaData) {
                if (topic.equals(item.topic())) {
                    for (PartitionMetadata part : item.partitionsMetadata()) {
                        if (part.partitionId() == partitionId) {
                            return part;
                        }
                    }
                }
            }
        } catch (Exception e) {
            ensureNotInterrupted(e);
            log.warn(e, "error communicating with Kafka Broker [%s] to find leader for [%s] - [%s]", broker,
                    topic, partitionId);
        } finally {
            if (consumer != null) {
                consumer.close();
            }
        }
    }

    return null;
}

From source file:org.apache.brooklyn.location.basic.ByonLocationResolver.java

protected LocationSpec<? extends MachineLocation> parseMachine(Map<String, ?> vals,
        Class<? extends MachineLocation> locationClass, Map<String, ?> defaults, String specForErrMsg) {
    Map<String, Object> valSanitized = Sanitizer.sanitize(vals);
    Map<String, Object> machineConfig = MutableMap.copyOf(vals);

    String osfamily = (String) machineConfig.remove(OS_FAMILY.getName());
    String ssh = (String) machineConfig.remove("ssh");
    String winrm = (String) machineConfig.remove("winrm");
    Map<Integer, String> tcpPortMappings = (Map<Integer, String>) machineConfig.get("tcpPortMappings");

    checkArgument(ssh != null ^ winrm != null, "Must specify exactly one of 'ssh' or 'winrm' for machine: %s",
            valSanitized);//w ww.j ava  2  s .c o m

    UserAndHostAndPort userAndHostAndPort;
    String host;
    int port;
    if (ssh != null) {
        userAndHostAndPort = parseUserAndHostAndPort((String) ssh, 22);
    } else {
        userAndHostAndPort = parseUserAndHostAndPort((String) winrm, 5985);
    }

    // If there is a tcpPortMapping defined for the connection-port, then use that for ssh/winrm machine
    port = userAndHostAndPort.getHostAndPort().getPort();
    if (tcpPortMappings != null && tcpPortMappings.containsKey(port)) {
        String override = tcpPortMappings.get(port);
        HostAndPort hostAndPortOverride = HostAndPort.fromString(override);
        if (!hostAndPortOverride.hasPort()) {
            throw new IllegalArgumentException(
                    "Invalid portMapping ('" + override + "') for port " + port + " in " + specForErrMsg);
        }
        port = hostAndPortOverride.getPort();
        host = hostAndPortOverride.getHostText().trim();
    } else {
        host = userAndHostAndPort.getHostAndPort().getHostText().trim();
    }

    machineConfig.put("address", host);
    try {
        InetAddress.getByName(host);
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Invalid host '" + host + "' specified in '" + specForErrMsg + "': " + e);
    }

    if (userAndHostAndPort.getUser() != null) {
        checkArgument(!vals.containsKey("user"), "Must not specify user twice for machine: %s", valSanitized);
        machineConfig.put("user", userAndHostAndPort.getUser());
    }
    if (userAndHostAndPort.getHostAndPort().hasPort()) {
        checkArgument(!vals.containsKey("port"), "Must not specify port twice for machine: %s", valSanitized);
        machineConfig.put("port", port);
    }
    for (Map.Entry<String, ?> entry : defaults.entrySet()) {
        if (!machineConfig.containsKey(entry.getKey())) {
            machineConfig.put(entry.getKey(), entry.getValue());
        }
    }

    Class<? extends MachineLocation> locationClassHere = locationClass;
    if (osfamily != null) {
        locationClassHere = OS_TO_MACHINE_LOCATION_TYPE.get(osfamily);
    }

    return LocationSpec.create(locationClassHere).configure(machineConfig);
}

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

/**
 * Runs a topic send and receive test case
 *
 * @param messageType        The message type to be used when publishing
 * @param numberOfPublishers The number of publishers
 * @param destinationName    The destination name for sender and receiver
 * @param messageCount       Number of message to send and receive
 * @throws XPathExpressionException/*from   w w w .  j a v  a 2  s  .  co  m*/
 * @throws AndesClientConfigurationException
 * @throws NamingException
 * @throws JMSException
 * @throws IOException
 * @throws AndesClientException
 */
private void runMessageTypeTestCase(JMSMessageType messageType, int numberOfPublishers, String destinationName,
        long messageCount) throws XPathExpressionException, AndesClientConfigurationException, NamingException,
        JMSException, IOException, AndesClientException, DataAccessUtilException {

    // Number of messages send
    long sendCount = messageCount;
    long printDivider = 10L;

    HostAndPort brokerAddress = getRandomAMQPBrokerAddress();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(
            brokerAddress.getHostText(), brokerAddress.getPort(), ExchangeType.QUEUE, destinationName);
    consumerConfig.setMaximumMessagesToReceived(sendCount * numberOfPublishers);
    consumerConfig.setPrintsPerMessageCount(sendCount / printDivider);

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

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

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

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);

    // Evaluating
    Assert.assertEquals(publisherClient.getSentMessageCount(), sendCount * numberOfPublishers,
            "Message sending failed.");
    Assert.assertEquals(consumerClient.getReceivedMessageCount(), sendCount * numberOfPublishers,
            "Message receiving failed.");

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

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

/**
 * Publish messages to a single node and receive from the same node with AUTO_ACKNOWLEDGE
 * ack mode//  w ww  . j ava 2s  . c  o  m
 *
 * @param messageCount number of message to send and receive
 * @throws XPathExpressionException
 * @throws AndesClientConfigurationException
 * @throws NamingException
 * @throws JMSException
 * @throws IOException
 * @throws AndesClientException
 */
@Test(groups = "wso2.mb", description = "AUTO_ACKNOWLEDGE ack mode test case for queue")
@Parameters({ "messageCount" })
public void testAutoAcknowledgeModeForQueue(long messageCount)
        throws XPathExpressionException, AndesClientConfigurationException, NamingException, JMSException,
        IOException, AndesClientException, DataAccessUtilException, InterruptedException {
    // Expected message count
    long expectedCount = messageCount;
    // Number of messages send
    long sendCount = messageCount;
    long printDivider = 10L;
    String queueName = "autoAcknowledgeQueue";

    HostAndPort brokerAddress = getRandomAMQPBrokerAddress();

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

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

    // Evaluating
    Assert.assertEquals(publisherClient.getSentMessageCount(), sendCount, "Message sending failed.");
    Assert.assertEquals(consumerClient.getReceivedMessageCount(), expectedCount, "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.DifferentAckModeQueueTestCase.java

/**
 * Publish messages to a single node and receive from the same node with SESSION_TRANSACTED
 * ack mode//from w  w  w  . ja va 2 s .c  o  m
 *
 * @param messageCount number of message to send and receive
 * @throws XPathExpressionException
 * @throws AndesClientConfigurationException
 * @throws NamingException
 * @throws JMSException
 * @throws IOException
 * @throws AndesClientException
 */
@Test(groups = "wso2.mb", description = "SESSION_TRANSACTED ack mode test case for queue")
@Parameters({ "messageCount" })
public void testSessionTransactedAckModeForQueueTestCase(long messageCount)
        throws XPathExpressionException, AndesClientConfigurationException, NamingException, JMSException,
        IOException, AndesClientException, DataAccessUtilException, InterruptedException {
    // Expected message count
    long expectedCount = messageCount;
    // Number of messages send
    long sendCount = messageCount;
    long printDivider = 10L;
    String queueName = "sessionTransactedAckQueue";

    HostAndPort brokerAddress = getRandomAMQPBrokerAddress();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(
            brokerAddress.getHostText(), brokerAddress.getPort(), ExchangeType.QUEUE, queueName);
    consumerConfig.setMaximumMessagesToReceived(expectedCount * 2);
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.SESSION_TRANSACTED);
    consumerConfig.setCommitAfterEachMessageCount(1L);
    consumerConfig.setPrintsPerMessageCount(expectedCount / printDivider);

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

    // Evaluating
    Assert.assertEquals(publisherClient.getSentMessageCount(), sendCount, "Message sending failed.");
    Assert.assertEquals(consumerClient.getReceivedMessageCount(), expectedCount, "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.DifferentAckModeQueueTestCase.java

/**
 * Publish messages to a single node and receive from the same node with DUPS_OK_ACKNOWLEDGE
 * ack mode/*from w  ww.ja  va 2 s .  c o  m*/
 *
 * @param messageCount number of message to send and receive
 * @throws XPathExpressionException
 * @throws AndesClientConfigurationException
 * @throws JMSException
 * @throws NamingException
 * @throws IOException
 * @throws AndesClientException
 */
@Test(groups = "wso2.mb", description = "DUPS_OK_ACKNOWLEDGE ack mode test case for queue")
@Parameters({ "messageCount" })
public void testDupOkAcknowledgeModeForQueue(long messageCount)
        throws XPathExpressionException, AndesClientConfigurationException, JMSException, NamingException,
        IOException, AndesClientException, DataAccessUtilException, InterruptedException {
    // Expected message count
    long expectedCount = messageCount;
    // Number of messages send
    long sendCount = messageCount;
    long printDivider = 10L;
    String queueName = "dupsOkAcknowledgeQueue";

    HostAndPort brokerAddress = getRandomAMQPBrokerAddress();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(
            brokerAddress.getHostText(), brokerAddress.getPort(), ExchangeType.QUEUE, queueName);
    consumerConfig.setMaximumMessagesToReceived(expectedCount * 2);
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.DUPS_OK_ACKNOWLEDGE);
    consumerConfig.setRunningDelay(10L);
    consumerConfig.setPrintsPerMessageCount(expectedCount / printDivider);

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

    // Evaluating
    Assert.assertEquals(publisherClient.getSentMessageCount(), sendCount, "Message sending failed.");
    Assert.assertEquals(consumerClient.getReceivedMessageCount(), expectedCount, "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.DifferentAckModeQueueTestCase.java

/**
 * Publish messages to a single node and receive from the same node with CLIENT_ACKNOWLEDGE
 * ack mode//w w  w.ja  v  a 2 s .c o  m
 *
 * @param messageCount number of message to send and receive
 * @throws XPathExpressionException
 * @throws AndesClientConfigurationException
 * @throws NamingException
 * @throws JMSException
 * @throws IOException
 * @throws AndesClientException
 */
@Test(groups = "wso2.mb", description = "CLIENT_ACKNOWLEDGE ack mode test case for queue")
@Parameters({ "messageCount" })
public void testClientAcknowledgeModeForQueue(long messageCount)
        throws XPathExpressionException, AndesClientConfigurationException, NamingException, JMSException,
        IOException, AndesClientException, DataAccessUtilException, InterruptedException {
    // Expected message count
    long expectedCount = messageCount;
    // Number of messages send
    long sendCount = messageCount;
    long printDivider = 10L;
    String queueName = "clientAcknowledgeQueue";

    HostAndPort brokerAddress = getRandomAMQPBrokerAddress();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(
            brokerAddress.getHostText(), brokerAddress.getPort(), ExchangeType.QUEUE, queueName);
    consumerConfig.setMaximumMessagesToReceived(expectedCount * 2);
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.CLIENT_ACKNOWLEDGE);
    consumerConfig.setAcknowledgeAfterEachMessageCount(1L);
    consumerConfig.setRunningDelay(10L);
    consumerConfig.setPrintsPerMessageCount(expectedCount / printDivider);

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

    // Evaluating
    Assert.assertEquals(publisherClient.getSentMessageCount(), sendCount, "Message sending failed.");
    Assert.assertEquals(consumerClient.getReceivedMessageCount(), expectedCount, "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.location.byon.ByonLocationResolver.java

protected LocationSpec<? extends MachineLocation> parseMachine(Map<String, ?> vals,
        Class<? extends MachineLocation> locationClass, Map<String, ?> defaults, String specForErrMsg) {
    Map<String, Object> valSanitized = Sanitizer.sanitize(vals);
    Map<String, Object> machineConfig = MutableMap.copyOf(vals);

    String osFamily = (String) machineConfig.remove(OS_FAMILY.getName());
    String ssh = (String) machineConfig.remove("ssh");
    String winrm = (String) machineConfig.remove("winrm");
    Map<Integer, String> tcpPortMappings = (Map<Integer, String>) machineConfig.get("tcpPortMappings");

    checkArgument(ssh != null ^ winrm != null, "Must specify exactly one of 'ssh' or 'winrm' for machine: %s",
            valSanitized);//from   w  w w  . j  a v  a  2s.com

    UserAndHostAndPort userAndHostAndPort;
    String host;
    int port;
    if (ssh != null) {
        userAndHostAndPort = parseUserAndHostAndPort((String) ssh, 22);
    } else {
        userAndHostAndPort = parseUserAndHostAndPort((String) winrm, 5985);
    }

    // If there is a tcpPortMapping defined for the connection-port, then use that for ssh/winrm machine
    port = userAndHostAndPort.getHostAndPort().getPort();
    if (tcpPortMappings != null && tcpPortMappings.containsKey(port)) {
        String override = tcpPortMappings.get(port);
        HostAndPort hostAndPortOverride = HostAndPort.fromString(override);
        if (!hostAndPortOverride.hasPort()) {
            throw new IllegalArgumentException(
                    "Invalid portMapping ('" + override + "') for port " + port + " in " + specForErrMsg);
        }
        port = hostAndPortOverride.getPort();
        host = hostAndPortOverride.getHostText().trim();
    } else {
        host = userAndHostAndPort.getHostAndPort().getHostText().trim();
    }

    machineConfig.put("address", host);
    try {
        InetAddress.getByName(host);
    } catch (Exception e) {
        throw new IllegalArgumentException(
                "Invalid host '" + host + "' specified in '" + specForErrMsg + "': " + e);
    }

    if (userAndHostAndPort.getUser() != null) {
        checkArgument(!vals.containsKey("user"), "Must not specify user twice for machine: %s", valSanitized);
        machineConfig.put("user", userAndHostAndPort.getUser());
    }
    if (userAndHostAndPort.getHostAndPort().hasPort()) {
        checkArgument(!vals.containsKey("port"), "Must not specify port twice for machine: %s", valSanitized);
        machineConfig.put("port", port);
    }
    for (Map.Entry<String, ?> entry : defaults.entrySet()) {
        if (!machineConfig.containsKey(entry.getKey())) {
            machineConfig.put(entry.getKey(), entry.getValue());
        }
    }

    Class<? extends MachineLocation> locationClassHere = locationClass;
    if (osFamily != null) {
        locationClassHere = getLocationClass(osFamily);
    }

    return LocationSpec.create(locationClassHere).configure(machineConfig);
}

From source file:org.apache.brooklyn.entity.java.JmxSupport.java

public String getJmxUrl() {
    init();/*ww  w  . j a va2 s.c om*/

    HostAndPort jmx = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity, entity.getAttribute(JMX_PORT));

    if (EnumSet.of(JmxAgentModes.JMXMP, JmxAgentModes.JMXMP_AND_RMI).contains(getJmxAgentMode())) {
        return JmxHelper.toJmxmpUrl(jmx.getHostText(), jmx.getPort());
    } else {
        if (getJmxAgentMode() == JmxAgentModes.NONE) {
            fixPortsForModeNone();
        }
        // this will work for agent or agentless
        HostAndPort rmi = BrooklynAccessUtils.getBrooklynAccessibleAddress(entity,
                entity.getAttribute(RMI_REGISTRY_PORT));
        return JmxHelper.toRmiJmxUrl(jmx.getHostText(), jmx.getPort(), rmi.getPort(),
                entity.getAttribute(JMX_CONTEXT));
    }
}

From source file:brooklyn.entity.mesos.framework.marathon.MarathonPortForwarder.java

@Override
public HostAndPort openPortForwarding(HostAndPort targetSide, Optional<Integer> optionalPublicPort,
        Protocol protocol, Cidr accessingCidr) {
    PortForwardManager pfw = getPortForwardManager();
    HostAndPort publicSide;/*from   ww w .j  av  a  2  s .  c  o  m*/
    if (optionalPublicPort.isPresent()) {
        int publicPort = optionalPublicPort.get();
        publicSide = HostAndPort.fromParts(marathonHostname, publicPort);
    } else {
        publicSide = HostAndPort.fromParts(marathonHostname, targetSide.getPort());
    }
    pfw.associate(marathonHostname, publicSide, targetSide.getPort());
    portmap.put(publicSide, targetSide);
    return publicSide;
}