Example usage for java.net ProxySelector getDefault

List of usage examples for java.net ProxySelector getDefault

Introduction

In this page you can find the example usage for java.net ProxySelector getDefault.

Prototype

public static ProxySelector getDefault() 

Source Link

Document

Gets the system-wide proxy selector.

Usage

From source file:io.fabric8.git.internal.GitDataStoreImpl.java

private void activateInternal() throws Exception {

    LOGGER.info("Starting up GitDataStore " + this);

    // Call the bootstrap {@link DataStoreTemplate}
    DataStoreTemplate template = runtimeProperties.get().removeRuntimeAttribute(DataStoreTemplate.class);
    if (template != null) {

        // Do the initial commit and set the root tag
        Ref rootTag = getGit().getRepository().getRef(GitHelpers.ROOT_TAG);
        if (rootTag == null) {
            getGit().commit().setMessage("First Commit").setCommitter("fabric", "user@fabric").call();
            getGit().tag().setName(GitHelpers.ROOT_TAG).setMessage("Tag the root commit").call();
        }/*from  w  w w .  j a v  a  2  s .  c  om*/

        LOGGER.debug("Running datastore bootstrap template: " + template);
        template.doWith(this, dataStore.get());
    }

    // Setup proxy service
    GitProxyService proxyService = gitProxyService.get();
    defaultProxySelector = ProxySelector.getDefault();

    // authenticator disabled, until properly tested it does not affect others, as Authenticator is static in the JVM
    // Authenticator.setDefault(new FabricGitLocalHostAuthenticator(proxyService));
    ProxySelector fabricProxySelector = new FabricGitLocalHostProxySelector(defaultProxySelector, proxyService);
    ProxySelector.setDefault(fabricProxySelector);
    LOGGER.debug("Setting up FabricProxySelector: {}", fabricProxySelector);

    if (configuredUrl != null) {
        gitListener.runRemoteUrlChanged(configuredUrl);
        remoteUrl = configuredUrl;
    } else {
        gitService.get().addGitListener(gitListener);
        remoteUrl = gitService.get().getRemoteUrl();
        if (remoteUrl != null) {
            gitListener.runRemoteUrlChanged(remoteUrl);
        }
    }

    // Get initial versions
    getInitialVersions();

    LOGGER.info(
            "Using ZooKeeper SharedCount to react when master git repo is changed, so we can do a git pull to the local git repo.");
    counter = new SharedCount(curator.get(), ZkPath.GIT_TRIGGER.getPath(), 0);
    counter.addListener(new SharedCountListener() {
        @Override
        public void countHasChanged(final SharedCountReader sharedCountReader, final int value)
                throws Exception {
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    LOGGER.info("Watch counter updated to " + value + ", doing a pull");
                    doPullInternal();
                }
            });
        }

        @Override
        public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) {
            switch (connectionState) {
            case CONNECTED:
            case RECONNECTED:
                LOGGER.info("Shared Counter (Re)connected, doing a pull");
                doPullInternal();
            }
        }
    });
    counter.start();

    //It is not safe to assume that we will get notified by the ShareCounter, if the component is not activated
    // when the SharedCounter gets updated.
    //Also we cannot rely on the remote url change event, as it will only trigger when there is an actual change.
    //So we should be awesome and always attempt a pull when we are activating if we don't want to loose stuff.
    doPullInternal();
}

From source file:org.apache.abdera2.common.protocol.BasicClient.java

/**
 * Configure the client to use the proxy configured for the JVM
 * @return/*from   www. j  a v  a 2s. c o m*/
 */
public <T extends Client> T setStandardProxy() {
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    getDefaultHttpClient().setRoutePlanner(routePlanner);
    return (T) this;
}

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

/**
 * Get or create the http client to be used to fetch all the map data.
 *///w ww.j av  a2  s  . c om
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.android.tools.idea.sdk.remote.internal.UrlOpener.java

