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

The following examples show how to use com.google.common.net.HostAndPort#getHost() . 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: 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 2
Source File: LegacyApacheThriftTesterUtil.java    From drift with Apache License 2.0 6 votes vote down vote up
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 3
Source File: ProgressMonitor.java    From secor with Apache License 2.0 6 votes vote down vote up
public ProgressMonitor(SecorConfig config)
        throws Exception
{
    mConfig = config;
    mZookeeperConnector = new ZookeeperConnector(mConfig);
    try {
        Class timestampClass = Class.forName(mConfig.getKafkaClientClass());
        this.mKafkaClient = (KafkaClient) timestampClass.newInstance();
        this.mKafkaClient.init(config);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    mMessageParser = (MessageParser) ReflectionUtil.createMessageParser(
            mConfig.getMessageParserClass(), mConfig);

    mPrefix = mConfig.getMonitoringPrefix();
    if (Strings.isNullOrEmpty(mPrefix)) {
        mPrefix = "secor";
    }

    if (mConfig.getStatsDHostPort() != null && !mConfig.getStatsDHostPort().isEmpty()) {
        HostAndPort hostPort = HostAndPort.fromString(mConfig.getStatsDHostPort());
        mStatsDClient = new NonBlockingStatsDClient(null, hostPort.getHost(), hostPort.getPort(),
                mConfig.getStatsDDogstatsdConstantTags());
    }
}
 
Example 4
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 5
Source File: HttpUtil.java    From CapturePacket with MIT License 6 votes vote down vote up
/**
 * 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 6
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 7
Source File: ResolvedHostnameCacheFilter.java    From CapturePacket with MIT License 5 votes vote down vote up
@Override
public void proxyToServerResolutionSucceeded(String serverHostAndPort, InetSocketAddress resolvedRemoteAddress) {
    // the address *should* always be resolved at this point
    InetAddress resolvedAddress = resolvedRemoteAddress.getAddress();

    if (resolvedAddress != null) {
        // place the resolved host into the hostname cache, so subsequent requests will be able to identify the IP address
        HostAndPort parsedHostAndPort = HostAndPort.fromString(serverHostAndPort);
        String host = parsedHostAndPort.getHost();

        if (host != null && !host.isEmpty()) {
            resolvedAddresses.put(host, resolvedAddress.getHostAddress());
        }
    }
}
 
Example 8
Source File: HostProxy.java    From styx with Apache License 2.0 5 votes vote down vote up
@NotNull
public static HostProxy createHostProxyHandler(
        NettyExecutor executor,
        MetricRegistry metricRegistry,
        HostAndPort hostAndPort,
        ConnectionPoolSettings poolSettings,
        TlsSettings tlsSettings,
        int responseTimeoutMillis,
        int maxHeaderSize,
        String metricPrefix,
        String objectName) {

    String host = hostAndPort.getHost();
    int port = hostAndPort.getPort();

    Origin origin = newOriginBuilder(host, port)
            .applicationId(metricPrefix)
            .id(objectName)
            .build();

    OriginMetrics originMetrics = OriginMetrics.create(id(metricPrefix), objectName, metricRegistry);

    ConnectionPool.Factory connectionPoolFactory = new SimpleConnectionPoolFactory.Builder()
            .connectionFactory(
                    connectionFactory(
                            executor,
                            tlsSettings,
                            responseTimeoutMillis,
                            maxHeaderSize,
                            theOrigin -> originMetrics,
                            poolSettings.connectionExpirationSeconds()))
            .connectionPoolSettings(poolSettings)
            .metricRegistry(metricRegistry)
            .build();

    return new HostProxy(host, port, StyxHostHttpClient.create(connectionPoolFactory.create(origin)), originMetrics);
}
 
Example 9
Source File: Origin.java    From styx with Apache License 2.0 5 votes vote down vote up
Origin(String originId, String host) {
    HostAndPort hostAndPort = HostAndPort.fromString(host);

    this.originId = Id.id(originId);
    this.host = hostAndPort.getHost();
    this.port = hostAndPort.getPort();
    this.hostAsString = hostAndPort.toString();
    this.applicationId = GENERIC_APP;
    this.hashCode = Objects.hash(this.host, this.originId);
}
 
Example 10
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 11
Source File: MetricsConfiguration.java    From data-highway with Apache License 2.0 5 votes vote down vote up
@Autowired
public MetricsConfiguration(
    @Value("${metrics.graphiteEndpoint:disabled}") String graphiteEndpoint,
    @Value("${road.name}") String roadName) {
  if ("disabled".equalsIgnoreCase(graphiteEndpoint)) {
    log.info("Graphite metrics reporting is disabled");
    this.graphiteEndpoint = null;
  } else {
    log.info("Graphite reporting is configured for {}", graphiteEndpoint);
    HostAndPort hostAndPort = HostAndPort.fromString(graphiteEndpoint);
    this.graphiteEndpoint = new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPort());
  }
  this.roadName = roadName;
}
 
Example 12
Source File: UpstreamResolver.java    From Baragon with Apache License 2.0 5 votes vote down vote up
public Optional<String> resolveUpstreamDNS(String address) {
  String host;
  Optional<Integer> port = Optional.absent();

  if (address.contains(":")) {
    HostAndPort hostAndPort = HostAndPort.fromString(address);
    host = hostAndPort.getHost();
    port = Optional.of(hostAndPort.getPort());
  } else {
    host = address;
  }

  try {
    InetAddresses.forString(host);
    return Optional.of(address); // `address` is already an IP
  } catch (IllegalArgumentException e) {
    // `address` is not an IP, continue and try to resolve it
  }

  try {
    String cached = resolveCache.getIfPresent(host);
    String ip;
    if (cached != null) {
      ip = cached;
    } else {
      ip = InetAddress.getByName(host).getHostAddress();
      resolveCache.put(host, ip);
    }

    if (port.isPresent()) {
      return Optional.of(String.format("%s:%d", ip, port.get()));
    } else {
      return Optional.of(String.format("%s", ip));
    }
  } catch (UnknownHostException uhe) {
    // Don't let this exception block rendering of the template, the lb config check will still fail if the host is truly unknown
    return Optional.absent();
  }
}
 
Example 13
Source File: ResolvedHostnameCacheFilter.java    From AndroidHttpCapture with MIT License 5 votes vote down vote up
@Override
public void proxyToServerResolutionSucceeded(String serverHostAndPort, InetSocketAddress resolvedRemoteAddress) {
    // the address *should* always be resolved at this point
    InetAddress resolvedAddress = resolvedRemoteAddress.getAddress();

    if (resolvedAddress != null) {
        // place the resolved host into the hostname cache, so subsequent requests will be able to identify the IP address
        HostAndPort parsedHostAndPort = HostAndPort.fromString(serverHostAndPort);
        String host = parsedHostAndPort.getHost();

        if (host != null && !host.isEmpty()) {
            resolvedAddresses.put(host, resolvedAddress.getHostAddress());
        }
    }
}
 
Example 14
Source File: HttpsAwareFiltersAdapter.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the hostname (but not the port) the specified request for both HTTP and HTTPS requests.  The request may reflect
 * modifications from this or other filters. This filter instance must be currently handling the specified request;
 * otherwise the results are undefined.
 *
 * @param modifiedRequest a possibly-modified version of the request currently being processed
 * @return hostname of the specified request, without the port
 */
public String getHost(HttpRequest modifiedRequest) {
    String serverHost;
    if (isHttps()) {
        HostAndPort hostAndPort = HostAndPort.fromString(getHttpsRequestHostAndPort());
        serverHost = hostAndPort.getHost();
    } else {
        serverHost = getHostFromRequest(modifiedRequest);
    }
    return serverHost;
}
 
Example 15
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 16
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 17
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 18
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 19
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 20
Source File: Node.java    From xio with Apache License 2.0 2 votes vote down vote up
/**
 * The current host and port returned as a InetSocketAddress
 *
 * @param hostAndPort host and port
 * @return socket address
 */
public static InetSocketAddress toInetAddress(HostAndPort hostAndPort) {
  return (hostAndPort == null)
      ? null
      : new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPort());
}