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

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

Introduction

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

Prototype

@Override
public String toString() 

Source Link

Document

Rebuild the host:port string, including brackets if necessary.

Usage

From source file:com.torodb.mongowp.utils.BsonArrayBuilder.java

public BsonArrayBuilder add(HostAndPortField field, HostAndPort value) {
    Preconditions.checkState(!built);//  w  w w .  ja  v a 2 s .  c  o m
    if (value == null) {
        return addNull();
    }
    list.add(newString(value.toString()));
    return this;
}

From source file:org.apache.accumulo.server.gc.GarbageCollectWriteAheadLogs.java

boolean holdsLock(HostAndPort addr) {
    try {// w w  w .j a  v a2  s. co m
        String zpath = ZooUtil.getRoot(instance) + Constants.ZTSERVERS + "/" + addr.toString();
        List<String> children = ZooReaderWriter.getInstance().getChildren(zpath);
        return !(children == null || children.isEmpty());
    } catch (KeeperException.NoNodeException ex) {
        return false;
    } catch (Exception ex) {
        log.debug(ex, ex);
        return true;
    }
}

From source file:clocker.docker.networking.entity.sdn.calico.CalicoNodeSshDriver.java

@Override
public Map<String, String> getShellEnvironment() {
    Entity etcdNode = getEntity().config().get(CalicoNode.ETCD_NODE);
    HostAndPort etcdAuthority = HostAndPort.fromParts(etcdNode.sensors().get(Attributes.SUBNET_ADDRESS),
            etcdNode.sensors().get(EtcdNode.ETCD_CLIENT_PORT));
    Map<String, String> environment = MutableMap.copyOf(super.getShellEnvironment());
    environment.put("ETCD_AUTHORITY", etcdAuthority.toString());
    return environment;
}

From source file:org.apache.gobblin.kafka.client.Kafka08ConsumerClient.java

private SimpleConsumer getSimpleConsumer(HostAndPort hostAndPort) {
    return this.getSimpleConsumer(hostAndPort.toString());
}

From source file:org.apache.accumulo.server.watcher.MonitorLog4jWatcher.java

/**
 * Read the host and port information for the Monitor's log4j socket and update the system properties so that, on logger refresh, it sees the new information.
 *//*  w  w w.  j a v a2 s . c om*/
protected void updateMonitorLog4jLocation() {
    try {
        String hostPortString = new String(ZooReaderWriter.getInstance().getData(path, null), UTF_8);
        HostAndPort hostAndPort = HostAndPort.fromString(hostPortString);

        System.setProperty(HOST_PROPERTY_NAME, hostAndPort.getHostText());
        System.setProperty(PORT_PROPERTY_NAME, Integer.toString(hostAndPort.getPort()));

        log.info("Changing monitor log4j address to " + hostAndPort.toString());

        doOnChange();
    } catch (NoNodeException e) {
        // Not sure on the synchronization guarantees for Loggers and Appenders
        // on configuration reload
        synchronized (lock) {
            // Don't need to try to re-disable'ing it.
            if (loggingDisabled) {
                return;
            }

            Logger logger = LogManager.getLogger("org.apache.accumulo");
            if (null != logger) {
                // TODO ACCUMULO-2343 Create a specific appender for log-forwarding to the monitor
                // that can replace the AsyncAppender+SocketAppender.
                Appender appender = logger.getAppender("ASYNC");
                if (null != appender) {
                    log.info("Closing log-forwarding appender");
                    appender.close();
                    log.info("Removing log-forwarding appender");
                    logger.removeAppender(appender);
                    loggingDisabled = true;
                }
            }
        }
    } catch (IllegalArgumentException e) {
        log.error("Could not parse host and port information", e);
    } catch (Exception e) {
        log.error("Error reading zookeeper data for Monitor Log4j watcher", e);
    }
}

From source file:com.eightkdata.mongowp.utils.BsonDocumentBuilder.java

public BsonDocumentBuilder append(HostAndPortField field, HostAndPort value) {
    Preconditions.checkState(!built);/*from   w ww . j a  v  a  2  s  . c o m*/
    if (value == null) {
        return appendNull(field);
    }
    map.put(field.getFieldName(), newString(value.toString()));
    return this;
}

