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:io.airlift.jmx.JmxAgent9.java

@Inject
public JmxAgent9(JmxConfig config) throws IOException {
    int registryPort;
    if (config.getRmiRegistryPort() == null) {
        registryPort = NetUtils.findUnusedPort();
    } else {/*from w  w  w.  j a va 2s .c  o  m*/
        registryPort = config.getRmiRegistryPort();
    }

    int serverPort = 0;
    if (config.getRmiServerPort() != null) {
        serverPort = config.getRmiServerPort();
    }

    try {
        VirtualMachine virtualMachine = VirtualMachine.attach(Long.toString(getProcessId()));
        try {
            virtualMachine.startLocalManagementAgent();

            Properties properties = new Properties();
            properties.setProperty("com.sun.management.jmxremote.port", Integer.toString(registryPort));
            properties.setProperty("com.sun.management.jmxremote.rmi.port", Integer.toString(serverPort));
            properties.setProperty("com.sun.management.jmxremote.authenticate", "false");
            properties.setProperty("com.sun.management.jmxremote.ssl", "false");
            virtualMachine.startManagementAgent(properties);
        } finally {
            virtualMachine.detach();
        }
    } catch (AttachNotSupportedException e) {
        throw new RuntimeException(e);
    }

    HostAndPort address;
    try {
        // This is how the jdk jmx agent constructs its url
        JMXServiceURL url = new JMXServiceURL("rmi", null, registryPort);
        address = HostAndPort.fromParts(url.getHost(), url.getPort());
    } catch (MalformedURLException e) {
        // should not happen...
        throw new AssertionError(e);
    }

    log.info("JMX agent started and listening on %s", address);

    this.url = new JMXServiceURL(
            String.format("service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi", address.getHost(), address.getPort()));
}

From source file:com.spotify.folsom.client.DefaultRawMemcacheClient.java

public static ListenableFuture<RawMemcacheClient> connect(final HostAndPort address,
        final int outstandingRequestLimit, final boolean binary, final Executor executor,
        final long timeoutMillis, final Charset charset, final Metrics metrics, final int maxSetLength) {

    final ChannelInboundHandler decoder;
    if (binary) {
        decoder = new BinaryMemcacheDecoder();
    } else {//from  w w w  . j  a  v a2  s  .  co  m
        decoder = new AsciiMemcacheDecoder(charset);
    }

    final ChannelHandler initializer = new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(new TcpTuningHandler(), decoder,

                    // Downstream
                    new MemcacheEncoder());
        }
    };

    final SettableFuture<RawMemcacheClient> clientFuture = SettableFuture.create();

    final Bootstrap bootstrap = new Bootstrap().group(EVENT_LOOP_GROUP).handler(initializer)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.MESSAGE_SIZE_ESTIMATOR, SimpleSizeEstimator.INSTANCE);

    final ChannelFuture connectFuture = bootstrap
            .connect(new InetSocketAddress(address.getHostText(), address.getPort()));

    connectFuture.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                // Create client
                final RawMemcacheClient client = new DefaultRawMemcacheClient(address, future.channel(),
                        outstandingRequestLimit, executor, timeoutMillis, metrics, maxSetLength);
                clientFuture.set(client);
            } else {
                clientFuture.setException(future.cause());
            }
        }
    });

    return onExecutor(clientFuture, executor);
}

From source file:com.streamsets.pipeline.kafka.impl.KafkaLowLevelConsumer09.java

