Example usage for java.net InetSocketAddress createUnresolved

List of usage examples for java.net InetSocketAddress createUnresolved

Introduction

In this page you can find the example usage for java.net InetSocketAddress createUnresolved.

Prototype

public static InetSocketAddress createUnresolved(String host, int port) 

Source Link

Document

Creates an unresolved socket address from a hostname and a port number.

Usage

From source file:io.druid.client.cache.CacheDistributionTest.java

private static MemcachedNode dummyNode(String host, int port) {
    SocketAddress address = InetSocketAddress.createUnresolved(host, port);
    MemcachedNode node = EasyMock.createNiceMock(MemcachedNode.class);
    EasyMock.expect(node.getSocketAddress()).andReturn(address).anyTimes();
    EasyMock.replay(node);//  w w  w .j a  va 2 s  . c o  m
    return node;
}

From source file:org.apache.pulsar.client.impl.HttpLookupService.java

/**
 * Calls http-lookup api to find broker-service address which can serve a given topic.
 *
 * @param topicName topic-name// w w  w  .  j  a v  a2s  . c o m
 * @return broker-socket-address that serves given topic
 */
@SuppressWarnings("deprecation")
public CompletableFuture<Pair<InetSocketAddress, InetSocketAddress>> getBroker(TopicName topicName) {
    String basePath = topicName.isV2() ? BasePathV2 : BasePathV1;

    return httpClient.get(basePath + topicName.getLookupName(), LookupData.class).thenCompose(lookupData -> {
        // Convert LookupData into as SocketAddress, handling exceptions
        URI uri = null;
        try {
            if (useTls) {
                uri = new URI(lookupData.getBrokerUrlTls());
            } else {
                String serviceUrl = lookupData.getBrokerUrl();
                if (serviceUrl == null) {
                    serviceUrl = lookupData.getNativeUrl();
                }
                uri = new URI(serviceUrl);
            }

            InetSocketAddress brokerAddress = InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort());
            return CompletableFuture.completedFuture(Pair.of(brokerAddress, brokerAddress));
        } catch (Exception e) {
            // Failed to parse url
            log.warn("[{}] Lookup Failed due to invalid url {}, {}", topicName, uri, e.getMessage());
            return FutureUtil.failedFuture(e);
        }
    });
}

From source file:com.xebialabs.xlt.ci.server.XLTestServerImpl.java

private void setupHttpClient() {
    // TODO: make configurable ?
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setWriteTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);

    if (proxyUrl != null) {
        Proxy p = new Proxy(Proxy.Type.HTTP,
                InetSocketAddress.createUnresolved(proxyUrl.getHost(), proxyUrl.getPort()));
        client.setProxy(p);//from   w  w w.  j  ava2 s .  com
    }
}

From source file:org.apache.pulsar.client.impl.BinaryProtoLookupService.java