@NonNull
private static Pair<InputStream, HttpResponse> openWithHttpClient(@NonNull String url,
        @NonNull ITaskMonitor monitor, Header[] inHeaders) throws IOException, CanceledByUserException {
    UserCredentials result = null;/*from   w w  w .jav a2  s. c om*/
    String realm = null;

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, sConnectionTimeoutMs);
    HttpConnectionParams.setSoTimeout(params, sSocketTimeoutMs);

    // use the simple one
    final DefaultHttpClient httpClient = new DefaultHttpClient(params);

    // create local execution context
    HttpContext localContext = new BasicHttpContext();
    final HttpGet httpGet = new HttpGet(url);
    if (inHeaders != null) {
        for (Header header : inHeaders) {
            httpGet.addHeader(header);
        }
    }

    // retrieve local java configured network in case there is the need to
    // authenticate a proxy
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    // Set preference order for authentication options.
    // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in
    // servers that support both, as it is more secure. However, we don't seem to handle it
    // very well, so we leave it off the list.
    // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for
    // more info.
    List<String> authpref = new ArrayList<String>();
    authpref.add(AuthPolicy.BASIC);
    authpref.add(AuthPolicy.DIGEST);
    authpref.add(AuthPolicy.NTLM);
    httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
    httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref);

    if (DEBUG) {
        try {
            URI uri = new URI(url);
            ProxySelector sel = routePlanner.getProxySelector();
            if (sel != null && uri.getScheme().startsWith("httP")) { //$NON-NLS-1$
                List<Proxy> list = sel.select(uri);
                System.out.printf("SdkLib.UrlOpener:\n  Connect to: %s\n  Proxy List: %s\n", //$NON-NLS-1$
                        url, list == null ? "(null)" : Arrays.toString(list.toArray()));//$NON-NLS-1$
            }
        } catch (Exception e) {
            System.out.printf("SdkLib.UrlOpener: Failed to get proxy info for %s: %s\n", //$NON-NLS-1$
                    url, e.toString());
        }
    }

    boolean trying = true;
    // loop while the response is being fetched
    while (trying) {
        // connect and get status code
        HttpResponse response = httpClient.execute(httpGet, localContext);
        int statusCode = response.getStatusLine().getStatusCode();

        if (DEBUG) {
            System.out.printf("  Status: %d\n", statusCode); //$NON-NLS-1$
        }

        // check whether any authentication is required
        AuthState authenticationState = null;
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }
        if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // in case the status is OK and there is a realm and result,
            // cache it
            if (realm != null && result != null) {
                sRealmCache.put(realm, result);
            }
        }

        // there is the need for authentication
        if (authenticationState != null) {

            // get scope and realm
            AuthScope authScope = authenticationState.getAuthScope();

            // If the current realm is different from the last one it means
            // a pass was performed successfully to the last URL, therefore
            // cache the last realm
            if (realm != null && !realm.equals(authScope.getRealm())) {
                sRealmCache.put(realm, result);
            }

            realm = authScope.getRealm();

            // in case there is cache for this Realm, use it to authenticate
            if (sRealmCache.containsKey(realm)) {
                result = sRealmCache.get(realm);
            } else {
                // since there is no cache, request for login and password
                result = monitor.displayLoginCredentialsPrompt("Site Authentication",
                        "Please login to the following domain: " + realm
                                + "\n\nServer requiring authentication:\n" + authScope.getHost());
                if (result == null) {
                    throw new CanceledByUserException("User canceled login dialog.");
                }
            }

            // retrieve authentication data
            String user = result.getUserName();
            String password = result.getPassword();
            String workstation = result.getWorkstation();
            String domain = result.getDomain();

            // proceed in case there is indeed a user
            if (user != null && user.length() > 0) {
                Credentials credentials = new NTCredentials(user, password, workstation, domain);
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            if (trying) {
                // in case another pass to the Http Client will be performed, close the entity.
                entity.getContent().close();
            } else {
                // since no pass to the Http Client is needed, retrieve the
                // entity's content.

                // Note: don't use something like a BufferedHttpEntity since it would consume
                // all content and store it in memory, resulting in an OutOfMemory exception
                // on a large download.
                InputStream is = new FilterInputStream(entity.getContent()) {
                    @Override
                    public void close() throws IOException {
                        // Since Http Client is no longer needed, close it.

                        // Bug #21167: we need to tell http client to shutdown
                        // first, otherwise the super.close() would continue
                        // downloading and not return till complete.

                        httpClient.getConnectionManager().shutdown();
                        super.close();
                    }
                };

                HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
                outResponse.setHeaders(response.getAllHeaders());
                outResponse.setLocale(response.getLocale());

                return Pair.of(is, outResponse);
            }
        } else if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
            // It's ok to not have an entity (e.g. nothing to download) for a 304
            HttpResponse outResponse = new BasicHttpResponse(response.getStatusLine());
            outResponse.setHeaders(response.getAllHeaders());
            outResponse.setLocale(response.getLocale());

            return Pair.of(null, outResponse);
        }
    }

    // We get here if we did not succeed. Callers do not expect a null result.
    httpClient.getConnectionManager().shutdown();
    throw new FileNotFoundException(url);
}

