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

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

Introduction

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

Prototype

public boolean hasPort() 

Source Link

Document

Return true if this instance has a defined port.

Usage

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(/*w  w  w.  j a  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:org.apache.brooklyn.core.network.AbstractOnNetworkEnricher.java

protected boolean isHostAndPort(Object sensorVal) {
    if (sensorVal instanceof HostAndPort) {
        return true;
    } else if (sensorVal instanceof String) {
        try {//  w  ww . j  a v  a  2 s.  com
            HostAndPort hostAndPort = HostAndPort.fromString((String) sensorVal);
            return hostAndPort.hasPort();
        } catch (IllegalArgumentException e) {
            return false;
        }
    }
    return false;
}

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.");
    }//from w  w  w.  jav a2s .  c om

    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:com.github.jcustenborder.kafka.connect.utils.config.validators.ValidHostAndPort.java

void validate(final String setting, final String input) {
    HostAndPort hostAndPort = HostAndPort.fromString(input);
    if (this.requireBracketsForIPv6) {
        hostAndPort = hostAndPort.requireBracketsForIPv6();
    }/*from  www . ja  v  a 2  s . c o m*/
    if (null != this.defaultPort) {
        hostAndPort.withDefaultPort(this.defaultPort);
    }

    if (Strings.isNullOrEmpty(hostAndPort.getHostText())) {
        throw new ConfigException(String.format("'%s'(%s) host cannot be blank or null.", setting, input));
    }

    if (this.portRequired && !hostAndPort.hasPort()) {
        throw new ConfigException(String.format("'%s'(%s) must specify a port.", setting, input));
    }

}

From source file:io.druid.firehose.kafka.KafkaSimpleConsumer.java

public KafkaSimpleConsumer(String topic, int partitionId, String clientId, List<String> brokers,
        boolean earliest) {
    List<HostAndPort> brokerList = new ArrayList<>();
    for (String broker : brokers) {
        HostAndPort brokerHostAndPort = HostAndPort.fromString(broker);
        Preconditions.checkArgument(// w  w  w . j a va  2s.  c om
                brokerHostAndPort.getHostText() != null && !brokerHostAndPort.getHostText().isEmpty()
                        && brokerHostAndPort.hasPort(),
                "kafka broker [%s] is not valid, must be <host>:<port>", broker);
        brokerList.add(brokerHostAndPort);
    }

    this.allBrokers = Collections.unmodifiableList(brokerList);
    this.topic = topic;
    this.partitionId = partitionId;
    this.clientId = String.format("%s_%d_%s", topic, partitionId, clientId);
    this.leaderLookupClientId = clientId + "leaderLookup";
    this.replicaBrokers = new ArrayList<>();
    this.replicaBrokers.addAll(this.allBrokers);
    this.earliest = earliest;
    log.info(
            "KafkaSimpleConsumer initialized with clientId [%s] for message consumption and clientId [%s] for leader lookup",
            this.clientId, this.leaderLookupClientId);
}

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

public KafkaSimpleConsumer(String topic, int partitionId, String clientId, List<String> brokers,
        boolean earliest) {
    List<HostAndPort> brokerList = new ArrayList<>();
    for (String broker : brokers) {
        HostAndPort brokerHostAndPort = HostAndPort.fromString(broker);
        Preconditions.checkArgument(/*from w  w  w  .j a va 2  s  .co m*/
                brokerHostAndPort.getHostText() != null && !brokerHostAndPort.getHostText().isEmpty()
                        && brokerHostAndPort.hasPort(),
                "kafka broker [%s] is not valid, must be <host>:<port>", broker);
        brokerList.add(brokerHostAndPort);
    }

    this.allBrokers = Collections.unmodifiableList(brokerList);
    this.topic = topic;
    this.partitionId = partitionId;
    this.clientId = StringUtils.format("%s_%d_%s", topic, partitionId, clientId);
    this.leaderLookupClientId = clientId + "leaderLookup";
    this.replicaBrokers = new ArrayList<>();
    this.replicaBrokers.addAll(this.allBrokers);
    this.earliest = earliest;
    log.info(
            "KafkaSimpleConsumer initialized with clientId [%s] for message consumption and clientId [%s] for leader lookup",
            this.clientId, this.leaderLookupClientId);
}

From source file:brooklyn.networking.vclouddirector.PortForwarderVcloudDirector.java

@Override
public HostAndPort openPortForwarding(HostAndPort targetEndpoint, Optional<Integer> optionalPublicPort,
        Protocol protocol, Cidr accessingCidr) {
    // TODO should associate ip:port with PortForwardManager; but that takes location param
    //      getPortForwardManager().associate(publicIp, publicPort, targetVm, targetPort);
    // TODO Could check old mapping, and re-use that public port
    // TODO Pass cidr in vcloud-director call
    String publicIp = subnetTier.getConfig(NETWORK_PUBLIC_IP);

    HostAndPort publicEndpoint;//from  w ww.j  av a2  s .  c  o  m
    PortRange portRangeToUse;
    if (optionalPublicPort.isPresent()) {
        publicEndpoint = HostAndPort.fromParts(publicIp, optionalPublicPort.get());
        portRangeToUse = null;
    } else if (getNatMicroserviceAutoAllocatesPorts()) {
        publicEndpoint = HostAndPort.fromString(publicIp);
        portRangeToUse = getPortRange();
    } else {
        PortForwardManager pfw = getPortForwardManager();
        int publicPort = pfw.acquirePublicPort(publicIp);
        publicEndpoint = HostAndPort.fromParts(publicIp, publicPort);
        portRangeToUse = null;
    }

    try {
        HostAndPort result = getClient().openPortForwarding(new PortForwardingConfig().protocol(Protocol.TCP)
                .publicEndpoint(publicEndpoint).publicPortRange(portRangeToUse).targetEndpoint(targetEndpoint));

        // TODO Work around for old vCD NAT microservice, which returned empty result
        if (!result.hasPort() && result.getHostText().equals("")) {
            if (publicEndpoint.hasPort()) {
                LOG.warn(
                        "[DEPRECATED] NAT Rule addition returned endpoint '{}'; probably old micro-service version; "
                                + "assuming result is {}->{} via {}",
                        new Object[] { result, publicEndpoint, targetEndpoint, subnetTier });
                result = publicEndpoint;
            } else {
                throw new IllegalStateException("Invalid result for NAT Rule addition, returned endpoint ''; "
                        + "cannot infer actual result as no explicit port requested for " + publicEndpoint
                        + "->" + targetEndpoint + " via " + subnetTier);
            }
        }

        LOG.debug("Enabled port-forwarding for {}, via {}, on ",
                new Object[] { targetEndpoint, result, subnetTier });
        return result;
    } catch (Exception e) {
        Exceptions.propagateIfFatal(e);
        LOG.info("Failed creating port forwarding rule on " + this + ": " + publicEndpoint + "->"
                + targetEndpoint + "; rethrowing", e);
        throw Exceptions.propagate(e);
    }
}

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  ww w.j  a va 2 s  .c o m*/

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