private CompletableFuture<Pair<InetSocketAddress, InetSocketAddress>> findBroker(
        InetSocketAddress socketAddress, boolean authoritative, TopicName topicName) {
    CompletableFuture<Pair<InetSocketAddress, InetSocketAddress>> addressFuture = new CompletableFuture<>();

    client.getCnxPool().getConnection(socketAddress).thenAccept(clientCnx -> {
        long requestId = client.newRequestId();
        ByteBuf request = Commands.newLookup(topicName.toString(), authoritative, requestId);
        clientCnx.newLookup(request, requestId).thenAccept(lookupDataResult -> {
            URI uri = null;/*from  w ww .  j  a va2 s.  c  o  m*/
            try {
                // (1) build response broker-address
                if (useTls) {
                    uri = new URI(lookupDataResult.brokerUrlTls);
                } else {
                    String serviceUrl = lookupDataResult.brokerUrl;
                    uri = new URI(serviceUrl);
                }

                InetSocketAddress responseBrokerAddress = InetSocketAddress.createUnresolved(uri.getHost(),
                        uri.getPort());

                // (2) redirect to given address if response is: redirect
                if (lookupDataResult.redirect) {
                    findBroker(responseBrokerAddress, lookupDataResult.authoritative, topicName)
                            .thenAccept(addressPair -> {
                                addressFuture.complete(addressPair);
                            }).exceptionally((lookupException) -> {
                                // lookup failed
                                log.warn("[{}] lookup failed : {}", topicName.toString(),
                                        lookupException.getMessage(), lookupException);
                                addressFuture.completeExceptionally(lookupException);
                                return null;
                            });
                } else {
                    // (3) received correct broker to connect
                    if (lookupDataResult.proxyThroughServiceUrl) {
                        // Connect through proxy
                        addressFuture.complete(Pair.of(responseBrokerAddress, socketAddress));
                    } else {
                        // Normal result with direct connection to broker
                        addressFuture.complete(Pair.of(responseBrokerAddress, responseBrokerAddress));
                    }
                }

            } catch (Exception parseUrlException) {
                // Failed to parse url
                log.warn("[{}] invalid url {} : {}", topicName.toString(), uri, parseUrlException.getMessage(),
                        parseUrlException);
                addressFuture.completeExceptionally(parseUrlException);
            }
        }).exceptionally((sendException) -> {
            // lookup failed
            log.warn("[{}] failed to send lookup request : {}", topicName.toString(),
                    sendException.getMessage(),
                    sendException instanceof ClosedChannelException ? null : sendException);
            addressFuture.completeExceptionally(sendException);
            return null;
        });
    }).exceptionally(connectionException -> {
        addressFuture.completeExceptionally(connectionException);
        return null;
    });
    return addressFuture;
}

From source file:com.googlecode.gmail4j.http.HttpProxyAwareSslSocketFactory.java

public void setProxy(final String proxyHost, final int proxyPort) {
    this.proxy = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(proxyHost, proxyPort));
}

From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java

/**
 * This method is used get the proxy instance by using user provided proxy details
 * //from   w w w .j  av  a 2  s. c  o m
 * @param httpProxyUrl proxy url configured in property file
 * @param httpProxyPort proxy port configured in property file
 * @param httpProxyUsername proxy username to authenticate
 * @param httpProxyPassword proxy password to authenticate
 * @return proxy instance
 */
private Proxy getProxy(final String httpProxyUrl, final String httpProxyPort, final String httpProxyUsername,
        final String httpProxyPassword) {
    if (!httpProxyUrl.isEmpty() && !httpProxyPort.isEmpty()) {
        final InetSocketAddress socket = InetSocketAddress.createUnresolved(httpProxyUrl,
                Integer.parseInt(httpProxyPort));
        if (!httpProxyUsername.isEmpty() && !httpProxyPassword.isEmpty()) {
            Authenticator authenticator = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    LOGGER.info("proxy authentication called");
                    return (new PasswordAuthentication(httpProxyUsername, httpProxyPassword.toCharArray()));
                }
            };
            Authenticator.setDefault(authenticator);
        }
        return new Proxy(Proxy.Type.HTTP, socket);
    }
    return null;
}

From source file:com.kumbaya.dht.Dht.java

private Dht start(String hostname, int port, int proxy) throws IOException, NumberFormatException {
    // The following lines allows the DHT to connect to local ip addresses
    // which is sometimes useful for debugging purposes. Production binaries
    // should probably not set these flags though. Leaving them as comments
    // for convenience.
    // NetworkSettings.LOCAL_IS_PRIVATE.setValue(false);
    // NetworkSettings.FILTER_CLASS_C.setValue(false);
    ContactUtils.setNetworkInstanceUtils(new SimpleNetworkInstanceUtils(false));

    NetworkSettings.LOCAL_IS_PRIVATE.setValue(false);
    NetworkSettings.FILTER_CLASS_C.setValue(false);
    ContactUtils.setNetworkInstanceUtils(new SimpleNetworkInstanceUtils(false));

    dht.getStorableModelManager().addStorableModel(DHTValueType.TEXT, model);

    if (dispatcher != null) {
        dht.setMessageDispatcher(dispatcher);
    }/*from www . jav  a2  s. co  m*/

    if (localDb != null) {
        dht.setDatabase(localDb);
    }

    dht.bind(new InetSocketAddress(hostname, port));
    dht.setExternalAddress(InetSocketAddress.createUnresolved(hostname, proxy));
    dht.start();

    return this;
}

