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:com.villemos.ispace.webster.WebsterProducer.java

public void process(Exchange exchange) throws Exception {

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {/* www .j a v  a 2 s.  com*/
        client = new DefaultHttpClient();
    }

    String proxyHost = getWebsterEndpoint().getProxyHost();
    Integer proxyPort = getWebsterEndpoint().getProxyPort();

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (getWebsterEndpoint().getAuthenticationUser() != null
            && getWebsterEndpoint().getAuthenticationPassword() != null) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort()),
                new UsernamePasswordCredentials(getWebsterEndpoint().getAuthenticationUser(),
                        getWebsterEndpoint().getAuthenticationPassword()));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    String uriStr = getWebsterEndpoint().getProtocol() + "://" + getWebsterEndpoint().getDomain() + "/"
            + getWebsterEndpoint().getPath();
    if (getWebsterEndpoint().getPort() != 80) {
        uriStr += ":" + getWebsterEndpoint().getPort() + "/" + getWebsterEndpoint().getPath();
    }

    /** Break the query into its elements and search for each. */
    for (String word : ((String) exchange.getIn().getHeader(SolrOptions.query)).split("\\s+")) {
        uriStr += "/" + word;
        URI uri = new URI(uriStr);

        if (getWebsterEndpoint().getPort() != 80) {
            target = new HttpHost(getWebsterEndpoint().getDomain(), getWebsterEndpoint().getPort(),
                    getWebsterEndpoint().getProtocol());
        } else {
            target = new HttpHost(getWebsterEndpoint().getDomain());
        }
        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpUriRequest method = new HttpGet(uri);
        HttpResponse response = client.execute(target, method, localContext);

        if (response.getStatusLine().getStatusCode() == 200) {
            /** Extract result. */
            String page = HttpClientConfigurer.readFully(response.getEntity().getContent());

            ResultSet set = new ResultSet();

            Matcher matcher = pattern.matcher(page);
            if (matcher.find()) {
                String result = matcher.group(1).replaceAll("\\<.*?\\>", "").replaceAll("\\s+", " ");

                /** Create ResultSet*/
                InformationObject io = new InformationObject();
                io.hasUri = uriStr;
                io.fromSource = "Webster";
                io.hasTitle = "Webster definition of '" + word + "'.";
                io.ofEntityType = "Definition";
                io.ofMimeType = "text/html";
                io.withRawText = result;
                io.score = 20;
                set.informationobjects.add(io);
            }

            matcher = spellPattern.matcher(page);
            if (matcher.find()) {
                String result = matcher.group(1);
                String[] elements = result.split("<li><a href=.*?>");

                for (String element : elements) {
                    if (element.trim().equals("") == false) {
                        set.suggestions
                                .add(new Suggestion(word, element.replaceAll("<.*?>", "").trim(), "Webster"));
                    }
                }
            }

            if (exchange.getIn().getHeader(SolrOptions.stream) != null) {

                for (InformationObject io : set.informationobjects) {
                    Exchange newExchange = new DefaultExchange(endpoint.getCamelContext());
                    newExchange.getIn().setBody(io);
                    endpoint.getCamelContext().createProducerTemplate()
                            .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange);
                }

                for (Suggestion suggestion : set.suggestions) {
                    Exchange newExchange = new DefaultExchange(endpoint.getCamelContext());
                    newExchange.getIn().setBody(suggestion);
                    endpoint.getCamelContext().createProducerTemplate()
                            .send((String) exchange.getIn().getHeader(SolrOptions.stream), newExchange);
                }
            } else {
                exchange.getOut().setBody(set);
            }
        } else {
            HttpEntity entity = response.getEntity();
            InputStream instream = entity.getContent();
            String page = HttpClientConfigurer.readFully(response.getEntity().getContent());

            System.out.println(page);
        }
    }
}

From source file:com.openshift.internal.restclient.authorization.AuthorizationClient.java