From source file:gov.nih.nci.nbia.StandaloneDMV3.java

private List<String> connectAndReadFromURL(URL url, List<String> seriesList, String userId, String passWd) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override// ww  w.j  av a 2  s. c  o m
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        // SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        // sslContext.init(null, new TrustManager[] { new
        // EasyX509TrustManager(null)}, null);

        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        // HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        // HttpConnectionParams.setSoTimeout(httpParams, new
        // Integer(12000));
        HttpConnectionParams.setConnectionTimeout(httpParams, 500000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(120000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        // httpClient.getParams().setParameter("http.socket.timeout", new
        // Integer(12000));
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(120000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();

        if (userId != null && passWd != null) {
            postParams.add(new BasicNameValuePair("userId", userId));
            httpPostMethod.addHeader("password", passWd);
        }
        postParams.add(new BasicNameValuePair("numberOfSeries", Integer.toString(seriesList.size())));
        int i = 0;
        for (String s : seriesList) {
            postParams.add(new BasicNameValuePair("series" + Integer.toString(++i), s));
        }

        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();

        if (responseCode != HttpURLConnection.HTTP_OK) {
            returnStatus = responseCode;
            return null;
        } else {
            InputStream inputStream = response.getEntity().getContent();
            data = IOUtils.readLines(inputStream);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }

    return data;
}

From source file:org.apache.taverna.activities.rest.HTTPRequestHandler.java

/**
 * TODO - REDIRECTION output:: if there was no redirection, should just show
 * the actual initial URL?//  w ww  .ja  va2  s  .com
 *
 * @param httpRequest
 * @param acceptHeaderValue
 */
private static HTTPRequestResponse performHTTPRequest(ClientConnectionManager connectionManager,
        HttpRequestBase httpRequest, RESTActivityConfigurationBean configBean,
        Map<String, String> urlParameters, CredentialsProvider credentialsProvider) {
    // headers are set identically for all HTTP methods, therefore can do
    // centrally - here

    // If the user wants to set MIME type for the 'Accepts' header
    String acceptsHeaderValue = configBean.getAcceptsHeaderValue();
    if ((acceptsHeaderValue != null) && !acceptsHeaderValue.isEmpty()) {
        httpRequest.setHeader(ACCEPT_HEADER_NAME, URISignatureHandler.generateCompleteURI(acceptsHeaderValue,
                urlParameters, configBean.getEscapeParameters()));
    }

    // See if user wanted to set any other HTTP headers
    ArrayList<ArrayList<String>> otherHTTPHeaders = configBean.getOtherHTTPHeaders();
    if (!otherHTTPHeaders.isEmpty())
        for (ArrayList<String> httpHeaderNameValuePair : otherHTTPHeaders)
            if (httpHeaderNameValuePair.get(0) != null && !httpHeaderNameValuePair.get(0).isEmpty()) {
                String headerParameterizedValue = httpHeaderNameValuePair.get(1);
                String headerValue = URISignatureHandler.generateCompleteURI(headerParameterizedValue,
                        urlParameters, configBean.getEscapeParameters());
                httpRequest.setHeader(httpHeaderNameValuePair.get(0), headerValue);
            }

    try {
        HTTPRequestResponse requestResponse = new HTTPRequestResponse();
        DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, null);
        ((DefaultHttpClient) httpClient).setCredentialsProvider(credentialsProvider);
        HttpContext localContext = new BasicHttpContext();

        // Set the proxy settings, if any
        if (System.getProperty(PROXY_HOST) != null && !System.getProperty(PROXY_HOST).isEmpty()) {
            // Instruct HttpClient to use the standard
            // JRE proxy selector to obtain proxy information
            ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                    httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
            httpClient.setRoutePlanner(routePlanner);
            // Do we need to authenticate the user to the proxy?
            if (System.getProperty(PROXY_USERNAME) != null && !System.getProperty(PROXY_USERNAME).isEmpty())
                // Add the proxy username and password to the list of
                // credentials
                httpClient.getCredentialsProvider().setCredentials(
                        new AuthScope(System.getProperty(PROXY_HOST),
                                Integer.parseInt(System.getProperty(PROXY_PORT))),
                        new UsernamePasswordCredentials(System.getProperty(PROXY_USERNAME),
                                System.getProperty(PROXY_PASSWORD)));
        }

        // execute the request
        HttpResponse response = httpClient.execute(httpRequest, localContext);

        // record response code
        requestResponse.setStatusCode(response.getStatusLine().getStatusCode());
        requestResponse.setReasonPhrase(response.getStatusLine().getReasonPhrase());

        // record header values for Content-Type of the response
        requestResponse.setResponseContentTypes(response.getHeaders(CONTENT_TYPE_HEADER_NAME));

        // track where did the final redirect go to (if there was any)
        HttpHost targetHost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest targetRequest = (HttpUriRequest) localContext
                .getAttribute(ExecutionContext.HTTP_REQUEST);
        requestResponse.setRedirectionURL("" + targetHost + targetRequest.getURI());
        requestResponse.setRedirectionHTTPMethod(targetRequest.getMethod());
        requestResponse.setHeaders(response.getAllHeaders());

        /* read and store response body
         (check there is some content - negative length of content means
         unknown length;
         zero definitely means no content...)*/
        // TODO - make sure that this test is sufficient to determine if
        // there is no response entity
        if (response.getEntity() != null && response.getEntity().getContentLength() != 0)
            requestResponse.setResponseBody(readResponseBody(response.getEntity()));

        // release resources (e.g. connection pool, etc)
        httpClient.getConnectionManager().shutdown();
        return requestResponse;
    } catch (Exception ex) {
        return new HTTPRequestResponse(ex);
    }
}

From source file:org.mozilla.gecko.updater.UpdateService.java

private URLConnection openConnectionWithProxy(URI uri)
        throws java.net.MalformedURLException, java.io.IOException {
    Log.i(LOGTAG, "opening connection with URI: " + uri);

    ProxySelector ps = ProxySelector.getDefault();
    Proxy proxy = Proxy.NO_PROXY;
    if (ps != null) {
        List<Proxy> proxies = ps.select(uri);
        if (proxies != null && !proxies.isEmpty()) {
            proxy = proxies.get(0);//from   w  ww  .  ja va 2  s. c o  m
        }
    }

    return uri.toURL().openConnection(proxy);
}

From source file:com.naryx.tagfusion.cfm.http.cfHttpConnection.java

private void setDefaultProxy() {
    HttpHost currentProxy = (HttpHost) client.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY);

    if (currentProxy == null) {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }/*  www  . j av a2 s. com*/
}

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./*  ww  w . ja  v  a2 s. co  m*/
 *
 * @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.broad.igv.util.HttpUtils.java

/**
 * Get the system defined proxy defined for the URI, or null if
 * not available. May also return a {@code Proxy} object which
 * represents a direct connection//  w  w w.j  a v  a  2  s.  c o  m
 *
 * @param uri
 * @return
 */
private Proxy getSystemProxy(String uri) {
    try {
        log.debug("Getting system proxy for " + uri);
        ProxySelector selector = ProxySelector.getDefault();
        List<Proxy> proxyList = selector.select(new URI(uri));
        return proxyList.get(0);
    } catch (URISyntaxException e) {
        log.error(e.getMessage(), e);
        return null;
    } catch (NullPointerException e) {
        return null;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        return null;
    }

}