com.google.common.net.HostAndPort Java Examples
The following examples show how to use
com.google.common.net.HostAndPort.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ResolvingEnsembleProvider.java From curator-extensions with Apache License 2.0 | 6 votes |
@Override public String getConnectionString() { StringBuilder connectStringBuilder = new StringBuilder(); SortedSet<String> addresses = new TreeSet<>(); for (InetSocketAddress hostAndPort : _connectStringParser.getServerAddresses()) { try { for (InetAddress address : _resolver.lookupAllHostAddr(hostAndPort.getHostName())) { addresses.add(HostAndPort.fromParts(address.getHostAddress(), hostAndPort.getPort()).toString()); } } catch (UnknownHostException e) { // Leave unresolvable host in connect string as-is. addresses.add(hostAndPort.toString()); } } Joiner.on(',').appendTo(connectStringBuilder, addresses); if (_connectStringParser.getChrootPath() != null) { connectStringBuilder.append(_connectStringParser.getChrootPath()); } return connectStringBuilder.toString(); }
Example #2
Source File: KafkaLowLevelConsumer08.java From datacollector with Apache License 2.0 | 6 votes |
public KafkaLowLevelConsumer08( String topic, int partition, HostAndPort broker, int minFetchSize, int maxFetchSize, int maxWaitTime, String clientName ) { this.topic = topic; this.partition = partition; this.broker = broker; this.maxFetchSize = maxFetchSize; this.minFetchSize = minFetchSize; this.maxWaitTime = maxWaitTime; this.clientName = clientName; this.replicaBrokers = new ArrayList<>(); }
Example #3
Source File: OnPublicNetworkEnricherTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test public <T> void testDoesNotDoRegexMatchingWhenSensorsSpecified() throws Exception { AttributeSensor<String> sensor = Sensors.newStringSensor("mysensor"); AttributeSensor<Integer> intPort = Sensors.newIntegerSensor("int.port"); entity.sensors().set(Attributes.SUBNET_ADDRESS, "127.0.0.1"); entity.sensors().set(intPort, 1234); entity.sensors().set(sensor, "127.0.0.1:1234"); portForwardManager.associate("myPublicIp", HostAndPort.fromParts("mypublichost", 5678), machine, 1234); entity.addLocations(ImmutableList.of(machine)); entity.enrichers().add(EnricherSpec.create(OnPublicNetworkEnricher.class) .configure(OnPublicNetworkEnricher.SENSORS, ImmutableList.of(sensor))); assertAttributeEqualsEventually("mysensor.mapped.public", "mypublichost:5678"); assertAttributeEqualsContinually("int.endpoint.mapped.public", null, VERY_SHORT_WAIT); }
Example #4
Source File: ValidHostAndPort.java From connect-utils with Apache License 2.0 | 6 votes |
void validate(final String setting, final String input) { HostAndPort hostAndPort = HostAndPort.fromString(input); if (this.requireBracketsForIPv6) { hostAndPort = hostAndPort.requireBracketsForIPv6(); } if (null != this.defaultPort) { hostAndPort.withDefaultPort(this.defaultPort); } if (Strings.isNullOrEmpty(hostAndPort.getHost())) { 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)); } }
Example #5
Source File: TestDriftNettyServerTransport.java From drift with Apache License 2.0 | 6 votes |
private static int testServerMethodInvoker(ServerMethodInvoker methodInvoker, boolean assumeClientsSupportOutOfOrderResponses, List<ToIntFunction<HostAndPort>> clients) { DriftNettyServerConfig config = new DriftNettyServerConfig() .setAssumeClientsSupportOutOfOrderResponses(assumeClientsSupportOutOfOrderResponses); TestingPooledByteBufAllocator testingAllocator = new TestingPooledByteBufAllocator(); ServerTransport serverTransport = new DriftNettyServerTransportFactory(config, testingAllocator).createServerTransport(methodInvoker); try { serverTransport.start(); HostAndPort address = HostAndPort.fromParts("localhost", ((DriftNettyServerTransport) serverTransport).getPort()); int sum = 0; for (ToIntFunction<HostAndPort> client : clients) { sum += client.applyAsInt(address); } return sum; } finally { serverTransport.shutdown(); testingAllocator.close(); } }
Example #6
Source File: ParquetGroupScanUtils.java From dremio-oss with Apache License 2.0 | 6 votes |
public static EndpointByteMap buildEndpointByteMap( Set<HostAndPort> activeHostMap, Set<HostAndPort> activeHostPortMap, Map<com.google.common.net.HostAndPort, Float> affinities, long totalLength) { EndpointByteMap endpointByteMap = new EndpointByteMapImpl(); for (HostAndPort host : affinities.keySet()) { HostAndPort endpoint = null; if (!host.hasPort()) { if (activeHostMap.contains(host)) { endpoint = host; } } else { // multi executor deployment and affinity provider is sensitive to the port // picking the map late as it allows a source that contains files in HDFS and S3 if (activeHostPortMap.contains(host)) { endpoint = host; } } if (endpoint != null) { endpointByteMap.add(endpoint, (long) (affinities.get(host) * totalLength)); } } return endpointByteMap; }
Example #7
Source File: LegacyApacheThriftTesterUtil.java From drift with Apache License 2.0 | 6 votes |
private static TSocket createClientSocket(boolean secure, HostAndPort address) throws TTransportException { if (!secure) { return new TSocket(address.getHost(), address.getPort()); } try { SSLContext serverSslContext = ClientTestUtils.getClientSslContext(); SSLSocket clientSocket = (SSLSocket) serverSslContext.getSocketFactory().createSocket(address.getHost(), address.getPort()); // clientSocket.setSoTimeout(timeout); return new TSocket(clientSocket); } catch (Exception e) { throw new TTransportException("Error initializing secure socket", e); } }
Example #8
Source File: SingularityAbort.java From Singularity with Apache License 2.0 | 6 votes |
@Inject public SingularityAbort( SingularitySmtpSender smtpSender, ServerProvider serverProvider, SingularityConfiguration configuration, SingularityExceptionNotifier exceptionNotifier, Injector injector, @Named(SingularityMainModule.HTTP_HOST_AND_PORT) HostAndPort hostAndPort ) { this.maybeSmtpConfiguration = configuration.getSmtpConfigurationOptional(); this.serverProvider = serverProvider; this.smtpSender = smtpSender; this.exceptionNotifier = exceptionNotifier; this.injector = injector; this.hostAndPort = hostAndPort; }
Example #9
Source File: ZooKeeperDiscovery.java From soabase with Apache License 2.0 | 6 votes |
@Override public void setForcedState(String serviceName, String instanceId, ForcedState forcedState) { try { ServiceInstance<Payload> foundInstance = discovery.queryForInstance(serviceName, instanceId); if ( foundInstance != null ) { DiscoveryInstance soaInstance = toSoaInstance(foundInstance); Payload oldPayload = foundInstance.getPayload(); Payload newPayload = new Payload(null, oldPayload.getAdminPort(), oldPayload.getMetaData(), forcedState, oldPayload.getHealthyState()); ServiceInstance<Payload> updatedInstance = buildInstance(serviceName, HostAndPort.fromParts(soaInstance.getHost(), soaInstance.getPort()), newPayload, instanceId, soaInstance.getHost()); discovery.updateService(updatedInstance); } // TODO else? } catch ( Exception e ) { log.error("Could not update service: " + (serviceName + ":" + instanceId), e); throw new RuntimeException(e); } }
Example #10
Source File: TestClientsWithDriftNettyServer.java From drift with Apache License 2.0 | 6 votes |
private static void testDriftServer(DriftService service, Consumer<HostAndPort> task) { DriftNettyServerConfig config = new DriftNettyServerConfig() .setSslEnabled(true) .setTrustCertificate(ClientTestUtils.getCertificateChainFile()) .setKey(ClientTestUtils.getPrivateKeyFile()); TestingPooledByteBufAllocator testingAllocator = new TestingPooledByteBufAllocator(); DriftServer driftServer = new DriftServer( new DriftNettyServerTransportFactory(config, testingAllocator), CODEC_MANAGER, new NullMethodInvocationStatsFactory(), ImmutableSet.of(service), ImmutableSet.of()); try { driftServer.start(); HostAndPort address = HostAndPort.fromParts("localhost", ((DriftNettyServerTransport) driftServer.getServerTransport()).getPort()); task.accept(address); } finally { driftServer.shutdown(); testingAllocator.close(); } }
Example #11
Source File: CompactionControlMonitorManager.java From emodb with Apache License 2.0 | 6 votes |
@Inject CompactionControlMonitorManager(LifeCycleRegistry lifeCycle, @LocalCompactionControl CompactionControlSource compactionControlSource, @GlobalFullConsistencyZooKeeper CuratorFramework curator, @SelfHostAndPort HostAndPort self, Clock clock, LeaderServiceTask dropwizardTask, final MetricRegistry metricRegistry) { LeaderService leaderService = new LeaderService( curator, "/leader/compaction-control-monitor", self.toString(), "Leader-CompactionControlMonitor", 30, TimeUnit.MINUTES, () -> new CompactionControlMonitor(compactionControlSource, clock, metricRegistry) ); ServiceFailureListener.listenTo(leaderService, metricRegistry); dropwizardTask.register("stash-runtime-monitor", leaderService); lifeCycle.manage(new ManagedGuavaService(leaderService)); }
Example #12
Source File: GraphiteSenderProvider.java From graylog-plugin-metrics-reporter with GNU General Public License v3.0 | 6 votes |
@Override public GraphiteSender get() { HostAndPort hostAndPort = configuration.getAddress(); String host = hostAndPort.getHost(); int port = hostAndPort.getPortOrDefault(2003); switch (configuration.getProtocol()) { case PICKLE: return new PickledGraphite( host, port, SocketFactory.getDefault(), configuration.getCharset(), configuration.getPickleBatchSize()); case TCP: return new Graphite(host, port, SocketFactory.getDefault(), configuration.getCharset()); case UDP: return new GraphiteUDP(host, port); default: throw new IllegalArgumentException("Unknown Graphite protocol \"" + configuration.getProtocol() + "\""); } }
Example #13
Source File: AbstractOnNetworkEnricher.java From brooklyn-server with Apache License 2.0 | 6 votes |
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("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(); } }
Example #14
Source File: GuavaCachedMongoClientFactory.java From mongowp with Apache License 2.0 | 6 votes |
@Override public MongoClient createClient(HostAndPort address) throws UnreachableMongoServerException { try { return cachedClients.get(address, () -> { return new CachedMongoClient(factory.createClient(address)); }); } catch (ExecutionException ex) { Throwable cause = ex.getCause(); if (cause instanceof UnreachableMongoServerException) { throw (UnreachableMongoServerException) cause; } if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } throw new RuntimeException(ex); } }
Example #15
Source File: PortForwardManagerRebindTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test public void testAssociationPreservedOnRebind() throws Exception { String publicIpId = "5.6.7.8"; String publicAddress = "5.6.7.8"; TestEntity origEntity = origApp.createAndManageChild(EntitySpec.create(TestEntity.class).impl(MyEntity.class)); PortForwardManager origPortForwardManager = origEntity.getConfig(MyEntity.PORT_FORWARD_MANAGER); // We first wait for persisted, to ensure that it is the PortForwardManager.onChanged that is causing persistence. RebindTestUtils.waitForPersisted(origApp); origPortForwardManager.associate(publicIpId, HostAndPort.fromParts(publicAddress, 40080), origSimulatedMachine, 80); newApp = rebind(); // After rebind, confirm that lookups still work TestEntity newEntity = (TestEntity) Iterables.find(newApp.getChildren(), Predicates.instanceOf(TestEntity.class)); Location newSimulatedMachine = newApp.getManagementContext().getLocationManager().getLocation(origSimulatedMachine.getId()); PortForwardManager newPortForwardManager = newEntity.getConfig(MyEntity.PORT_FORWARD_MANAGER); assertEquals(newPortForwardManager.lookup(newSimulatedMachine, 80), HostAndPort.fromParts(publicAddress, 40080)); assertEquals(newPortForwardManager.lookup(publicIpId, 80), HostAndPort.fromParts(publicAddress, 40080)); }
Example #16
Source File: PortForwardManagerTest.java From brooklyn-server with Apache License 2.0 | 6 votes |
@Test public void testForgetPortMappingsOfMachine() throws Exception { String publicIpId = "myipid"; String publicIpId2 = "myipid2"; String publicAddress = "5.6.7.8"; pfm.associate(publicIpId, HostAndPort.fromParts(publicAddress, 40080), machine1, 80); pfm.associate(publicIpId, HostAndPort.fromParts(publicAddress, 40081), machine1, 81); pfm.associate(publicIpId2, HostAndPort.fromParts(publicAddress, 40082), machine2, 80); pfm.forgetPortMappings(machine1); assertNull(pfm.lookup(machine1, 80)); assertNull(pfm.lookup(machine1, 81)); assertNull(pfm.lookup(publicIpId, 80)); assertEquals(pfm.lookup(machine2, 80), HostAndPort.fromParts(publicAddress, 40082)); }
Example #17
Source File: HttpUtil.java From AndroidHttpCapture with MIT License | 6 votes |
/** * Retrieves the host and, optionally, the port from the specified request's Host header. * * @param httpRequest HTTP request * @param includePort when true, include the port * @return the host and, optionally, the port specified in the request's Host header */ private static String parseHostHeader(HttpRequest httpRequest, boolean includePort) { // this header parsing logic is adapted from ClientToProxyConnection#identifyHostAndPort. List<String> hosts = httpRequest.headers().getAll(HttpHeaders.Names.HOST); if (!hosts.isEmpty()) { String hostAndPort = hosts.get(0); if (includePort) { return hostAndPort; } else { HostAndPort parsedHostAndPort = HostAndPort.fromString(hostAndPort); return parsedHostAndPort.getHost(); } } else { return null; } }
Example #18
Source File: JcloudsLocation.java From brooklyn-server with Apache License 2.0 | 6 votes |
protected ConnectivityResolverOptions.Builder getConnectivityOptionsBuilder(ConfigBag setup, boolean isWindows) { boolean waitForSshable = !"false".equalsIgnoreCase(setup.get(JcloudsLocationConfig.WAIT_FOR_SSHABLE)); boolean waitForWinRmable = !"false".equalsIgnoreCase(setup.get(JcloudsLocationConfig.WAIT_FOR_WINRM_AVAILABLE)); boolean waitForConnectable = isWindows ? waitForWinRmable : waitForSshable; boolean usePortForwarding = setup.get(JcloudsLocationConfig.USE_PORT_FORWARDING); boolean skipJcloudsSshing = usePortForwarding || Boolean.FALSE.equals(setup.get(JcloudsLocationConfig.USE_JCLOUDS_SSH_INIT)); ConnectivityResolverOptions.Builder builder = ConnectivityResolverOptions.builder() .waitForConnectable(waitForConnectable) .usePortForwarding(usePortForwarding) .skipJcloudsSshing(skipJcloudsSshing); String pollForFirstReachable = setup.get(JcloudsLocationConfig.POLL_FOR_FIRST_REACHABLE_ADDRESS); boolean pollEnabled = !"false".equalsIgnoreCase(pollForFirstReachable); if (pollEnabled) { Predicate<? super HostAndPort> reachableAddressesPredicate = getReachableAddressesPredicate(setup); Duration pollTimeout = "true".equals(pollForFirstReachable) ? Duration.FIVE_MINUTES : Duration.of(pollForFirstReachable); builder.pollForReachableAddresses(reachableAddressesPredicate, pollTimeout, true); } return builder; }
Example #19
Source File: ProxyToServerConnection.java From g4proxy with Apache License 2.0 | 6 votes |
/** * Build an {@link InetSocketAddress} for the given hostAndPort. * * @param hostAndPort String representation of the host and port * @param proxyServer the current {@link DefaultHttpProxyServer} * @return a resolved InetSocketAddress for the specified hostAndPort * @throws UnknownHostException if hostAndPort could not be resolved, or if the input string could not be parsed into * a host and port. */ public static InetSocketAddress addressFor(String hostAndPort, DefaultHttpProxyServer proxyServer) throws UnknownHostException { HostAndPort parsedHostAndPort; try { parsedHostAndPort = HostAndPort.fromString(hostAndPort); } catch (IllegalArgumentException e) { // we couldn't understand the hostAndPort string, so there is no way we can resolve it. throw new UnknownHostException(hostAndPort); } String host = parsedHostAndPort.getHost(); int port = parsedHostAndPort.getPortOrDefault(80); return proxyServer.getServerResolver().resolve(host, port); }
Example #20
Source File: ServiceConfigManager.java From grpc-swagger with MIT License | 5 votes |
@Nullable public static HostAndPort getEndPoint(String fullServiceName) { ServiceConfig config = STORAGE.get(fullServiceName); if (config == null) { return null; } return HostAndPort.fromString(config.getEndPoint()); }
Example #21
Source File: MapR61StreamsValidationUtil11.java From datacollector with Apache License 2.0 | 5 votes |
@Override public List<HostAndPort> validateKafkaBrokerConnectionString( List<Stage.ConfigIssue> issues, String connectionString, String configGroupName, String configName, Stage.Context context ) { List<HostAndPort> kafkaBrokers = new ArrayList<>(); return kafkaBrokers; }
Example #22
Source File: CouchbaseNodeSshDriver.java From brooklyn-library with Apache License 2.0 | 5 votes |
private Iterable<HostAndPort> getNodesHostAndPort() { Group group = Iterables.getFirst(getEntity().groups(), null); if (group == null) return Lists.newArrayList(); return Iterables.transform(group.getAttribute(CouchbaseCluster.COUCHBASE_CLUSTER_UP_NODES), new Function<Entity, HostAndPort>() { @Override public HostAndPort apply(Entity input) { return BrooklynAccessUtils.getBrooklynAccessibleAddress(input, input.getAttribute(CouchbaseNode.COUCHBASE_WEB_ADMIN_PORT)); } }); }
Example #23
Source File: HibernateOgmConfiguration.java From jpa-unit with Apache License 2.0 | 5 votes |
private void configureServerAddresses(final Map<String, Object> properties) { final List<HostAndPort> hostsAndPorts = parse((String) properties.get(HIBERNATE_OGM_DATASTORE_HOST)); serverAddresses = hostsAndPorts.stream() .map(h -> new ServerAddress(h.getHost(), h.hasPort() ? h.getPort() : ServerAddress.defaultPort())) .collect(Collectors.toList()); if (serverAddresses.isEmpty()) { serverAddresses.add(new ServerAddress()); } }
Example #24
Source File: TransportProvider.java From graylog-plugin-metrics-reporter with GNU General Public License v3.0 | 5 votes |
@Override public Transport get() { switch (configuration.getTransport()) { case HTTP: { final HostAndPort proxy = configuration.getHttpProxy(); final Duration connectTimeout = configuration.getHttpConnectTimeout(); final Duration socketTimeout = configuration.getHttpSocketTimeout(); final HttpTransport.Builder builder = new HttpTransport.Builder() .withApiKey(configuration.getApiKey()) .withConnectTimeout(Ints.saturatedCast(connectTimeout.toMilliseconds())) .withSocketTimeout(Ints.saturatedCast(socketTimeout.toMilliseconds())); if (proxy != null) { builder.withProxy(proxy.getHost(), proxy.getPortOrDefault(8080)); } return builder.build(); } case UDP: { final HostAndPort udpAddress = configuration.getUdpAddress(); return new UdpTransport.Builder() .withStatsdHost(udpAddress.getHost()) .withPort(udpAddress.getPortOrDefault(8125)) .withPrefix(configuration.getUdpPrefix()) .build(); } default: throw new IllegalArgumentException("Unknown Datadog transport \"" + configuration.getTransport() + "\""); } }
Example #25
Source File: QueueModuleTest.java From emodb with Apache License 2.0 | 5 votes |
@Test public void testQueueModule() { Injector injector = Guice.createInjector(new AbstractModule() { @Override protected void configure() { binder().requireExplicitBindings(); // construct the minimum necessary elements to allow a Queue module to be created. bind(QueueConfiguration.class).toInstance(new QueueConfiguration() .setCassandraConfiguration(new CassandraConfiguration() .setCluster("Test Cluster") .setSeeds("127.0.0.1") .setPartitioner("random") .setKeyspaces(ImmutableMap.of( "queue", new KeyspaceConfiguration())))); bind(HealthCheckRegistry.class).toInstance(mock(HealthCheckRegistry.class)); bind(LeaderServiceTask.class).toInstance(mock(LeaderServiceTask.class)); bind(LifeCycleRegistry.class).toInstance(new SimpleLifeCycleRegistry()); bind(TaskRegistry.class).toInstance(mock(TaskRegistry.class)); bind(HostAndPort.class).annotatedWith(SelfHostAndPort.class).toInstance(HostAndPort.fromString("localhost:8080")); bind(CuratorFramework.class).annotatedWith(Global.class).toInstance(mock(CuratorFramework.class)); bind(CuratorFramework.class).annotatedWith(QueueZooKeeper.class).toInstance(mock(CuratorFramework.class)); bind(HostDiscovery.class).annotatedWith(DedupQueueHostDiscovery.class).toInstance(mock(HostDiscovery.class)); bind(JobHandlerRegistry.class).toInstance(mock(JobHandlerRegistry.class)); bind(JobService.class).toInstance(mock(JobService.class)); MetricRegistry metricRegistry = new MetricRegistry(); bind(MetricRegistry.class).toInstance(metricRegistry); bind(Clock.class).toInstance(mock(Clock.class)); install(new QueueModule(metricRegistry)); } }); assertNotNull(injector.getInstance(QueueService.class)); assertNotNull(injector.getInstance(DedupQueueService.class)); }
Example #26
Source File: LegacyKafkaClient.java From secor with Apache License 2.0 | 5 votes |
private SimpleConsumer createConsumer(TopicPartition topicPartition) { HostAndPort leader = findLeader(topicPartition); if (leader == null) { LOG.warn("no leader for topic {} partition {}", topicPartition.getTopic(), topicPartition.getPartition()); return null; } LOG.debug("leader for topic {} partition {} is {}", topicPartition.getTopic(), topicPartition.getPartition(), leader); final String clientName = getClientName(topicPartition); return createConsumer(leader.getHost(), leader.getPort(), clientName); }
Example #27
Source File: MongodManager.java From jpa-unit with Apache License 2.0 | 5 votes |
private List<IMongodConfig> buildMongodConfiguration(final List<HostAndPort> hosts, final boolean configureReplicaSet) throws IOException { final List<IMongodConfig> configs = new ArrayList<>(hosts.size()); for (final HostAndPort hostAndPort : hosts) { configs.add(buildMongodConfiguration(hostAndPort, configureReplicaSet)); } return configs; }
Example #28
Source File: ChangeSkinCore.java From ChangeSkin with MIT License | 5 votes |
public void load(boolean database) { saveDefaultFile("messages.yml"); saveDefaultFile("config.yml"); try { config = loadFile("config.yml"); int rateLimit = config.getInt("mojang-request-limit"); cooldownService = new CooldownService(Duration.ofSeconds(config.getInt("cooldown"))); autoUpdateDiff = Duration.ofMinutes(config.getInt("auto-skin-update")); List<HostAndPort> proxies = config.getStringList("proxies") .stream().map(HostAndPort::fromString).collect(toList()); skinApi = new MojangSkinApi(plugin.getLog(), rateLimit, proxies); if (database) { if (!setupDatabase(config.getSection("storage"))) { return; } loadDefaultSkins(config.getStringList("default-skins")); loadAccounts(config.getStringList("upload-accounts")); } Configuration messages = loadFile("messages.yml"); messages.getKeys() .stream() .filter(key -> messages.get(key) != null) .collect(toMap(identity(), messages::get)) .forEach((key, message) -> { String colored = CommonUtil.translateColorCodes((String) message); if (!colored.isEmpty()) { localeMessages.put(key, colored.replace("/newline", "\n")); } }); } catch (IOException ioEx) { plugin.getLog().info("Failed to load yaml file", ioEx); } }
Example #29
Source File: HddsUtils.java From hadoop-ozone with Apache License 2.0 | 5 votes |
/** * Gets the port if there is one, returns empty {@code OptionalInt} otherwise. * @param value String in host:port format. * @return Port */ public static OptionalInt getHostPort(String value) { if ((value == null) || value.isEmpty()) { return OptionalInt.empty(); } int port = HostAndPort.fromString(value).getPortOrDefault(NO_PORT); if (port == NO_PORT) { return OptionalInt.empty(); } else { return OptionalInt.of(port); } }
Example #30
Source File: HttpUtil.java From CapturePacket with MIT License | 5 votes |
/** * Retrieves the host and port from the specified URI. * * @param uriString URI to retrieve the host and port from * @return the host and port from the URI as a String * @throws URISyntaxException if the specified URI is invalid or cannot be parsed */ public static String getHostAndPortFromUri(String uriString) throws URISyntaxException { URI uri = new URI(uriString); if (uri.getPort() == -1) { return uri.getHost(); } else { return HostAndPort.fromParts(uri.getHost(), uri.getPort()).toString(); } }