private IAuthorizationContext getContextUsingCredentials(final String baseURL,
        CredentialsProvider credentialsProvider) {

    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;//  w  w w .  jav  a  2 s  . co m
    try {
        OpenShiftAuthorizationRedirectStrategy redirectStrategy = new OpenShiftAuthorizationRedirectStrategy(
                openshiftClient);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT)
                .setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT)
                .setStaleConnectionCheckEnabled(true).build();
        client = HttpClients.custom().setRedirectStrategy(redirectStrategy)
                .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider)
                .setSslcontext(sslContext).setDefaultRequestConfig(defaultRequestConfig).build();
        HttpGet request = new HttpGet(new URIBuilder(String.format("%s/oauth/authorize", baseURL))
                .addParameter("response_type", "token")
                .addParameter("client_id", "openshift-challenging-client").build());
        request.addHeader("X-CSRF-Token", "1");
        response = client.execute(request);
        return redirectStrategy.getAuthorizationContext();
    } catch (URISyntaxException e) {
        throw new OpenShiftException(e, String
                .format("Unvalid URI while trying to get an authorization context for server %s", baseURL));
    } catch (ClientProtocolException e) {
        throw new OpenShiftException(e, String.format(
                "Client protocol exception while trying to get authorization context for server %s", baseURL));
    } catch (IOException e) {
        throw new OpenShiftException(e,
                String.format("%s while trying to get an authorization context for server %s",
                        e.getClass().getName(), baseURL));
    } finally {
        close(response);
        close(client);
    }

}

From source file:es.eucm.eadventure.editor.plugin.vignette.ProxySetup.java