From source file:org.apache.bookkeeper.stats.prometheus.PrometheusMetricsProvider.java

@Override
public void start(Configuration conf) {
    boolean httpEnabled = conf.getBoolean(PROMETHEUS_STATS_HTTP_ENABLE, DEFAULT_PROMETHEUS_STATS_HTTP_ENABLE);
    boolean bkHttpServerEnabled = conf.getBoolean("httpServerEnabled", false);
    // only start its own http server when prometheus http is enabled and bk http server is not enabled.
    if (httpEnabled && !bkHttpServerEnabled) {
        int httpPort = conf.getInt(PROMETHEUS_STATS_HTTP_PORT, DEFAULT_PROMETHEUS_STATS_HTTP_PORT);
        InetSocketAddress httpEndpoint = InetSocketAddress.createUnresolved("0.0.0.0", httpPort);
        this.server = new Server(httpEndpoint);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        server.setHandler(context);/*from   w  w w . j a v a 2s.  c o m*/

        context.addServlet(new ServletHolder(new PrometheusServlet(this)), "/metrics");

        try {
            server.start();
            log.info("Started Prometheus stats endpoint at {}", httpEndpoint);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // Include standard JVM stats
    registerMetrics(new StandardExports());
    registerMetrics(new MemoryPoolsExports());
    registerMetrics(new GarbageCollectorExports());
    registerMetrics(new ThreadExports());

    // Add direct memory allocated through unsafe
    registerMetrics(Gauge.build("jvm_memory_direct_bytes_used", "-").create().setChild(new Child() {
        @Override
        public double get() {
            return directMemoryUsage != null ? directMemoryUsage.longValue() : Double.NaN;
        }
    }));

    registerMetrics(Gauge.build("jvm_memory_direct_bytes_max", "-").create().setChild(new Child() {
        @Override
        public double get() {
            return PlatformDependent.maxDirectMemory();
        }
    }));

    executor = Executors.newSingleThreadScheduledExecutor(new DefaultThreadFactory("metrics"));

    int latencyRolloverSeconds = conf.getInt(PROMETHEUS_STATS_LATENCY_ROLLOVER_SECONDS,
            DEFAULT_PROMETHEUS_STATS_LATENCY_ROLLOVER_SECONDS);

    executor.scheduleAtFixedRate(() -> {
        rotateLatencyCollection();
    }, 1, latencyRolloverSeconds, TimeUnit.SECONDS);

}

From source file:com.kumbaya.dht.Dht.java

public DHTFuture<BootstrapResult> bootstrap(String hostname, int port) {
    DHTFuture<BootstrapResult> result = dht.bootstrap(InetSocketAddress.createUnresolved(hostname, port));
    return result;
}

From source file:org.apache.hadoop.net.NetUtils.java

/**
 * Create a socket address with the given host and port.  The hostname
 * might be replaced with another host that was set via
 * {@link #addStaticResolution(String, String)}.  The value of
 * hadoop.security.token.service.use_ip will determine whether the
 * standard java host resolver is used, or if the fully qualified resolver
 * is used./* w  w  w.jav a  2 s  .  com*/
 * @param host the hostname or IP use to instantiate the object
 * @param port the port number
 * @return InetSocketAddress
 */
public static InetSocketAddress makeSocketAddr(String host, int port) {
    String staticHost = getStaticResolution(host);
    String resolveHost = (staticHost != null) ? staticHost : host;

    InetSocketAddress addr;
    try {
        InetAddress iaddr = SecurityUtil.getByName(resolveHost);
        // if there is a static entry for the host, make the returned
        // address look like the original given host
        if (staticHost != null) {
            iaddr = InetAddress.getByAddress(host, iaddr.getAddress());
        }
        addr = new InetSocketAddress(iaddr, port);
    } catch (UnknownHostException e) {
        addr = InetSocketAddress.createUnresolved(host, port);
    }
    return addr;
}