Java Code Examples for com.google.common.net.HostAndPort#getPortOrDefault()

The following examples show how to use com.google.common.net.HostAndPort#getPortOrDefault() . 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: DockerHost.java    From docker-client with Apache License 2.0 6 votes vote down vote up
private DockerHost(final String endpoint, final String certPath) {
  if (endpoint.startsWith("unix://")) {
    this.port = 0;
    this.address = DEFAULT_ADDRESS;
    this.host = endpoint;
    this.uri = URI.create(endpoint);
    this.bindUri = URI.create(endpoint);
  } else {
    final String stripped = endpoint.replaceAll(".*://", "");
    final HostAndPort hostAndPort = HostAndPort.fromString(stripped);
    final String hostText = hostAndPort.getHost();
    final String scheme = isNullOrEmpty(certPath) ? "http" : "https";

    this.port = hostAndPort.getPortOrDefault(defaultPort());
    this.address = isNullOrEmpty(hostText) ? DEFAULT_ADDRESS : hostText;
    this.host = address + ":" + port;
    this.uri = URI.create(scheme + "://" + address + ":" + port);
    this.bindUri = URI.create("tcp://" + address + ":" + port);
  }

  this.certPath = certPath;
}
 
Example 2
Source File: ProxyToServerConnection.java    From PowerTunnel with MIT License 6 votes vote down vote up
/**
 * 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 3
Source File: ProxyToServerConnection.java    From g4proxy with Apache License 2.0 6 votes vote down vote up
/**
 * 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 4
Source File: ProxyToServerConnection.java    From yfs with Apache License 2.0 6 votes vote down vote up
/**
 * 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 5
Source File: StyxHttpClient.java    From styx with Apache License 2.0 6 votes vote down vote up
private static Origin originFromRequest(LiveHttpRequest request, Boolean isHttps) {
    String hostAndPort = request.header(HOST)
            .orElseGet(() -> {
                checkArgument(request.url().isAbsolute(), "host header is not set for request=%s", request);
                return request.url().authority().map(Url.Authority::hostAndPort)
                        .orElseThrow(() -> new IllegalArgumentException("Cannot send request " + request + " as URL is not absolute and no HOST header is present"));
            });

    HostAndPort host = HostAndPort.fromString(hostAndPort);

    if (host.getPortOrDefault(-1) < 0) {
        host = host.withDefaultPort(isHttps ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT);
    }

    return newOriginBuilder(host.getHost(), host.getPort()).build();
}
 
Example 6
Source File: PCCMock.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
public static void main(final String[] args) throws InterruptedException, ExecutionException {
    Preconditions.checkArgument(args.length > 0, "Host and port of server must be provided.");
    final List<PCEPCapability> caps = new ArrayList<>();
    final PCEPSessionProposalFactory proposal = new BasePCEPSessionProposalFactory((short) 120, (short) 30, caps);
    final PCEPSessionNegotiatorFactory<? extends PCEPSession> snf
        = new DefaultPCEPSessionNegotiatorFactory(proposal, 0);
    final HostAndPort serverHostAndPort = HostAndPort.fromString(args[0]);
    final InetSocketAddress serverAddr = new InetSocketAddress(serverHostAndPort.getHost(), serverHostAndPort
            .getPortOrDefault(12345));
    final InetSocketAddress clientAddr = InetSocketAddressUtil.getRandomLoopbackInetSocketAddress(0);

    try (PCCDispatcherImpl pccDispatcher = new PCCDispatcherImpl(ServiceLoaderPCEPExtensionProviderContext
            .getSingletonInstance().getMessageHandlerRegistry())) {
        pccDispatcher.createClient(serverAddr, -1, SimpleSessionListener::new, snf,
                KeyMapping.getKeyMapping(), clientAddr).get();
    }
}
 
Example 7
Source File: GraphiteSenderProvider.java    From graylog-plugin-metrics-reporter with GNU General Public License v3.0 6 votes vote down vote up
@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 8
Source File: OpenTsdbProvider.java    From graylog-plugin-metrics-reporter with GNU General Public License v3.0 6 votes vote down vote up
@Override
public OpenTsdb get() {
    final OpenTsdbProtocol protocol = configuration.getProtocol();
    switch (protocol) {
        case HTTP:
            return OpenTsdb.forService(configuration.getHttpBaseUrl().toASCIIString())
                    .withConnectTimeout(configuration.getHttpConnectTimeout())
                    .withReadTimeout(configuration.getHttpReadTimeout())
                    .withGzipEnabled(configuration.isHttpEnableGzip())
                    .create();
        case TELNET:
            final HostAndPort address = configuration.getTelnetAddress();
            final String host = address.getHost();
            final int port = address.getPortOrDefault(MetricsOpenTsdbReporterConfiguration.DEFAULT_PORT);

            return OpenTsdbTelnet.forService(host, port).create();
        default:
            throw new IllegalStateException("Invalid OpenTSDB protocol: " + protocol);
    }
}
 
Example 9
Source File: InetSocketAddressUtil.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
public static InetSocketAddress getInetSocketAddress(final String hostPortString, final Integer defaultPort) {
    final HostAndPort hostAndPort = HostAndPort.fromString(hostPortString);
    if (defaultPort != null) {
        return new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPortOrDefault(defaultPort));
    }
    return new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPort());
}
 
Example 10
Source File: DefaultDockerClient.java    From docker-client with Apache License 2.0 5 votes vote down vote up
/**
 * 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
 */