private static Proxy getProxy() {
    List<Proxy> l = null;
    try {//  w  ww .j  a v a 2  s. c  om
        ProxySelector def = ProxySelector.getDefault();

        l = def.select(new URI("http://foo/bar"));
        ProxySelector.setDefault(null);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (l != null) {
        for (Iterator<Proxy> iter = l.iterator(); iter.hasNext();) {
            java.net.Proxy proxy = iter.next();
            return proxy;
        }
    }
    return null;
}

From source file:com.villemos.ispace.httpcrawler.HttpAccessor.java

public int poll() throws Exception {

    /** Always ignore authentication protocol errors. */
    if (ignoreAuthenticationFailure) {
        SSLContext sslContext = SSLContext.getInstance("SSL");

        // set up a TrustManager that trusts everything
        sslContext.init(null, new TrustManager[] { new EasyX509TrustManager() }, new SecureRandom());

        SchemeRegistry schemeRegistry = new SchemeRegistry();

        SSLSocketFactory sf = new SSLSocketFactory(sslContext);
        Scheme httpsScheme = new Scheme("https", sf, 443);
        schemeRegistry.register(httpsScheme);

        SocketFactory sfa = new PlainSocketFactory();
        Scheme httpScheme = new Scheme("http", sfa, 80);
        schemeRegistry.register(httpScheme);

        HttpParams params = new BasicHttpParams();
        ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(cm, params);
    } else {/* www.j ava 2s.co  m*/
        client = new DefaultHttpClient();
    }

    String proxyHost = getHttpCrawlerEndpoint().getProxyHost();
    Integer proxyPort = getHttpCrawlerEndpoint().getProxyPort();

    if (proxyHost != null && proxyPort != null) {
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    } else {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }

    /** The target location may demand authentication. We setup preemptive authentication. */
    if (getHttpCrawlerEndpoint().getAuthenticationUser() != null
            && getHttpCrawlerEndpoint().getAuthenticationPassword() != null) {
        client.getCredentialsProvider().setCredentials(
                new AuthScope(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort()),
                new UsernamePasswordCredentials(getHttpCrawlerEndpoint().getAuthenticationUser(),
                        getHttpCrawlerEndpoint().getAuthenticationPassword()));
    }

    /** Set default cookie policy and store. Can be overridden for a specific method using for example;
     *    method.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); 
     */
    client.setCookieStore(cookieStore);
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    String uriStr = getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain();
    if (getHttpCrawlerEndpoint().getPort() != 80) {
        uriStr += ":" + getHttpCrawlerEndpoint().getPort() + "" + getHttpCrawlerEndpoint().getPath();
    } else {
        uriStr += getHttpCrawlerEndpoint().getPath();
    }
    URI uri = new URI(uriStr);

    if (getHttpCrawlerEndpoint().getPort() != 80) {
        target = new HttpHost(getHttpCrawlerEndpoint().getDomain(), getHttpCrawlerEndpoint().getPort(),
                getHttpCrawlerEndpoint().getProtocol());
    } else {
        target = new HttpHost(getHttpCrawlerEndpoint().getDomain());
    }
    localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    /** Default boundary is the domain. */
    getHttpCrawlerEndpoint().getBoundaries()
            .add(getHttpCrawlerEndpoint().getProtocol() + "://" + getHttpCrawlerEndpoint().getDomain());

    HttpUriRequest method = createInitialRequest(uri);
    HttpResponse response = client.execute(target, method, localContext);

    if (response.getStatusLine().getStatusCode() == 200) {
        processSite(uri, response);
    } else if (response.getStatusLine().getStatusCode() == 302) {
        HttpHost target = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpGet get = new HttpGet(target.toURI());
        // HttpGet get = new HttpGet("https://om.eo.esa.int/oem/kt/dashboard.php");

        /** Read the response fully, to clear it. */
        HttpEntity entity = response.getEntity();
        HttpClientConfigurer.readFully(entity.getContent());

        response = client.execute(target, get, localContext);
        processSite(uri, response);
        System.out.println("Final target: " + target);
    } else {
        HttpEntity entity = response.getEntity();
        InputStream instream = entity.getContent();
        System.out.println(HttpClientConfigurer.readFully(instream));
    }

    return 0;
}

From source file:com.liferay.sync.engine.session.Session.java

public static HttpRoutePlanner getHttpRoutePlanner() {
    if (_httpRoutePlanner != null) {
        return _httpRoutePlanner;
    }/*from   w w w  .j a v  a  2 s . co  m*/

    ProxySearch proxySearch = ProxySearch.getDefaultProxySearch();

    ProxySelector proxySelector = proxySearch.getProxySelector();

    if (proxySelector == null) {
        proxySelector = ProxySelector.getDefault();
    }

    _httpRoutePlanner = new SystemDefaultRoutePlanner(proxySelector);

    return _httpRoutePlanner;
}

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

private static List<String> connectAndReadFromURL(URL url, String fileName) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override/*from   w  w  w  .  jav  a2 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));
        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.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>();
        postParams.add(new BasicNameValuePair("serverjnlpfileloc", fileName));
        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        // int responseCode = response.getStatusLine().getStatusCode();
        // System.out.println("Response code for requesting datda file: " +
        // responseCode);
        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:com.marvelution.hudson.plugins.apiv2.client.connectors.HttpClient4Connector.java

/**
 * Method to create the {@link HttpClient}
 * //w  w  w .  j  a va  2  s. co  m
 * @return the {@link DefaultHttpClient}
 */
private DefaultHttpClient createClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    if (server.isSecured()) {
        log.debug("The Server is secured, create the BasicHttpContext to handle preemptive authentication.");
        client.getCredentialsProvider().setCredentials(getAuthScope(),
                new UsernamePasswordCredentials(server.getUsername(), server.getPassword()));
        localContext = new BasicHttpContext();
        // Generate BASIC scheme object and stick it to the local execution context
        BasicScheme basicAuth = new BasicScheme();
        localContext.setAttribute("preemptive-auth", basicAuth);
        // Add as the first request intercepter
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
    if (StringUtils.isNotBlank(System.getProperty("http.proxyHost"))
            || StringUtils.isNotBlank(System.getProperty("https.proxyHost"))) {
        log.debug("A System HTTP(S) proxy is set, set the ProxySelectorRoutePlanner for the client");
        System.setProperty("java.net.useSystemProxies", "true");
        // Set the ProxySelectorRoute Planner to automatically select the system proxy host if set.
        client.setRoutePlanner(new ProxySelectorRoutePlanner(client.getConnectionManager().getSchemeRegistry(),
                ProxySelector.getDefault()));
    }
    return client;
}

From source file:org.jclouds.http.apachehc.config.ApacheHCHttpCommandExecutorServiceModule.java

@Provides
@Singleton/*from  ww  w .j  a  va  2 s.  co  m*/
final HttpClient newDefaultHttpClient(ProxyConfig config, BasicHttpParams params, ClientConnectionManager cm) {
    DefaultHttpClient client = new DefaultHttpClient(cm, params);
    if (config.useSystem()) {
        ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
                client.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
        client.setRoutePlanner(routePlanner);
    }
    return client;
}

From source file:com.maxmind.ws.HTTPBase.java

boolean querySingleServer(String hostname) {
    String scheme, url2;/*from   w w w.j a  v  a2  s . c  o  m*/

    // check if we using the Secure HTTPS protocol
    scheme = isSecure ? "https://" : "http://";

    final ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>();
    for (final Map.Entry<String, String> entry : queries.entrySet()) {
        parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    parameters.add(new BasicNameValuePair("clientAPI", clientApi));

    // scheme already has the name of the protocol
    // append the domain name of the server, url of the web service
    // and the query string to the string named url2
    url2 = scheme + hostname + "/" + url;
    if (debug) {
        System.out.println("url2 = " + url2);
    }
    CloseableHttpClient client = null;
    try {
        RequestConfig timeoutConfig = RequestConfig.custom().setConnectionRequestTimeout((int) timeout * 1000)
                .setSocketTimeout((int) timeout * 1000).build();

        HttpRoutePlanner proxyPlaner = null;
        if (useSystemProxies) {
            proxyPlaner = new SystemDefaultRoutePlanner(ProxySelector.getDefault());
        }
        if (proxyHost != null && proxyPort > -1) {
            proxyPlaner = new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort));
        }
        client = HttpClients.custom().setDefaultRequestConfig(timeoutConfig).setRoutePlanner(proxyPlaner)
                .build();

        // connect the server
        final HttpPost method = new HttpPost(url2);
        method.setEntity(new UrlEncodedFormEntity(parameters));

        final HttpResponse response = client.execute(method);

        final String content = EntityUtils.toString(response.getEntity());
        if (response.getStatusLine().getStatusCode() == 200) {

            if (debug) {
                System.out.println("content = " + content);
            }

            // get the keys and values from
            // the string content and store them
            // the hash named outputstr

            // split content into pairs containing both
            // the key and the value
            final StringTokenizer st = new StringTokenizer(content, ";");

            // for each pair store key and value into the
            // hash named outputstr
            while (st.hasMoreTokens()) {
                final String keyvaluepair = st.nextToken();

                // split the pair into a key and a value
                final StringTokenizer st2 = new StringTokenizer(keyvaluepair, "=");
                String key;
                String value;
                key = st2.nextToken();
                value = st2.hasMoreTokens() ? st2.nextToken() : "";
                // store the key and the value into the
                // hash named outputstr
                outputstr.put(key, value);
                if (debug) {
                    System.out.println("key = " + key + ", value = " + value);
                }
            }
            if (!outputstr.containsKey(check_field)) {
                // if the output does not have the field it is checking for
                // then return false
                return false;
            }
            method.releaseConnection();
            return true;
        }
        method.releaseConnection();
        return false;
    } catch (final java.io.IOException e) {
        if (e instanceof InterruptedIOException) {
            System.out.println("web service timeout");
        }
        System.out.println("error = " + e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            if (client != null) {
                client.close();
            }
        } catch (IOException e) {
            //ignore
        }
    }
    return false;
}

From source file:org.trancecode.xproc.step.HttpRequestStepProcessor.java

private HttpClient prepareHttpClient(final XProcHttpRequest xProcRequest, final BasicHttpContext localContext) {
    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(schemeRegistry);
    final DefaultHttpClient httpClient = new DefaultHttpClient(connManager);
    final ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpClient.setRoutePlanner(routePlanner);

    if (xProcRequest.getCredentials() != null) {
        final List<String> authPref = Lists.newArrayList(AuthPolicy.BASIC, AuthPolicy.DIGEST);
        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authPref);
        httpClient.setCredentialsProvider(xProcRequest.getCredentials());
        final AuthCache authCache = new BasicAuthCache();
        final BasicScheme basicAuth = new BasicScheme();
        authCache.put(xProcRequest.getHttpHost(), basicAuth);
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }/*from  www  .j  a va 2s  . c o m*/
    return httpClient;
}