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

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

Introduction

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

Prototype

public String getHostText() 

Source Link

Document

Returns the portion of this HostAndPort instance that should represent the hostname or IPv4/IPv6 literal.

Usage

From source file:org.apache.brooklyn.entity.nosql.couchbase.CouchbaseSyncGatewayImpl.java

@Override
protected void connectServiceUpIsRunning() {
    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this,
            getAttribute(CouchbaseSyncGateway.ADMIN_REST_API_PORT));

    String managementUri = String.format("http://%s:%s", hp.getHostText(), hp.getPort());

    sensors().set(MANAGEMENT_URL, managementUri);

    httpFeed = HttpFeed.builder().entity(this).period(200).baseUri(managementUri)
            .poll(new HttpPollConfig<Boolean>(SERVICE_UP).onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(false)))
            .build();//from  w  ww .j  av  a  2  s .  co m
}

From source file:brooklyn.entity.nosql.couchbase.CouchbaseSyncGatewayImpl.java

@Override
protected void connectServiceUpIsRunning() {
    HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this,
            getAttribute(CouchbaseSyncGateway.ADMIN_REST_API_PORT));

    String managementUri = String.format("http://%s:%s", hp.getHostText(), hp.getPort());

    setAttribute(MANAGEMENT_URL, managementUri);

    httpFeed = HttpFeed.builder().entity(this).period(200).baseUri(managementUri)
            .poll(new HttpPollConfig<Boolean>(SERVICE_UP).onSuccess(HttpValueFunctions.responseCodeEquals(200))
                    .onFailureOrException(Functions.constant(false)))
            .build();//from  w  ww . j  av a  2 s . c  om
}

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

/**
 * Publish 4000 messages when there is no subscription. Default safe slot buffer count is 3 and slot window size
 * is 1000. So 3000 (3*1000) messages should not be interpreted by the periodic deletion task as those can be
 * allocated to slots in the near future. Periodic deletion task should delete the remaining 1000 (4000-3000)
 * expired messages. Then create a subscription. The messages allocated into slots and put into delivery path and
 * eventually get caught at the flusher as expired messages. Messages caught by the flusher is accumulated for a
 * batch delete. Then they should be deleted by the pre-delivery expiry message deletion task.
 *
 * @throws XPathExpressionException//from ww  w .ja  v  a2 s.c  om
 * @throws AndesClientConfigurationException
 * @throws NamingException
 * @throws JMSException
 * @throws AndesClientException
 * @throws IOException
 * @throws InterruptedException
 * @throws DataAccessUtilException
 */
@Test(groups = "wso2.mb", description = "Message expiration and Expired message deletion")
public void testMessageExpiry() throws XPathExpressionException, AndesClientConfigurationException,
        NamingException, JMSException, AndesClientException, IOException, InterruptedException,
        DataAccessUtilException, CloneNotSupportedException {

    long sendCount = 1000L;
    String queueName = "clusterExpiryCheckQueue1";

    String randomInstanceKey = getRandomMBInstance();

    AutomationContext tempContext = getAutomationContextWithKey(randomInstanceKey);

    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(
            tempContext.getInstance().getHosts().get("default"),
            Integer.parseInt(tempContext.getInstance().getPorts().get("amqp")), ExchangeType.QUEUE, queueName);

    //To create the queue, start the subscription and disconnect it.
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    consumerClient.startClient();
    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);

    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            tempContext.getInstance().getHosts().get("default"),
            Integer.parseInt(tempContext.getInstance().getPorts().get("amqp")), ExchangeType.QUEUE, queueName);
    publisherConfig.setNumberOfMessagesToSend(sendCount);
    publisherConfig.setJMSMessageExpiryTime(1000);

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    publisherClient.startClient();
    //2 seconds wait for all messages got expired
    Thread.sleep(2000);

    //Creating a consumer
    AndesJMSConsumerClientConfiguration consumerConfig2 = consumerConfig.clone();
    HostAndPort randomAMQPBrokerAddress = getRandomAMQPBrokerAddress();
    consumerConfig2.setHostName(randomAMQPBrokerAddress.getHostText());
    consumerConfig2.setPort(randomAMQPBrokerAddress.getPort());
    AndesClient consumerClient2 = new AndesClient(consumerConfig2, true);
    consumerClient2.startClient();

    //since all the messages get expired in 1 sec and caught at Message flusher. So there should not be any messages
    // to deliver
    Assert.assertEquals(consumerClient.getReceivedMessageCount(), 0, "Message receiving failed.");
    //30 seconds sleep for pre delivery expiry message deletion task  to delete the messages captured at flusher
    Thread.sleep(30000);

    //Evaluate messages left in database
    Assert.assertEquals(dataAccessUtil.getMessageCountForQueue(queueName), 0,
            "Expired message deletion failed.");

}

From source file:zipkin.cassandra.CassandraConfig.java

List<InetSocketAddress> parseContactPoints() {
    List<InetSocketAddress> result = new LinkedList<>();
    for (String contactPoint : contactPoints.split(",")) {
        HostAndPort parsed = HostAndPort.fromString(contactPoint);
        result.add(new InetSocketAddress(parsed.getHostText(), parsed.getPortOrDefault(9042)));
    }//from ww w.ja v  a  2  s  . co m
    return result;
}

From source file:org.apache.hadoop.hbase.rsgroup.RSGroupAdminClient.java