public static Builder fromEnv() throws DockerCertificateException {
  final String endpoint = DockerHost.endpointFromEnv();
  final Path dockerCertPath = Paths.get(Iterables.find(
      Arrays.asList(DockerHost.certPathFromEnv(),
          DockerHost.configPathFromEnv(),
          DockerHost.defaultCertPath()),
      Predicates.notNull()));

  final Builder builder = new Builder();

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

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

    final int port = hostAndPort.getPortOrDefault(DockerHost.defaultPort());
    final String address = isNullOrEmpty(hostText) ? DockerHost.defaultAddress() : hostText;

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

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

  return builder;
}
 
Example 11
Source File: HttpHeaderUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Nullable
private static InetSocketAddress createInetSocketAddress(String address) throws UnknownHostException {
    final char firstChar = address.charAt(0);
    if (firstChar == '_' ||
        (firstChar == 'u' && "unknown".equals(address))) {
        // To early return when the address is not an IP address.
        // - an obfuscated identifier which must start with '_'
        //   - https://tools.ietf.org/html/rfc7239#section-6.3
        // - the "unknown" identifier
        return null;
    }

    // Remote quotes. e.g. "[2001:db8:cafe::17]:4711" => [2001:db8:cafe::17]:4711
    final String addr = firstChar == '"' ? QUOTED_STRING_TRIMMER.trimFrom(address) : address;
    try {
        final HostAndPort hostAndPort = HostAndPort.fromString(addr);
        final byte[] addressBytes = NetUtil.createByteArrayFromIpAddressString(hostAndPort.getHost());
        if (addressBytes == null) {
            logger.debug("Failed to parse an address: {}", address);
            return null;
        }
        return new InetSocketAddress(InetAddress.getByAddress(addressBytes),
                                     hostAndPort.getPortOrDefault(0));
    } catch (IllegalArgumentException e) {
        logger.debug("Failed to parse an address: {}", address, e);
        return null;
    }
}
 
Example 12
Source File: TestServer.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Converts a bind address into an address that other machines can use to connect here. */
private static HostAndPort createUrlAddress(HostAndPort address) {
  if (address.getHost().equals("::") || address.getHost().equals("0.0.0.0")) {
    return address.getPortOrDefault(DEFAULT_PORT) == DEFAULT_PORT
        ? HostAndPort.fromHost(getCanonicalHostName())
        : HostAndPort.fromParts(getCanonicalHostName(), address.getPort());
  } else {
    return address.getPortOrDefault(DEFAULT_PORT) == DEFAULT_PORT
        ? HostAndPort.fromHost(address.getHost())
        : address;
  }
}
 