From source file:brooklyn.entity.nosql.riak.RiakNodeImpl.java

public void connectSensors() {
    super.connectSensors();
    connectServiceUpIsRunning();//from  w  ww  .j a  v  a  2 s  . c o  m
    HostAndPort accessible = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getRiakWebPort());

    httpFeed = HttpFeed.builder().entity(this).period(500, TimeUnit.MILLISECONDS)
            .baseUri(String.format("http://%s/stats", accessible.toString()))
            .poll(new HttpPollConfig<Integer>(NODE_GETS)
                    .onSuccess(HttpValueFunctions.jsonContents("node_gets", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(NODE_GETS_TOTAL)
                    .onSuccess(HttpValueFunctions.jsonContents("node_gets_total", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(NODE_PUTS)
                    .onSuccess(HttpValueFunctions.jsonContents("node_puts", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(NODE_PUTS_TOTAL)
                    .onSuccess(HttpValueFunctions.jsonContents("node_puts_total", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(VNODE_GETS)
                    .onSuccess(HttpValueFunctions.jsonContents("vnode_gets", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(VNODE_GETS_TOTAL)
                    .onSuccess(HttpValueFunctions.jsonContents("vnode_gets_total", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(VNODE_PUTS)
                    .onSuccess(HttpValueFunctions.jsonContents("vnode_puts", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(VNODE_PUTS_TOTAL)
                    .onSuccess(HttpValueFunctions.jsonContents("vnode_puts_total", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(READ_REPAIRS_TOTAL)
                    .onSuccess(HttpValueFunctions.jsonContents("read_repairs_total", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(COORD_REDIRS_TOTAL)
                    .onSuccess(HttpValueFunctions.jsonContents("coord_redirs_total", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(MEMORY_PROCESSES_USED)
                    .onSuccess(HttpValueFunctions.jsonContents("memory_processes_used", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(SYS_PROCESS_COUNT)
                    .onSuccess(HttpValueFunctions.jsonContents("sys_process_count", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(PBC_CONNECTS)
                    .onSuccess(HttpValueFunctions.jsonContents("pbc_connects", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<Integer>(PBC_ACTIVE)
                    .onSuccess(HttpValueFunctions.jsonContents("pbc_active", Integer.class))
                    .onFailureOrException(Functions.constant(-1)))
            .poll(new HttpPollConfig<List<String>>(RING_MEMBERS).onSuccess(
                    Functionals.chain(HttpValueFunctions.jsonContents("ring_members", String[].class),
                            new Function<String[], List<String>>() {
                                @Nullable
                                @Override
                                public List<String> apply(@Nullable String[] strings) {
                                    return Arrays.asList(strings);
                                }
                            }))
                    .onFailureOrException(Functions.constant(Arrays.asList(new String[0]))))
            .build();

    WebAppServiceMethods.connectWebAppServerPolicies(this);
}

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

private PartitionMetadata findLeader() throws InterruptedException {
    for (HostAndPort broker : replicaBrokers) {
        SimpleConsumer consumer = null;/*from w w  w.j a  va2s . 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, 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.druid.firehose.kafka.KafkaSimpleConsumer.java

private PartitionMetadata findLeader() throws InterruptedException {
    for (HostAndPort broker : replicaBrokers) {
        SimpleConsumer consumer = null;/*from w  ww.  j  av a  2  s .  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:ratpack.http.client.internal.RequestActionSupport.java

public void connect(final Downstream<? super T> downstream) throws Exception {
    final Bootstrap b = new Bootstrap();
    b.group(this.execution.getEventLoop()).channel(ChannelImplDetector.getSocketChannelImpl())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override//from   w ww  .  ja v  a 2s .  com
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();

                    if (finalUseSsl) {
                        SSLEngine sslEngine;
                        if (requestSpecBacking.getSslContext() != null) {
                            sslEngine = requestSpecBacking.getSslContext().createSSLEngine();
                        } else {
                            sslEngine = SSLContext.getDefault().createSSLEngine();
                        }
                        sslEngine.setUseClientMode(true);
                        p.addLast("ssl", new SslHandler(sslEngine));
                    }

                    p.addLast("codec", new HttpClientCodec());
                    p.addLast("readTimeout",
                            new ReadTimeoutHandler(requestParams.readTimeoutNanos, TimeUnit.NANOSECONDS));

                    p.addLast("redirectHandler", new SimpleChannelInboundHandler<HttpObject>(false) {
                        boolean readComplete;
                        boolean redirected;

                        @Override
                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            if (!readComplete) {
                                error(downstream, new PrematureChannelClosureException(
                                        "Server " + uri + " closed the connection prematurely"));
                            }
                            super.channelReadComplete(ctx);
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
                                throws Exception {
                            super.exceptionCaught(ctx, cause);
                        }

                        @Override
                        protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg)
                                throws Exception {
                            if (msg instanceof HttpResponse) {
                                readComplete = true;
                                final HttpResponse response = (HttpResponse) msg;
                                int maxRedirects = requestSpecBacking.getMaxRedirects();
                                int status = response.status().code();
                                String locationValue = response.headers().get(HttpHeaderConstants.LOCATION);

                                Action<? super RequestSpec> redirectConfigurer = RequestActionSupport.this.requestConfigurer;
                                if (isRedirect(status) && redirectCounter < maxRedirects
                                        && locationValue != null) {
                                    final Function<? super ReceivedResponse, Action<? super RequestSpec>> onRedirect = requestSpecBacking
                                            .getOnRedirect();
                                    if (onRedirect != null) {
                                        final Action<? super RequestSpec> onRedirectResult = onRedirect
                                                .apply(toReceivedResponse(response));
                                        if (onRedirectResult == null) {
                                            redirectConfigurer = null;
                                        } else {
                                            redirectConfigurer = redirectConfigurer.append(onRedirectResult);
                                        }
                                    }

                                    if (redirectConfigurer != null) {
                                        Action<? super RequestSpec> redirectRequestConfig = s -> {
                                            if (status == 301 || status == 302) {
                                                s.method("GET");
                                            }
                                        };
                                        redirectRequestConfig = redirectRequestConfig
                                                .append(redirectConfigurer);

                                        URI locationUrl;
                                        if (ABSOLUTE_PATTERN.matcher(locationValue).matches()) {
                                            locationUrl = new URI(locationValue);
                                        } else {
                                            locationUrl = new URI(uri.getScheme(), null, uri.getHost(),
                                                    uri.getPort(), locationValue, null, null);
                                        }

                                        buildRedirectRequestAction(redirectRequestConfig, locationUrl,
                                                redirectCounter + 1).connect(downstream);
                                        redirected = true;
                                    }
                                }
                            }

                            if (!redirected) {
                                ctx.fireChannelRead(msg);
                            }
                        }
                    });

                    if (requestSpecBacking.isDecompressResponse()) {
                        p.addLast(new HttpContentDecompressor());
                    }
                    addResponseHandlers(p, downstream);
                }

                @Override
                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                    ctx.close();
                    error(downstream, cause);
                }
            });

    ChannelFuture connectFuture = b.connect(host, port);
    connectFuture.addListener(f1 -> {
        if (connectFuture.isSuccess()) {
            String fullPath = getFullPath(uri);
            FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(requestSpecBacking.getMethod()), fullPath, requestSpecBacking.getBody());
            if (headers.get(HttpHeaderConstants.HOST) == null) {
                HostAndPort hostAndPort = HostAndPort.fromParts(host, port);
                headers.set(HttpHeaderConstants.HOST, hostAndPort.toString());
            }
            headers.set(HttpHeaderConstants.CONNECTION, HttpHeaderValues.CLOSE);
            int contentLength = request.content().readableBytes();
            if (contentLength > 0) {
                headers.set(HttpHeaderConstants.CONTENT_LENGTH, Integer.toString(contentLength));
            }

            HttpHeaders requestHeaders = request.headers();

            for (String name : headers.getNames()) {
                requestHeaders.set(name, headers.getAll(name));
            }

            ChannelFuture writeFuture = connectFuture.channel().writeAndFlush(request);
            writeFuture.addListener(f2 -> {
                if (!writeFuture.isSuccess()) {
                    writeFuture.channel().close();
                    error(downstream, writeFuture.cause());
                }
            });
        } else {
            connectFuture.channel().close();
            error(downstream, connectFuture.cause());
        }
    });
}