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:com.streamsets.pipeline.destination.aerospike.AerospikeValidationUtil.java

public List<Host> validateConnectionString(List<Stage.ConfigIssue> issues, String connectionString,
        String configGroupName, String configName, Stage.Context context) {
    List<Host> clusterNodesList = new ArrayList<>();
    if (connectionString == null || connectionString.isEmpty()) {
        issues.add(context.createConfigIssue(configGroupName, configName, AerospikeErrors.AEROSPIKE_01,
                configName));//from  w  w  w  .  j  av a2  s. co  m
    } else {
        String[] nodes = connectionString.split(",");
        for (String node : nodes) {
            try {
                HostAndPort hostAndPort = HostAndPort.fromString(node);
                if (!hostAndPort.hasPort() || hostAndPort.getPort() < 0) {
                    issues.add(context.createConfigIssue(configGroupName, configName,
                            AerospikeErrors.AEROSPIKE_02, connectionString));
                } else {
                    clusterNodesList.add(new Host(hostAndPort.getHostText(), hostAndPort.getPort()));
                }
            } catch (IllegalArgumentException e) {
                issues.add(context.createConfigIssue(configGroupName, configName, AerospikeErrors.AEROSPIKE_02,
                        connectionString));
            }
        }
    }
    return clusterNodesList;
}

From source file:org.getlantern.firetweet.app.FiretweetApplication.java