Example 13
Source File: Configuration.java    From azure-cosmosdb-java with MIT License 5 votes vote down vote up
@SuppressWarnings("UnstableApiUsage")
private synchronized MeterRegistry graphiteMeterRegistry(String serviceAddress) {

    if (this.graphiteMeterRegistry == null) {

        HostAndPort address = HostAndPort.fromString(serviceAddress);

        String host = address.getHost();
        int port = address.getPortOrDefault(DEFAULT_GRAPHITE_SERVER_PORT);
        boolean enabled = !Boolean.getBoolean("cosmos.monitoring.graphite.disabled");
        Duration step = Duration.ofSeconds(Integer.getInteger("cosmos.monitoring.graphite.step", this.printingInterval));

        final GraphiteConfig config = new GraphiteConfig() {

            private String[] tagNames = { "source" };

            @Override
            @Nullable
            public String get(@Nullable String key) {
                return null;
            }

            @Override
            public boolean enabled() {
                return enabled;
            }

            @Override
            @Nullable
            public String host() {
                return host;
            }

            @Override
            @Nullable
            public int port() {
                return port;
            }

            @Override
            @Nullable
            public Duration step() {
                return step;
            }

            @Override
            @Nullable
            public String[] tagsAsPrefix() {
                return this.tagNames;
            }
        };

        this.graphiteMeterRegistry = new GraphiteMeterRegistry(config, Clock.SYSTEM);
        String source;

        try {
            PercentEscaper escaper = new PercentEscaper("_-", false);
            source = escaper.escape(InetAddress.getLocalHost().getHostName());
        } catch (UnknownHostException error) {
            source = "unknown-host";
        }

        this.graphiteMeterRegistry.config()
            .namingConvention(NamingConvention.dot)
            .commonTags("source", source);
    }

    return this.graphiteMeterRegistry;
}
 
