List of usage examples for com.google.common.net HostAndPort getPort
public int getPort()
From source file:org.getlantern.firetweet.app.FiretweetApplication.java
@Override public void onCreate() { StrictModeUtils.detectAll();//from w w w. j a v a 2 s. com 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:brooklyn.entity.nosql.mongodb.MongoDBServerImpl.java
@Override protected void connectSensors() { super.connectSensors(); connectServiceUpIsRunning();/*from w w w. j a v a2 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: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;//from w ww . jav a 2s . co 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 w w w . j a v a 2 s . c o 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:brooklyn.entity.webapp.jboss.JBoss7ServerImpl.java
@Override protected void connectSensors() { super.connectSensors(); HostAndPort hp = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, getAttribute(MANAGEMENT_HTTP_PORT) + getConfig(PORT_INCREMENT)); String managementUri = String.format("http://%s:%s/management/subsystem/web/connector/http/read-resource", hp.getHostText(), hp.getPort()); setAttribute(MANAGEMENT_URL, managementUri); log.debug("JBoss sensors for " + this + " reading from " + managementUri); Map<String, String> includeRuntimeUriVars = ImmutableMap.of("include-runtime", "true"); httpFeed = HttpFeed.builder().entity(this).period(200).baseUri(managementUri) .credentials(getConfig(MANAGEMENT_USER), getConfig(MANAGEMENT_PASSWORD)) .poll(new HttpPollConfig<Integer>(MANAGEMENT_STATUS).onSuccess(HttpValueFunctions.responseCode())) .poll(new HttpPollConfig<Boolean>(MANAGEMENT_URL_UP) .onSuccess(HttpValueFunctions.responseCodeEquals(200)) .onFailureOrException(Functions.constant(false))) .poll(new HttpPollConfig<Integer>(REQUEST_COUNT).vars(includeRuntimeUriVars) .onSuccess(HttpValueFunctions.jsonContents("requestCount", Integer.class))) .poll(new HttpPollConfig<Integer>(ERROR_COUNT).vars(includeRuntimeUriVars) .onSuccess(HttpValueFunctions.jsonContents("errorCount", Integer.class))) .poll(new HttpPollConfig<Integer>(TOTAL_PROCESSING_TIME).vars(includeRuntimeUriVars) .onSuccess(HttpValueFunctions.jsonContents("processingTime", Integer.class))) .poll(new HttpPollConfig<Integer>(MAX_PROCESSING_TIME).vars(includeRuntimeUriVars) .onSuccess(HttpValueFunctions.jsonContents("maxTime", Integer.class))) .poll(new HttpPollConfig<Long>(BYTES_RECEIVED).vars(includeRuntimeUriVars) // jboss seems to report 0 even if it has received lots of requests; dunno why. .onSuccess(HttpValueFunctions.jsonContents("bytesReceived", Long.class))) .poll(new HttpPollConfig<Long>(BYTES_SENT).vars(includeRuntimeUriVars) .onSuccess(HttpValueFunctions.jsonContents("bytesSent", Long.class))) .build();//from w w w .ja v a 2s .com connectServiceUp(); }
From source file:com.pinterest.secor.common.KafkaClient.java
public SimpleConsumer createConsumer(TopicPartition topicPartition) { HostAndPort leader = findLeader(topicPartition); LOG.info("leader for topic {} partition {} is {}", topicPartition.getTopic(), topicPartition.getPartition(), leader.toString());//from w w w . j av a 2s . co m final String clientName = getClientName(topicPartition); return createConsumer(leader.getHostText(), leader.getPort(), clientName); }
From source file:com.pinterest.secor.tools.ProgressMonitor.java
/** * Helper to publish stats to statsD client *///from w w w. ja va 2 s. com private void exportToStatsD(List<Stat> stats) { HostAndPort hostPort = HostAndPort.fromString(mConfig.getStatsDHostPort()); // group stats by kafka group NonBlockingStatsDClient client = new NonBlockingStatsDClient(mConfig.getKafkaGroup(), hostPort.getHostText(), hostPort.getPort()); for (Stat stat : stats) { @SuppressWarnings("unchecked") Map<String, String> tags = (Map<String, String>) stat.get(Stat.STAT_KEYS.TAGS.getName()); String aspect = new StringBuilder((String) stat.get(Stat.STAT_KEYS.METRIC.getName())).append(PERIOD) .append(tags.get(Stat.STAT_KEYS.TOPIC.getName())).append(PERIOD) .append(tags.get(Stat.STAT_KEYS.PARTITION.getName())).toString(); client.recordGaugeValue(aspect, Long.parseLong((String) stat.get(Stat.STAT_KEYS.VALUE.getName()))); } }
From source file:org.apache.brooklyn.entity.nosql.mongodb.MongoDBServerImpl.java
@Override protected void connectSensors() { super.connectSensors(); connectServiceUpIsRunning();//from www . j ava 2s . c om int port = sensors().get(MongoDBServer.PORT); HostAndPort accessibleAddress = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, port); sensors().set(MONGO_SERVER_ENDPOINT, String.format("%s:%d", accessibleAddress.getHostText(), accessibleAddress.getPort())); int httpConsolePort = BrooklynAccessUtils.getBrooklynAccessibleAddress(this, sensors().get(HTTP_PORT)) .getPort(); sensors().set(HTTP_INTERFACE_URL, String.format("http://%s:%d", accessibleAddress.getHostText(), httpConsolePort)); if (clientAccessEnabled()) { 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.sensors().get(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 org.apache.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)) .suppressDuplicates(true)) .build(); } else { sensors().set(IS_PRIMARY_FOR_REPLICA_SET, false); sensors().set(IS_SECONDARY_FOR_REPLICA_SET, false); } } else { LOG.info("Not monitoring " + this + " to retrieve state via client API"); } // Take interesting details from STATUS. subscriptions().subscribe(this, STATUS_BSON, new SensorEventListener<BasicBSONObject>() { @Override public void onEvent(SensorEvent<BasicBSONObject> event) { BasicBSONObject map = event.getValue(); if (map != null && !map.isEmpty()) { sensors().set(UPTIME_SECONDS, map.getDouble("uptime", 0)); // Operations BasicBSONObject opcounters = (BasicBSONObject) map.get("opcounters"); sensors().set(OPCOUNTERS_INSERTS, opcounters.getLong("insert", 0)); sensors().set(OPCOUNTERS_QUERIES, opcounters.getLong("query", 0)); sensors().set(OPCOUNTERS_UPDATES, opcounters.getLong("update", 0)); sensors().set(OPCOUNTERS_DELETES, opcounters.getLong("delete", 0)); sensors().set(OPCOUNTERS_GETMORE, opcounters.getLong("getmore", 0)); sensors().set(OPCOUNTERS_COMMAND, opcounters.getLong("command", 0)); // Network stats BasicBSONObject network = (BasicBSONObject) map.get("network"); sensors().set(NETWORK_BYTES_IN, network.getLong("bytesIn", 0)); sensors().set(NETWORK_BYTES_OUT, network.getLong("bytesOut", 0)); sensors().set(NETWORK_NUM_REQUESTS, network.getLong("numRequests", 0)); // Replica set stats BasicBSONObject repl = (BasicBSONObject) map.get("repl"); if (isReplicaSetMember() && repl != null) { sensors().set(IS_PRIMARY_FOR_REPLICA_SET, repl.getBoolean("ismaster")); sensors().set(IS_SECONDARY_FOR_REPLICA_SET, repl.getBoolean("secondary")); sensors().set(REPLICA_SET_PRIMARY_ENDPOINT, repl.getString("primary")); } } } }); }
From source file:com.google.cloud.GrpcServiceOptions.java
/** * Returns a channel provider./*w w w . j a v a 2 s.com*/ */ protected ChannelProvider getChannelProvider() { HostAndPort hostAndPort = HostAndPort.fromString(getHost()); InstantiatingChannelProvider.Builder builder = InstantiatingChannelProvider.newBuilder() .setServiceAddress(hostAndPort.getHostText()).setPort(hostAndPort.getPort()) .setClientLibHeader(getGoogApiClientLibName(), firstNonNull(getLibraryVersion(), "")); Credentials scopedCredentials = getScopedCredentials(); if (scopedCredentials != null && scopedCredentials != NoCredentials.getInstance()) { builder.setCredentialsProvider(FixedCredentialsProvider.create(scopedCredentials)); } return builder.build(); }
From source file:com.payu.ratel.config.beans.ServiceRegisterPostProcessorFactory.java
@SuppressWarnings("PMD.EmptyCatchBlock") public ServiceRegisterPostProcessor create(ConfigurableListableBeanFactory beanFactory, RegisterStrategy registerStrategy) { SelfAddressProviderChain selfAddressProvider = beanFactory.getBean(SelfAddressProviderChain.class); if (selfAddressProvider == null) { throw new IllegalStateException("No SelfAddressProvider bean in context"); }/*from ww w .ja v a2 s . c o m*/ final HostAndPort hostAndPort = selfAddressProvider.getHostAndPort(); ServletContext servletContext = null; try { servletContext = beanFactory.getBean(ServletContext.class); } catch (NoSuchBeanDefinitionException e) { } final String contextRoot = servletContext != null ? servletContext.getContextPath() : ""; final String address = String.format("http://%s:%s%s%s", hostAndPort.getHostText(), hostAndPort.getPort(), contextRoot, RATEL_PATH); return new ServiceRegisterPostProcessor(beanFactory, registerStrategy, address); }