private PartitionMetadata getPartitionMetadata(List<HostAndPort> brokers, String topic, int partition) {
    PartitionMetadata returnMetaData = null;
    for (HostAndPort broker : brokers) {
        SimpleConsumer simpleConsumer = null;
        try {//from  ww w. java 2  s. co  m
            LOG.info(
                    "Creating SimpleConsumer using the following configuration: host {}, port {}, max wait time {}, max "
                            + "fetch size {}, client columnName {}",
                    broker.getHostText(), broker.getPort(), METADATA_READER_TIME_OUT, BUFFER_SIZE,
                    METADATA_READER_CLIENT);
            simpleConsumer = new SimpleConsumer(broker.getHostText(), broker.getPort(),
                    METADATA_READER_TIME_OUT, BUFFER_SIZE, METADATA_READER_CLIENT);

            List<String> topics = Collections.singletonList(topic);
            TopicMetadataRequest req = new TopicMetadataRequest(topics);
            kafka.javaapi.TopicMetadataResponse resp = simpleConsumer.send(req);

            List<TopicMetadata> metaData = resp.topicsMetadata();
            for (TopicMetadata item : metaData) {
                for (PartitionMetadata part : item.partitionsMetadata()) {
                    if (part.partitionId() == partition) {
                        returnMetaData = part;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(KafkaErrors.KAFKA_25.getMessage(), broker.toString(), topic, partition, e.toString(), e);
        } finally {
            if (simpleConsumer != null) {
                simpleConsumer.close();
            }
        }
    }
    if (returnMetaData != null) {
        replicaBrokers.clear();
        for (kafka.cluster.BrokerEndPoint replica : returnMetaData.replicas()) {
            replicaBrokers.add(HostAndPort.fromParts(replica.host(), replica.port()));
        }
    }
    return returnMetaData;
}

From source file:com.streamsets.pipeline.kafka.impl.KafkaLowLevelConsumer08.java

private PartitionMetadata getPartitionMetadata(List<HostAndPort> brokers, String topic, int partition) {
    PartitionMetadata returnMetaData = null;
    for (HostAndPort broker : brokers) {
        SimpleConsumer simpleConsumer = null;
        try {/*from w ww . j  a  va2s.  c om*/
            LOG.info(
                    "Creating SimpleConsumer using the following configuration: host {}, port {}, max wait time {}, max "
                            + "fetch size {}, client columnName {}",
                    broker.getHostText(), broker.getPort(), METADATA_READER_TIME_OUT, BUFFER_SIZE,
                    METADATA_READER_CLIENT);
            simpleConsumer = new SimpleConsumer(broker.getHostText(), broker.getPort(),
                    METADATA_READER_TIME_OUT, BUFFER_SIZE, METADATA_READER_CLIENT);

            List<String> topics = Collections.singletonList(topic);
            TopicMetadataRequest req = new TopicMetadataRequest(topics);
            kafka.javaapi.TopicMetadataResponse resp = simpleConsumer.send(req);

            List<TopicMetadata> metaData = resp.topicsMetadata();
            for (TopicMetadata item : metaData) {
                for (PartitionMetadata part : item.partitionsMetadata()) {
                    if (part.partitionId() == partition) {
                        returnMetaData = part;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            LOG.error(KafkaErrors.KAFKA_25.getMessage(), broker.toString(), topic, partition, e.toString(), e);
        } finally {
            if (simpleConsumer != null) {
                simpleConsumer.close();
            }
        }
    }
    if (returnMetaData != null) {
        replicaBrokers.clear();
        for (kafka.cluster.Broker replica : returnMetaData.replicas()) {
            replicaBrokers.add(HostAndPort.fromParts(replica.host(), replica.port()));
        }
    }
    return returnMetaData;
}

From source file:org.apache.brooklyn.core.location.access.PortForwardManagerImpl.java

protected void associateImpl(String publicIpId, HostAndPort publicEndpoint, Location l, int privatePort) {
    synchronized (mutex) {
        String publicIp = publicEndpoint.getHostText();
        int publicPort = publicEndpoint.getPort();
        recordPublicIpHostname(publicIpId, publicIp);
        PortMapping mapping = new PortMapping(publicIpId, publicEndpoint, l, privatePort);
        PortMapping oldMapping = getPortMappingWithPublicSide(publicIpId, publicPort);
        log.debug(this + " associating public " + publicEndpoint + " on " + publicIpId + " with private port "
                + privatePort + " at " + l + " (" + mapping + ")"
                + (oldMapping == null ? "" : " (overwriting " + oldMapping + " )"));
        mappings.put(makeKey(publicIpId, publicPort), mapping);
    }//  w  w w.  j  av a  2 s .com
    onChanged();
}

From source file:org.apache.kudu.client.MiniKuduCluster.java

/**
 * Restart any master processes which are not currently running.
 *///from  www .  ja v  a2s  . com
public void restartDeadMasters() throws Exception {
    for (HostAndPort hostAndPort : masterHostPorts) {
        if (!masterProcesses.containsKey(hostAndPort.getPort())) {
            restartDeadProcessOnPort(hostAndPort.getPort(), masterProcesses);
        }
    }
}

From source file:com.bouncestorage.chaoshttpproxy.ChaosHttpProxyHandler.java

@Override
public void handle(String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse servletResponse) throws IOException {
    baseRequest.setHandled(true);//from   w w  w .j  av a  2s . c om

    // CONNECT is not supported pending implementation of MITM HTTPS
    if (request.getMethod().equals("CONNECT")) {
        logger.debug("CONNECT is not supported");
        servletResponse.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        return;
    }

    Failure failure = supplier.get();
    logger.debug("request: {}", request);
    logger.debug("Failure: {}", failure);
    try (InputStream is = request.getInputStream(); OutputStream os = servletResponse.getOutputStream()) {
        HostAndPort hostAndPort = HostAndPort.fromString(request.getHeader(HttpHeaders.HOST));
        String queryString = request.getQueryString();
        URI uri;
        try {
            uri = new URI(request.getScheme(), /*userInfo=*/ null, hostAndPort.getHostText(),
                    hostAndPort.hasPort() ? hostAndPort.getPort() : 80, request.getRequestURI(), queryString,
                    /*fragment=*/ null);
        } catch (URISyntaxException use) {
            throw new IOException(use);
        }
        logger.debug("uri: {}", uri);
        URI redirectedUri = redirects.get(uri);
        if (redirectedUri != null) {
            // TODO: parameters
            uri = redirectedUri;
            logger.debug("redirected uri: {}", uri);
        }

        switch (failure) {
        case HTTP_301:
        case HTTP_302:
        case HTTP_303:
        case HTTP_307:
        case HTTP_308:
            servletResponse.setStatus(failure.getResponseCode());
            URI redirectUri;
            try {
                redirectUri = new URI(request.getScheme(), /*userInfo=*/ null, hostAndPort.getHostText(),
                        hostAndPort.hasPort() ? hostAndPort.getPort() : 80, "/" + UUID.randomUUID().toString(),
                        /*query=*/ null, /*fragment=*/ null);
            } catch (URISyntaxException use) {
                throw new IOException(use);
            }
            redirects.put(redirectUri, uri);
            servletResponse.addHeader(HttpHeaders.LOCATION, redirectUri.toString());
            return;
        case HTTP_408:
        case HTTP_500:
        case HTTP_503:
        case HTTP_504:
            servletResponse.setStatus(failure.getResponseCode());
            return;
        case TIMEOUT:
            Uninterruptibles.sleepUninterruptibly(Long.MAX_VALUE, TimeUnit.DAYS);
            return;
        default:
            break;
        }

        InputStreamResponseListener listener = new InputStreamResponseListener();
        InputStream iss = failure == Failure.PARTIAL_REQUEST ?
        // TODO: random limit
                ByteStreams.limit(is, 1024) : is;
        org.eclipse.jetty.client.api.Request clientRequest = client.newRequest(uri.toString())
                .method(request.getMethod());
        long userContentLength = -1;
        for (String headerName : Collections.list(request.getHeaderNames())) {
            if (headerName.equalsIgnoreCase(HttpHeaders.EXPECT)
                    || headerName.equalsIgnoreCase("Proxy-Connection")) {
                continue;
            }
            String headerValue = request.getHeader(headerName);
            logger.trace("{}: {}", headerName, headerValue);

            if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_MD5)
                    && failure == Failure.CORRUPT_REQUEST_CONTENT_MD5) {
                headerValue = headerValue.toUpperCase();
            }
            if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) {
                userContentLength = Long.parseLong(headerValue);
            }
            clientRequest.header(headerName, headerValue);
        }

        // Work around Jetty bug that strips Content-Length
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=475613.
        final long length = userContentLength;
        clientRequest.content(new InputStreamContentProvider(iss) {
            @Override
            public long getLength() {
                return length != -1 ? length : super.getLength();
            }
        });
        clientRequest.send(listener);
        if (failure == Failure.PARTIAL_REQUEST) {
            return;
        }

        Response response;
        try {
            response = listener.get(Long.MAX_VALUE, TimeUnit.SECONDS);
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            throw new IOException(e);
        }
        int status = response.getStatus();
        logger.trace("status: {}", status);
        servletResponse.setStatus(status);
        List<HttpField> headers = Lists.newArrayList(response.getHeaders());
        if (failure == Failure.REORDER_HEADERS) {
            Collections.shuffle(headers);
        }
        for (HttpField field : headers) {
            String header = field.getName();
            String value = field.getValue();
            logger.trace("header: {}: {}", header, value);
            switch (failure) {
            case CHANGE_HEADER_CASE:
                // TODO: randomly change between upper- and lower-case
                header = header.toUpperCase();
                break;
            case CORRUPT_RESPONSE_CONTENT_MD5:
                if (header.equals(HttpHeaders.CONTENT_MD5)) {
                    value = BaseEncoding.base64().encode(new byte[Hashing.md5().bits() / 8]);
                }
                break;
            default:
                break;
            }
            servletResponse.addHeader(header, value);
        }
        try (InputStream responseContent = listener.getInputStream()) {
            switch (failure) {
            case PARTIAL_RESPONSE:
                byte[] array = new byte[1024];
                int count = responseContent.read(array);
                if (count != -1) {
                    // TODO: randomly read n - 1 bytes
                    os.write(array, 0, count / 2);
                    os.flush();
                }
                return;
            case SLOW_RESPONSE:
                for (int i = 0; i < 10; ++i) {
                    int ch = responseContent.read();
                    if (ch == -1) {
                        break;
                    }
                    os.write(ch);
                    os.flush();
                    Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
                }
                break;
            default:
                break;
            }
            ByteStreams.copy(responseContent, os);
        }
    }
}

From source file:com.proofpoint.jmx.JmxAgent9.java

@Inject
public JmxAgent9(JmxConfig config) throws IOException {
    if (config.isEnabled()) {
        int registryPort;
        if (config.getRmiRegistryPort() == null) {
            registryPort = NetUtils.findUnusedPort();
        } else {/* ww w.j a  va  2  s . c om*/
            registryPort = config.getRmiRegistryPort();
        }

        int serverPort = 0;
        if (config.getRmiServerPort() != null) {
            serverPort = config.getRmiServerPort();
        }

        try {
            VirtualMachine virtualMachine = VirtualMachine.attach(Long.toString(getProcessId()));
            try {
                virtualMachine.startLocalManagementAgent();

                Properties properties = new Properties();
                properties.setProperty("com.sun.management.jmxremote.port", Integer.toString(registryPort));
                properties.setProperty("com.sun.management.jmxremote.rmi.port", Integer.toString(serverPort));
                properties.setProperty("com.sun.management.jmxremote.authenticate", "false");
                properties.setProperty("com.sun.management.jmxremote.ssl", "false");
                virtualMachine.startManagementAgent(properties);
            } finally {
                virtualMachine.detach();
            }
        } catch (AttachNotSupportedException e) {
            throw new RuntimeException(e);
        }

        HostAndPort address;
        try {
            // This is how the jdk jmx agent constructs its url
            JMXServiceURL url = new JMXServiceURL("rmi", null, registryPort);
            address = HostAndPort.fromParts(url.getHost(), url.getPort());
        } catch (MalformedURLException e) {
            // should not happen...
            throw new AssertionError(e);
        }

        log.info("JMX agent started and listening on %s", address);

        this.url = new JMXServiceURL(String.format("service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi",
                address.getHost(), address.getPort()));
    } else {
        this.url = null;
    }
}

From source file:brooklyn.entity.proxy.AbstractControllerImpl.java

/** returns URL, if it can be inferred; null otherwise */
protected String inferUrl(boolean requireManagementAccessible) {
    String protocol = checkNotNull(getProtocol(), "no protocol configured");
    String domain = getDomain();/*  ww w.  j  a  va  2  s . c om*/
    if (domain != null && domain.startsWith("*.")) {
        domain = domain.replace("*.", ""); // Strip wildcard
    }
    Integer port = checkNotNull(getPort(), "no port configured (the requested port may be in use)");
    if (requireManagementAccessible) {
        HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port);
        if (accessible != null) {
            domain = accessible.getHostText();
            port = accessible.getPort();
        }
    }
    if (domain == null)
        domain = getAttribute(LoadBalancer.HOSTNAME);
    if (domain == null)
        return null;
    return protocol + "://" + domain + ":" + port + "/" + getConfig(SERVICE_UP_URL_PATH);
}

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

/**
 * Multiple subscribers and publishers in same node for a single queue
 *
 * @param messageCount Number of message to send and receive
 * @throws XPathExpressionException/*from w ww. j ava 2  s. c om*/
 * @throws AndesClientConfigurationException
 * @throws NamingException
 * @throws JMSException
 * @throws IOException
 * @throws AndesClientException
 */
@Test(groups = "wso2.mb", description = "Same node single queue multiple subscriber " + "publisher test case")
@Parameters({ "messageCount" })
public void testSameNodeSingleQueueMultipleSubscriberPublisher(long messageCount)
        throws XPathExpressionException, AndesClientConfigurationException, NamingException, JMSException,
        IOException, AndesClientException, DataAccessUtilException, InterruptedException {
    // Number of messages expected
    long expectedCount = messageCount;
    // Number of messages send
    long sendCount = messageCount;
    String queueName = "singleQueue1";

    HostAndPort brokerAddress = getRandomAMQPBrokerAddress();

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

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

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

    AndesClient publisherClient1 = new AndesClient(publisherConfig, true);
    publisherClient1.startClient();
    AndesClient publisherClient2 = new AndesClient(publisherConfig, true);
    publisherClient2.startClient();
    AndesClient publisherClient3 = new AndesClient(publisherConfig, true);
    publisherClient3.startClient();
    AndesClient publisherClient4 = new AndesClient(publisherConfig, true);
    publisherClient4.startClient();

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient1, AndesClientConstants.DEFAULT_RUN_TIME);
    AndesClientUtils.shutdownClient(consumerClient2);
    AndesClientUtils.shutdownClient(consumerClient3);
    AndesClientUtils.shutdownClient(consumerClient4);
    // Wait until consumers are closed
    Thread.sleep(AndesClientConstants.DEFAULT_RUN_TIME);

    Assert.assertEquals(publisherClient1.getSentMessageCount(), sendCount,
            "Message sending failed by publisherClient1.");
    Assert.assertEquals(publisherClient2.getSentMessageCount(), sendCount,
            "Message sending failed by publisherClient2.");
    Assert.assertEquals(publisherClient3.getSentMessageCount(), sendCount,
            "Message sending failed by publisherClient3.");
    Assert.assertEquals(publisherClient4.getSentMessageCount(), sendCount,
            "Message sending failed by publisherClient4.");
    Assert.assertEquals(consumerClient1.getReceivedMessageCount(), expectedCount,
            "Message receiving failed by consumerClient1.");
    Assert.assertEquals(consumerClient2.getReceivedMessageCount(), expectedCount,
            "Message receiving failed by consumerClient2.");
    Assert.assertEquals(consumerClient3.getReceivedMessageCount(), expectedCount,
            "Message receiving failed by consumerClient3.");
    Assert.assertEquals(consumerClient4.getReceivedMessageCount(), expectedCount,
            "Message receiving failed by consumerClient4.");

    long totalMessagesSent = publisherClient1.getSentMessageCount() + publisherClient2.getSentMessageCount()
            + publisherClient3.getSentMessageCount() + publisherClient4.getSentMessageCount();
    long totalMessagesReceived = consumerClient1.getReceivedMessageCount()
            + consumerClient2.getReceivedMessageCount() + consumerClient3.getReceivedMessageCount()
            + consumerClient4.getReceivedMessageCount();
    Assert.assertEquals(totalMessagesSent, totalMessagesReceived, "Message receiving failed by all consumers");
    Assert.assertEquals(totalMessagesSent, sendCount * 4,
            "Message receiving by all consumers does not match the message count that was sent");

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