Example 14
Source File: ClientOptions.java    From presto with Apache License 2.0 5 votes vote down vote up
public static URI parseServer(String server)
{
    server = server.toLowerCase(ENGLISH);
    if (server.startsWith("http://") || server.startsWith("https://")) {
        return URI.create(server);
    }

    HostAndPort host = HostAndPort.fromString(server);
    try {
        return new URI("http", null, host.getHost(), host.getPortOrDefault(80), null, null, null);
    }
    catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 15
Source File: BenchmarkDriverOptions.java    From presto with Apache License 2.0 5 votes vote down vote up
private static URI parseServer(String server)
{
    server = server.toLowerCase(ENGLISH);
    if (server.startsWith("http://") || server.startsWith("https://")) {
        return URI.create(server);
    }

    HostAndPort host = HostAndPort.fromString(server);
    try {
        return new URI("http", null, host.getHost(), host.getPortOrDefault(80), null, null, null);
    }
    catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 16
Source File: ProxyToServerConnection.java    From PowerTunnel with MIT License 5 votes vote down vote up
/**
 * Similar to {@link #addressFor(String, DefaultHttpProxyServer)} except that it does
 * not resolve the address.
 * @param hostAndPort the host and port to parse.
 * @return an unresolved {@link InetSocketAddress}.
 */
private static InetSocketAddress unresolvedAddressFor(String hostAndPort) {
    HostAndPort parsedHostAndPort = HostAndPort.fromString(hostAndPort);
    String host = parsedHostAndPort.getHost();
    int port = parsedHostAndPort.getPortOrDefault(80);
    return InetSocketAddress.createUnresolved(host, port);
}
 
Example 17
Source File: DockerClientFactory.java    From ice with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * This method returns the DockerClient dependent on the current OS.
 * 
 * @return
 * @throws DockerCertificateException
 * @throws IOException
 * @throws InterruptedException
 */
public DockerClient getDockerClient() throws DockerCertificateException, IOException, InterruptedException {
	DockerClient client = null;

	// If this is not Linux, then we have to find DOCKER_HOST
	if (!Platform.getOS().equals(Platform.OS_LINUX)) {

		// See if we can get the DOCKER_HOST environment variaable
		String dockerHost = System.getenv("DOCKER_HOST");
		if (dockerHost == null) {

			// If not, run a script to see if we can get it
			File script = getDockerConnectionScript();
			String[] scriptExec = null;
			if (Platform.getOS().equals(Platform.OS_MACOSX)) {
				scriptExec = new String[] { script.getAbsolutePath() };
			} else if (Platform.getOS().equals(Platform.OS_WIN32)) {
				scriptExec = new String[] { "cmd.exe", "/C", script.getAbsolutePath() };
			}

			// Execute the script to get the DOCKER vars.
			Process process = new ProcessBuilder(scriptExec).start();
			process.waitFor();
			int exitValue = process.exitValue();
			if (exitValue == 0) {

				// Read them into a Properties object
				InputStream processInputStream = process.getInputStream();
				Properties dockerSettings = new Properties();
				// Properties.load screws up windows path separators
				// so if windows, just get the string from the stream
				if (Platform.getOS().equals(Platform.OS_WIN32)) {
					String result = streamToString(processInputStream).trim();
					String[] dockerEnvs = result.split(System.lineSeparator());
					for (String s : dockerEnvs) {
						String[] env = s.split("=");
						dockerSettings.put(env[0], env[1]);
					}
				} else {
					dockerSettings.load(processInputStream);
				}
				
				// Create the Builder object that wil build the DockerClient
				Builder builder = new Builder();

				// Get the DOCKER_HOST and CERT_PATH vars
				String endpoint = dockerSettings.getProperty("DOCKER_HOST");
				Path dockerCertPath = Paths.get(dockerSettings.getProperty("DOCKER_CERT_PATH"));

				System.out.println("DOCKERHOST: " + endpoint);
				System.out.println("DOCKER CERT PATH: " + dockerSettings.getProperty("DOCKER_CERT_PATH"));
				// Set up the certificates
				DockerCertificates certs = DockerCertificates.builder().dockerCertPath(dockerCertPath).build();

				// Set the data need for the builder.
				String stripped = endpoint.replaceAll(".*://", "");
				HostAndPort hostAndPort = HostAndPort.fromString(stripped);
				String hostText = hostAndPort.getHostText();
				String scheme = certs != null ? "https" : "http";
				int port = hostAndPort.getPortOrDefault(2375);
				String address = hostText;
				builder.uri(scheme + "://" + address + ":" + port);
				if (certs != null) {
					builder.dockerCertificates(certs);
				}

				// Build the Dockerclient!
				client = builder.build();

			} else {
				// log what happened if the process did not end as expected
				// an exit value of 1 should indicate no connection found
				InputStream processErrorStream = process.getErrorStream();
				String errorMessage = streamToString(processErrorStream);
				logger.error("Error in getting DOCKER variables: " + errorMessage);
			}
		} else {
			client = DefaultDockerClient.fromEnv().build();
		}
	} else {
		// It was equal to Linux, so just use the default stuff.
		client = DefaultDockerClient.fromEnv().build();
	}

	return client;
}
 
Example 18
Source File: StatsdProvider.java    From graylog-plugin-metrics-reporter with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Statsd get() {
    final HostAndPort address = configuration.getAddress();
    return new Statsd(address.getHost(), address.getPortOrDefault(8125));
}
 
Example 19
Source File: KafkaStreamReader.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private SimpleConsumer connect(BrokerEndPoint leader) {
   HostAndPort broker = config.getBrokerOverride(leader.id()).orElse(HostAndPort.fromParts(leader.host(), leader.port()));
   return new SimpleConsumer(broker.getHostText(), broker.getPortOrDefault(9092), config.getSoTimeoutMs(), config.getBufferSize(), config.getClientId());
}