@Override
public void moveServers(Set<HostAndPort> servers, String targetGroup) throws IOException {
    Set<HBaseProtos.ServerName> hostPorts = Sets.newHashSet();
    for (HostAndPort el : servers) {
        hostPorts.add(HBaseProtos.ServerName.newBuilder().setHostName(el.getHostText()).setPort(el.getPort())
                .build());// w  w w .j  av a2 s. com
    }
    RSGroupAdminProtos.MoveServersRequest request = RSGroupAdminProtos.MoveServersRequest.newBuilder()
            .setTargetGroup(targetGroup).addAllServers(hostPorts).build();

    try {
        proxy.moveServers(null, request);
    } catch (ServiceException e) {
        throw ProtobufUtil.getRemoteException(e);
    }
}

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.
 *///from   w w w  .j ava  2  s .co m
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:org.apache.bookkeeper.stats.CodahaleMetricsProvider.java

@Override
public void start(Configuration conf) {
    initIfNecessary();// w  w w  .j  av  a 2 s . c  o m

    int metricsOutputFrequency = conf.getInt("codahaleStatsOutputFrequencySeconds", 60);
    String prefix = conf.getString("codahaleStatsPrefix", "");
    String graphiteHost = conf.getString("codahaleStatsGraphiteEndpoint");
    String csvDir = conf.getString("codahaleStatsCSVEndpoint");
    String slf4jCat = conf.getString("codahaleStatsSlf4jEndpoint");
    String jmxDomain = conf.getString("codahaleStatsJmxEndpoint");

    if (!Strings.isNullOrEmpty(graphiteHost)) {
        LOG.info("Configuring stats with graphite");
        HostAndPort addr = HostAndPort.fromString(graphiteHost);
        final Graphite graphite = new Graphite(new InetSocketAddress(addr.getHostText(), addr.getPort()));
        reporters.add(
                GraphiteReporter.forRegistry(getMetrics()).prefixedWith(prefix).convertRatesTo(TimeUnit.SECONDS)
                        .convertDurationsTo(TimeUnit.MILLISECONDS).filter(MetricFilter.ALL).build(graphite));
    }
    if (!Strings.isNullOrEmpty(csvDir)) {
        // NOTE: 1/ metrics output files are exclusive to a given process
        // 2/ the output directory must exist
        // 3/ if output files already exist they are not overwritten and there is no metrics output
        File outdir;
        if (!Strings.isNullOrEmpty(prefix)) {
            outdir = new File(csvDir, prefix);
        } else {
            outdir = new File(csvDir);
        }
        LOG.info("Configuring stats with csv output to directory [{}]", outdir.getAbsolutePath());
        reporters.add(CsvReporter.forRegistry(getMetrics()).convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS).build(outdir));
    }
    if (!Strings.isNullOrEmpty(slf4jCat)) {
        LOG.info("Configuring stats with slf4j");
        reporters.add(Slf4jReporter.forRegistry(getMetrics()).outputTo(LoggerFactory.getLogger(slf4jCat))
                .convertRatesTo(TimeUnit.SECONDS).convertDurationsTo(TimeUnit.MILLISECONDS).build());
    }
    if (!Strings.isNullOrEmpty(jmxDomain)) {
        LOG.info("Configuring stats with jmx");
        jmx = JmxReporter.forRegistry(getMetrics()).inDomain(jmxDomain).convertRatesTo(TimeUnit.SECONDS)
                .convertDurationsTo(TimeUnit.MILLISECONDS).build();
        jmx.start();
    }

    for (ScheduledReporter r : reporters) {
        r.start(metricsOutputFrequency, TimeUnit.SECONDS);
    }
}

From source file:org.apache.sentry.core.common.transport.SentryTransportFactory.java

/**
 * Connect to the endpoint and return a connected Thrift transport.
 * @return Connection to the endpoint/*from  w w  w  . j ava2  s  .c o  m*/
 * @throws IOException
 */
@Override
public TTransportWrapper getTransport(HostAndPort endpoint) throws Exception {
    return new TTransportWrapper(
            connectToServer(new InetSocketAddress(endpoint.getHostText(), endpoint.getPort())), endpoint);
}

From source file:brooklyn.entity.nosql.mongodb.ReplicaSetConfig.java

/** Removes the first entity with host and port matching the given address. */
public ReplicaSetConfig remove(HostAndPort address) {
    return remove(address.getHostText(), address.getPort());
}

From source file:com.smoketurner.dropwizard.riak.config.RiakConfiguration.java

@JsonIgnore
public RiakClient build(@Nonnull final Environment environment) throws UnknownHostException, KeyStoreException {
    Objects.requireNonNull(environment);

    final RiakNode.Builder builder = new RiakNode.Builder().withMinConnections(minConnections)
            .withMaxConnections(maxConnections)
            .withConnectionTimeout(Ints.checkedCast(connectionTimeout.toMilliseconds()))
            .withIdleTimeout(Ints.checkedCast(idleTimeout.toMilliseconds()))
            .withBlockOnMaxConnections(blockOnMaxConnections);

    if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password)
            && !Strings.isNullOrEmpty(keyStore)) {
        // TODO finish keyStore implementation
        final KeyStore keystore = KeyStore.getInstance("PKS");
        builder.withAuth(username, password, keystore);
    }//from w w  w. ja v a2 s  .  co  m

    final List<RiakNode> nodes = new ArrayList<>();
    for (HostAndPort address : this.nodes) {
        final RiakNode node = builder.withRemoteAddress(address.getHostText())
                .withRemotePort(address.getPortOrDefault(RiakNode.Builder.DEFAULT_REMOTE_PORT)).build();
        nodes.add(node);
    }

    DefaultCharset.set(StandardCharsets.UTF_8);

    final RiakCluster cluster = RiakCluster.builder(nodes).withExecutionAttempts(executionAttempts).build();
    environment.lifecycle().manage(new RiakClusterManager(cluster));

    final RiakClient client = new RiakClient(cluster);
    environment.healthChecks().register("riak", new RiakHealthCheck(client));
    return client;
}