Example usage for java.net Proxy address

List of usage examples for java.net Proxy address

Introduction

In this page you can find the example usage for java.net Proxy address.

Prototype

public SocketAddress address() 

Source Link

Document

Returns the socket address of the proxy, or null if its a direct connection.

Usage

From source file:org.jenkinsci.plugins.newrelicnotifier.api.NewRelicClientImpl.java

private CloseableHttpClient getHttpClient(URI url) {
    HttpClientBuilder builder = HttpClientBuilder.create();

    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
        Proxy proxy = proxyConfig.createProxy(url.getHost());
        if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
            SocketAddress addr = proxy.address();
            if (addr != null && addr instanceof InetSocketAddress) {
                InetSocketAddress proxyAddr = (InetSocketAddress) addr;
                HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
                DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
                builder = builder.setRoutePlanner(routePlanner);

                String proxyUser = proxyConfig.getUserName();
                if (proxyUser != null) {
                    String proxyPass = proxyConfig.getPassword();
                    CredentialsProvider cred = new BasicCredentialsProvider();
                    cred.setCredentials(new AuthScope(proxyHost),
                            new UsernamePasswordCredentials(proxyUser, proxyPass));
                    builder = builder.setDefaultCredentialsProvider(cred)
                            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }//from ww  w  .j  a v a 2 s  . c o m
            }
        }
    }

    return builder.build();
}

From source file:org.talend.core.nexus.HttpClientTransport.java

private IProxySelectorProvider addProxy(final DefaultHttpClient httpClient, URI requestURI) {
    IProxySelectorProvider proxySelectorProvider = null;
    try {/*from   w w w . j  a v a 2  s  .  co m*/
        if (Boolean.valueOf(
                System.getProperty(PROP_PROXY_HTTP_CLIENT_USE_DEFAULT_SETTINGS, Boolean.FALSE.toString()))) {
            return proxySelectorProvider;
        }
        final List<Proxy> proxyList = TalendProxySelector.getInstance().getDefaultProxySelector()
                .select(requestURI);
        Proxy usedProxy = null;
        if (proxyList != null && !proxyList.isEmpty()) {
            usedProxy = proxyList.get(0);
        }

        if (usedProxy != null) {
            if (Type.DIRECT.equals(usedProxy.type())) {
                return proxySelectorProvider;
            }
            final Proxy finalProxy = usedProxy;
            InetSocketAddress address = (InetSocketAddress) finalProxy.address();
            String proxyServer = address.getHostName();
            int proxyPort = address.getPort();
            PasswordAuthentication proxyAuthentication = Authenticator.requestPasswordAuthentication(
                    proxyServer, address.getAddress(), proxyPort, "Http Proxy", "Http proxy authentication",
                    null);
            if (proxyAuthentication != null) {
                String proxyUser = proxyAuthentication.getUserName();
                if (StringUtils.isNotBlank(proxyUser)) {
                    String proxyPassword = "";
                    char[] passwordChars = proxyAuthentication.getPassword();
                    if (passwordChars != null) {
                        proxyPassword = new String(passwordChars);
                    }
                    httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyServer, proxyPort),
                            new UsernamePasswordCredentials(proxyUser, proxyPassword));
                }
            }
            HttpHost proxyHost = new HttpHost(proxyServer, proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
            proxySelectorProvider = createProxySelectorProvider();
        }
        return proxySelectorProvider;
    } finally {
        if (proxySelectorProvider != null) {
            TalendProxySelector.getInstance().addProxySelectorProvider(proxySelectorProvider);
        }
    }
}

From source file:org.whitesource.agent.client.WssServiceClientImpl.java

private void findDefaultProxy() {
    ProxySearch proxySearch = new ProxySearch();
    proxySearch.addStrategy(ProxySearch.Strategy.JAVA);
    proxySearch.addStrategy(ProxySearch.Strategy.ENV_VAR);
    proxySearch.addStrategy(ProxySearch.Strategy.OS_DEFAULT);
    proxySearch.addStrategy(ProxySearch.Strategy.BROWSER);
    ProxySelector proxySelector = proxySearch.getProxySelector();

    if (proxySelector != null) {
        ProxySelector.setDefault(proxySelector);
        try {//from  w w  w .  j  a v a  2 s .c o  m
            List<Proxy> proxyList = proxySelector.select(new URI(serviceUrl));
            if (proxyList != null && !proxyList.isEmpty()) {
                for (Proxy proxy : proxyList) {
                    InetSocketAddress address = (InetSocketAddress) proxy.address();
                    if (address != null) {
                        String host = address.getHostName();
                        int port = address.getPort();
                        String username = System.getProperty(HTTP_PROXY_USER);
                        String password = System.getProperty(HTTP_PROXY_PASSWORD);
                        setProxy(host, port, username, password);
                    }
                }
            }
        } catch (URISyntaxException e) {
            logger.error("Bad service url: " + serviceUrl, e);
        }
    }
}