@Override
public void onCreate() {
    StrictModeUtils.detectAll();//from   ww  w.j a v a  2  s  . c  om

    super.onCreate();

    Fabric.with(this, new Crashlytics());

    final Context context = this.getApplicationContext();
    File f = context.getFilesDir();
    String path = "";
    if (f != null) {
        path = f.getPath();
    }

    int startupTimeoutMillis = 30000;
    String trackingId = "UA-21408036-4";
    try {
        org.lantern.mobilesdk.StartResult result = Lantern.enable(context, startupTimeoutMillis, true,
                trackingId, null);
        HostAndPort hp = HostAndPort.fromString(result.getHTTPAddr());
        PROXY_HOST = hp.getHostText();
        PROXY_PORT = hp.getPort();
        Log.d(TAG, "Proxy host --> " + PROXY_HOST + " " + PROXY_PORT);
    } catch (Exception e) {
        Log.d(TAG, "Unable to start Lantern: " + e.getMessage());
    }

    mHandler = new Handler();
    mMessageBus = new Bus();
    //mPreferences = getSharedPreferences(SHARED_PREFERENCES_NAME, MODE_PRIVATE);
    //mPreferences.registerOnSharedPreferenceChangeListener(this);
    initializeAsyncTask();
    initAccountColor(this);
    initUserColor(this);

    final PackageManager pm = getPackageManager();
    final ComponentName main = new ComponentName(this, MainActivity.class);
    final ComponentName main2 = new ComponentName(this, MainHondaJOJOActivity.class);
    final boolean mainDisabled = pm
            .getComponentEnabledSetting(main) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
    final boolean main2Disabled = pm
            .getComponentEnabledSetting(main2) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
    final boolean noEntry = mainDisabled && main2Disabled;
    if (noEntry) {
        pm.setComponentEnabledSetting(main, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    } else if (!mainDisabled) {
        pm.setComponentEnabledSetting(main2, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }
    startRefreshServiceIfNeeded(this);
}

From source file:hm.binkley.util.XPropsConverter.java

public XPropsConverter() {
    register("address", value -> {
        final HostAndPort parsed = HostAndPort.fromString(value).requireBracketsForIPv6();
        return createUnresolved(parsed.getHostText(), parsed.getPort());
    });/* ww w.  j a  v a  2  s.  c o  m*/
    register("bundle", ResourceBundle::getBundle);
    register("byte", Byte::valueOf);
    register("class", Class::forName);
    register("date", LocalDate::parse);
    register("decimal", BigDecimal::new);
    register("double", Double::valueOf);
    register("duration", Duration::parse);
    register("file", File::new);
    register("float", Float::valueOf);
    register("inet", InetAddress::getByName);
    register("int", Integer::valueOf);
    register("integer", BigInteger::new);
    register("long", Long::valueOf);
    register("path", Paths::get);
    register("period", Period::parse);
    register("regex", Pattern::compile);
    register("resource",
            value -> new DefaultResourceLoader(currentThread().getContextClassLoader()).getResource(value));
    register("resource*",
            value -> asList(new PathMatchingResourcePatternResolver(currentThread().getContextClassLoader())
                    .getResources(value)));
    register("short", Short::valueOf);
    register("time", LocalDateTime::parse);
    register("timestamp", Instant::parse);
    register("tz", TimeZone::getTimeZone);
    register("uri", URI::create);
    register("url", URL::new);
}

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

@Override
protected void connectSensors() {
    super.connectSensors();
    connectServiceUpIsRunning();//  w ww. j a va  2  s  .  c  o  m

    int port = getAttribute(MongoDBServer.PORT);
    HostAndPort accessibleAddress = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port);
    setAttribute(MONGO_SERVER_ENDPOINT,
            String.format("http://%s:%d", accessibleAddress.getHostText(), accessibleAddress.getPort()));

    int httpConsolePort = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(HTTP_PORT))
            .getPort();
    setAttribute(HTTP_INTERFACE_URL,
            String.format("http://%s:%d", accessibleAddress.getHostText(), httpConsolePort));

    try {
        client = MongoDBClientSupport.forServer(this);
    } catch (UnknownHostException e) {
        LOG.warn("Unable to create client connection to {}, not connecting sensors: {} ", this, e.getMessage());
        return;
    }

    serviceStats = FunctionFeed.builder().entity(this)
            .poll(new FunctionPollConfig<Object, BasicBSONObject>(STATUS_BSON).period(2, TimeUnit.SECONDS)
                    .callable(new Callable<BasicBSONObject>() {
                        @Override
                        public BasicBSONObject call() throws Exception {
                            return MongoDBServerImpl.this.getAttribute(SERVICE_UP) ? client.getServerStatus()
                                    : null;
                        }
                    }).onException(Functions.<BasicBSONObject>constant(null)))
            .build();

    if (isReplicaSetMember()) {
        replicaSetStats = FunctionFeed.builder().entity(this)
                .poll(new FunctionPollConfig<Object, ReplicaSetMemberStatus>(REPLICA_SET_MEMBER_STATUS)
                        .period(2, TimeUnit.SECONDS).callable(new Callable<ReplicaSetMemberStatus>() {
                            /**
                             * Calls {@link MongoDBClientSupport#getReplicaSetStatus} and
                             * extracts <code>myState</code> from the response.
                             * @return
                             *      The appropriate {@link brooklyn.entity.nosql.mongodb.ReplicaSetMemberStatus}
                             *      if <code>myState</code> was non-null, {@link ReplicaSetMemberStatus#UNKNOWN} otherwise.
                             */
                            @Override
                            public ReplicaSetMemberStatus call() {
                                BasicBSONObject serverStatus = client.getReplicaSetStatus();
                                int state = serverStatus.getInt("myState", -1);
                                return ReplicaSetMemberStatus.fromCode(state);
                            }
                        }).onException(Functions.constant(ReplicaSetMemberStatus.UNKNOWN)))
                .build();
    } else {
        setAttribute(IS_PRIMARY_FOR_REPLICA_SET, false);
        setAttribute(IS_SECONDARY_FOR_REPLICA_SET, false);
    }

    // Take interesting details from STATUS.
    subscribe(this, STATUS_BSON, new SensorEventListener<BasicBSONObject>() {
        @Override
        public void onEvent(SensorEvent<BasicBSONObject> event) {
            BasicBSONObject map = event.getValue();
            if (map != null && !map.isEmpty()) {
                setAttribute(UPTIME_SECONDS, map.getDouble("uptime", 0));

                // Operations
                BasicBSONObject opcounters = (BasicBSONObject) map.get("opcounters");
                setAttribute(OPCOUNTERS_INSERTS, opcounters.getLong("insert", 0));
                setAttribute(OPCOUNTERS_QUERIES, opcounters.getLong("query", 0));
                setAttribute(OPCOUNTERS_UPDATES, opcounters.getLong("update", 0));
                setAttribute(OPCOUNTERS_DELETES, opcounters.getLong("delete", 0));
                setAttribute(OPCOUNTERS_GETMORE, opcounters.getLong("getmore", 0));
                setAttribute(OPCOUNTERS_COMMAND, opcounters.getLong("command", 0));

                // Network stats
                BasicBSONObject network = (BasicBSONObject) map.get("network");
                setAttribute(NETWORK_BYTES_IN, network.getLong("bytesIn", 0));
                setAttribute(NETWORK_BYTES_OUT, network.getLong("bytesOut", 0));
                setAttribute(NETWORK_NUM_REQUESTS, network.getLong("numRequests", 0));

                // Replica set stats
                BasicBSONObject repl = (BasicBSONObject) map.get("repl");
                if (isReplicaSetMember() && repl != null) {
                    setAttribute(IS_PRIMARY_FOR_REPLICA_SET, repl.getBoolean("ismaster"));
                    setAttribute(IS_SECONDARY_FOR_REPLICA_SET, repl.getBoolean("secondary"));
                    setAttribute(REPLICA_SET_PRIMARY_ENDPOINT, repl.getString("primary"));
                }
            }
        }
    });
}

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(//from  w w  w.  jav a  2  s  .c o  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 = 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  av a  2 s  . com*/
                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: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  .j  a  v a 2  s .  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:ezbake.discovery.servicediscovery.ZooKeeperServiceRegistry.java

@Override
public List<ServiceInstance> listInstances(String applicationName, String serviceName, String serviceType)
        throws DiscoveryException {
    String path = formatZooKeeperServiceTypePath(applicationName, serviceName, serviceType);
    List<ServiceInstance> instances = new ArrayList<ServiceInstance>();
    InterProcessLock readLock = readWriteLock.readLock();
    Exception maybeError = null;/*ww w  .jav a  2s.  c o  m*/

    try {
        List<String> children;
        readLock.acquire();

        if (client.checkExists().forPath(path) == null) {
            children = Collections.emptyList();
        } else {
            children = client.getChildren().forPath(path);
        }

        for (String c : children) {
            HostAndPort hostAndPort = HostAndPort.fromString(c);
            instances.add(new BasicServiceInstance(applicationName, serviceName, serviceType,
                    hostAndPort.getHostText(), hostAndPort.getPort()));
        }

    } catch (Exception e) {
        maybeError = e;
    } finally {
        safelyRelease(readLock, maybeError);
    }

    return instances;
}

From source file:org.apache.hoya.providers.accumulo.AccumuloProviderService.java

@Override
public TreeMap<String, URL> buildMonitorDetails(ClusterDescription clusterDesc) {
    TreeMap<String, URL> map = new TreeMap<String, URL>();

    map.put("Active Accumulo Master (RPC): " + getInfoAvoidingNull(clusterDesc, AccumuloKeys.MASTER_ADDRESS),
            null);/*from   ww w. jav  a  2  s.  co  m*/

    String monitorKey = "Active Accumulo Monitor: ";
    String monitorAddr = getInfoAvoidingNull(clusterDesc, AccumuloKeys.MONITOR_ADDRESS);
    if (!StringUtils.isBlank(monitorAddr)) {
        try {
            HostAndPort hostPort = HostAndPort.fromString(monitorAddr);
            map.put(monitorKey, new URL("http", hostPort.getHostText(), hostPort.getPort(), ""));
        } catch (Exception e) {
            log.debug("Caught exception parsing Accumulo monitor URL", e);
            map.put(monitorKey + "N/A", null);
        }
    } else {
        map.put(monitorKey + "N/A", null);
    }

    return map;
}

From source file:com.spotify.docker.client.DefaultDockerClient.java

/**
 * Create a new {@link DefaultDockerClient} builder prepopulated with values loaded
 * from the DOCKER_HOST and DOCKER_CERT_PATH environment variables.
 * @return Returns a builder that can be used to further customize and then build the client.
 * @throws DockerCertificateException if we could not build a DockerCertificates object
 *///from w w w.  j  ava  2  s.c o m
public static Builder fromEnv() throws DockerCertificateException {
    final String endpoint = fromNullable(getenv("DOCKER_HOST")).or(defaultEndpoint());
    final Path dockerCertPath = Paths.get(fromNullable(getenv("DOCKER_CERT_PATH")).or(defaultCertPath()));

    final Builder builder = new Builder();

    final Optional<DockerCertificates> certs = DockerCertificates.builder().dockerCertPath(dockerCertPath)
            .build();

    if (endpoint.startsWith(UNIX_SCHEME + "://")) {
        builder.uri(endpoint);
    } else {
        final String stripped = endpoint.replaceAll(".*://", "");
        final HostAndPort hostAndPort = HostAndPort.fromString(stripped);
        final String hostText = hostAndPort.getHostText();
        final String scheme = certs.isPresent() ? "https" : "http";

        final int port = hostAndPort.getPortOrDefault(DEFAULT_PORT);
        final String address = isNullOrEmpty(hostText) ? DEFAULT_HOST : hostText;

        builder.uri(scheme + "://" + address + ":" + port);
    }

    if (certs.isPresent()) {
        builder.dockerCertificates(certs.get());
    }

    return builder;
}