From source file:eu.operando.proxy.OperandoProxyStatus.java

private void updateStatusView() {

    OperandoProxyStatus proxyStatus = OperandoProxyStatus.STOPPED;
    OperandoProxyLink proxyLink = OperandoProxyLink.INVALID;

    boolean isProxyRunning = MainUtil.isServiceRunning(mainContext.getContext(), ProxyService.class);
    boolean isProxyPaused = MainUtil.isProxyPaused(mainContext);

    if (isProxyRunning) {
        if (isProxyPaused) {
            proxyStatus = OperandoProxyStatus.PAUSED;
        } else {//from   ww w  .j a v  a2s.  c o  m
            proxyStatus = OperandoProxyStatus.ACTIVE;
        }
    }

    try {
        Proxy proxy = APL.getCurrentHttpProxyConfiguration();
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        if (proxyAddress != null) {
            //TODO: THIS SHOULD BE DYNAMIC
            String proxyHost = proxyAddress.getHostName();
            int proxyPort = proxyAddress.getPort();

            if (proxyHost.equals("127.0.0.1") && proxyPort == 8899) {
                proxyLink = OperandoProxyLink.VALID;
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    String info = "";
    try {
        InputStream is = getResources().openRawResource(R.raw.info_template);
        info = IOUtils.toString(is);
        IOUtils.closeQuietly(is);
    } catch (IOException e) {
        e.printStackTrace();
    }

    info = info.replace("@@status@@", proxyStatus.name());
    info = info.replace("@@link@@", proxyLink.name());
    webView.loadDataWithBaseURL("", info, "text/html", "UTF-8", "");
    webView.setBackgroundColor(Color.TRANSPARENT); //TRANSPARENT

}

From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java

private ProxyHost getProxyHost() {
    ProxyHost theProxyHost = null;//from w  ww. ja va2 s .  c  om
    ProxySelector ps = ProxySelector.getDefault();
    List<Proxy> p = null;
    // select the proxy for the URI of this repository
    try {
        if (ps != null) {
            // log.info( "Getting Proxy List." );
            p = ps.select(new java.net.URI(this.servletURL));
        }
    } catch (Exception e) {
        // log.warn( "Exception getting proxy: " + e.toString() );
    }
    if (p == null) {
        // log.warn( "No proxy information available." );
    } else {
        // log.info( "Received proxy list: " + p.toString() );
        Iterator<Proxy> proxies = p.iterator();
        // just take the first for now
        if (proxies != null && proxies.hasNext()) {
            Proxy theProxy = (Proxy) proxies.next();
            // log.info( "Proxy set to: " + theProxy.toString() );
            if (!Proxy.NO_PROXY.equals(theProxy)) {
                InetSocketAddress theSock = (InetSocketAddress) theProxy.address();
                theProxyHost = new ProxyHost(theSock.getHostName(), theSock.getPort());
            }
        } else {
            // log.warn( "Proxy list has zero members." );
        }
    }
    return theProxyHost;
}

From source file:org.mapfish.print.config.Config.java

/**
 * Get or create the http client to be used to fetch all the map data.
 *//* www  .ja  va 2s  . c  o m*/
public HttpClient getHttpClient(URI uri) {
    MultiThreadedHttpConnectionManager connectionManager = getConnectionManager();
    HttpClient httpClient = new HttpClient(connectionManager);

    // httpclient is a bit pesky about loading everything in memory...
    // disabling the warnings.
    Logger.getLogger(HttpMethodBase.class).setLevel(Level.ERROR);

    // configure proxies for URI
    ProxySelector selector = ProxySelector.getDefault();

    List<Proxy> proxyList = selector.select(uri);
    Proxy proxy = proxyList.get(0);

    if (!proxy.equals(Proxy.NO_PROXY)) {
        InetSocketAddress socketAddress = (InetSocketAddress) proxy.address();
        String hostName = socketAddress.getHostName();
        int port = socketAddress.getPort();

        httpClient.getHostConfiguration().setProxy(hostName, port);
    }

    for (SecurityStrategy sec : security)
        if (sec.matches(uri)) {
            sec.configure(uri, httpClient);
            break;
        }
    return httpClient;
}

From source file:com.joyent.manta.http.MantaConnectionFactory.java

/**
 * Finds the host of the proxy server that was configured as part of the
 * JVM settings./*from   w  w w.  j av  a  2s . c om*/
 *
 * @return proxy server as {@link HttpHost}, if no proxy then null
 */
protected HttpHost findProxyServer() {
    final ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> proxies = proxySelector.select(URI.create(config.getMantaURL()));

    if (!proxies.isEmpty()) {
        /* The Apache HTTP Client doesn't understand the concept of multiple
         * proxies, so we use only the first one returned. */
        final Proxy proxy = proxies.get(0);

        switch (proxy.type()) {
        case DIRECT:
            return null;
        case SOCKS:
            throw new ConfigurationException("SOCKS proxies are unsupported");
        default:
            // do nothing and fall through
        }

        if (proxy.address() instanceof InetSocketAddress) {
            InetSocketAddress sa = (InetSocketAddress) proxy.address();

            return new HttpHost(sa.getHostName(), sa.getPort());
        } else {
            String msg = String.format(
                    "Expecting proxy to be instance of InetSocketAddress. " + " Actually: %s", proxy.address());
            throw new ConfigurationException(msg);
        }
    } else {
        return null;
    }
}

From source file:org.jenkinsci.plugins.GitLabSecurityRealm.java

/**
 * Returns the proxy to be used when connecting to the given URI.
 *///  w w  w.  j a v  a 2 s  .c om
private HttpHost getProxy(HttpUriRequest method) throws URIException {
    Jenkins jenkins = Jenkins.getInstance();
    if (jenkins == null) {
        return null; // defensive check
    }
    ProxyConfiguration proxy = jenkins.proxy;
    if (proxy == null) {
        return null; // defensive check
    }

    Proxy p = proxy.createProxy(method.getURI().getHost());
    switch (p.type()) {
    case DIRECT:
        return null; // no proxy
    case HTTP:
        InetSocketAddress sa = (InetSocketAddress) p.address();
        return new HttpHost(sa.getHostName(), sa.getPort());
    case SOCKS:
    default:
        return null; // not supported yet
    }
}

From source file:com.okta.sdk.framework.ApiClient.java

/**
 * Constructor for the ApiClient./*from w  w  w .  j a  v a 2 s .  co m*/
 *
 * Bootstraps an HTTPClient to make various requests to the Okta API.
 *
 * @param config {@link ApiClientConfiguration}
 */
public ApiClient(ApiClientConfiguration config) {
    Proxy proxy = ProxySelector.getDefault().select(URI.create(config.getBaseUrl())).iterator().next();
    HttpRoutePlanner routePlanner;
    if (Proxy.Type.HTTP.equals(proxy.type())) {
        URI proxyUri = URI.create(proxy.type() + "://" + proxy.address());
        HttpHost proxyHost = new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme());
        routePlanner = new DefaultProxyRoutePlanner(proxyHost);
    } else {
        routePlanner = new DefaultRoutePlanner(null);
    }
    StandardHttpRequestRetryHandler requestRetryHandler = new StandardHttpRequestRetryHandler(RETRY_COUNT,
            true);
    HttpClient client = HttpClientBuilder.create().setRetryHandler(requestRetryHandler)
            .setUserAgent("OktaSDKJava_v" + Utils.getSdkVersion()).disableCookieManagement()
            .setRoutePlanner(routePlanner).build();

    this.httpClient = client;
    this.baseUrl = config.getBaseUrl();
    this.apiVersion = config.getApiVersion();
    this.configuration = config;
    this.token = config.getApiToken();

    initMarshaller();
}

From source file:org.jenkinsci.plugins.GithubSecurityRealm.java

/**
 * Returns the proxy to be used when connecting to the given URI.
 *///from w  w  w. j a va  2 s.  c  o  m
private HttpHost getProxy(HttpUriRequest method) throws URIException {
    ProxyConfiguration proxy = Jenkins.getInstance().proxy;
    if (proxy == null)
        return null; // defensive check

    Proxy p = proxy.createProxy(method.getURI().getHost());
    switch (p.type()) {
    case DIRECT:
        return null; // no proxy
    case HTTP:
        InetSocketAddress sa = (InetSocketAddress) p.address();
        return new HttpHost(sa.getHostName(), sa.getPort());
    case SOCKS:
    default:
        return null; // not supported yet
    }
}