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:org.seedstack.hub.infra.vcs.ProxySelectorService.java

@Override
public void started() {
    defaultProxySelector = ProxySelector.getDefault();
    initializeProxiesFromConfiguration();
    ProxySelector.setDefault(this);
}

From source file:org.yccheok.jstock.network.ProxyDetector.java

/**
 * Find the proxy, use the property <code>java.net.useSystemProxies</code> to force
 * the usage of the system proxy. The value of this setting is restored afterwards.
 *
 * @return a list of found proxies/*from w  w  w . jav a 2 s  .  c  om*/
 */
private List<Proxy> initProxies() {
    final String valuePropertyBefore = System.getProperty(PROXY_PROPERTY);
    try {
        System.setProperty(PROXY_PROPERTY, "true");
        return ProxySelector.getDefault().select(new java.net.URI("http://www.google.com"));
    } catch (Exception e) {
        // As ProxyDetector is the initial code being executed in main,
        // we cannot afford any failure. This will make our entire JStock
        // application crash.
        // throw new RuntimeException(e);
        log.error(null, e);
    } finally {
        if (valuePropertyBefore != null) {
            System.setProperty(PROXY_PROPERTY, valuePropertyBefore);
        }
    }

    // Use emptyList instead of EMPTY_LIST, to avoid compiler warning.
    return java.util.Collections.emptyList();
}

From source file:com.kenai.redminenb.repository.RedmineManagerFactoryHelper.java

public static HttpClient getTransportConfig() {
    /**/*  w ww  .java2  s. c  o  m*/
    * Implement a minimal hostname verifier. This is needed to be able to use
    * hosts with certificates, that don't match the used hostname (VServer).
     *
     * This is implemented by first trying the "Browser compatible" hostname
     * verifier and if that fails, fall back to the default java hostname
     * verifier.
     *
     * If the default case the hostname verifier in java always rejects, but
     * for netbeans the "SSL Certificate Exception" module is available that
     * catches this and turns a failure into a request to the GUI user.
     */
    X509HostnameVerifier hostnameverified = new X509HostnameVerifier() {
        @Override
        public void verify(String string, SSLSocket ssls) throws IOException {
            if (SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER.verify(string, ssls.getSession())) {
                return;
            }
            if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls.getSession())) {
                throw new SSLException("Hostname did not verify");
            }
        }

        @Override
        public void verify(String string, X509Certificate xc) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public boolean verify(String string, SSLSession ssls) {
            if (SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER.verify(string, ssls)) {
                return true;
            }
            return HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls);
        }
    };

    try {
        SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                hostnameverified);

        HttpClient hc = HttpClientBuilder.create()
                .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .setSSLSocketFactory(scsf).build();

        return hc;
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.googlecode.fascinator.common.BasicHttpClient.java

/**
 * Gets an HTTP client. If authentication is required, the authenticate()
 * method must be called prior to this method.
 * //from   w  ww  . ja va2  s.  c  om
 * @param auth set true to use authentication, false to skip authentication
 * @return an HTTP client
 */
public HttpClient getHttpClient(boolean auth) {
    HttpClient client = new HttpClient();
    try {
        URL url = new URL(baseUrl);
        Proxy proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
        if (!proxy.type().equals(Proxy.Type.DIRECT)) {
            InetSocketAddress address = (InetSocketAddress) proxy.address();
            String proxyHost = address.getHostName();
            int proxyPort = address.getPort();
            client.getHostConfiguration().setProxy(proxyHost, proxyPort);
            log.trace("Using proxy {}:{}", proxyHost, proxyPort);
        }
    } catch (Exception e) {
        log.warn("Failed to get proxy settings: " + e.getMessage());
    }
    if (auth && credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
        log.trace("Credentials: username={}", credentials.getUserName());
    }
    return client;
}

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

public static HttpClient setupClient(boolean ignoreAuthenticationFailure, String domain, Integer port,
        String proxyHost, Integer proxyPort, String authUser, String authPassword, CookieStore cookieStore)
        throws NoSuchAlgorithmException, KeyManagementException {

    DefaultHttpClient client = null;/*w  w  w. j a  va 2  s.  co m*/

    /** 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 {
        client = new DefaultHttpClient();
    }

    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 (authUser != null && authPassword != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(domain, port),
                new UsernamePasswordCredentials(authUser, authPassword));
    }

    /** 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.RFC_2965);      
    client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

    return client;
}

From source file:com.geoxp.oss.client.OSSClient.java

/**
 * Get an HttpClient able to use a the Java configured proxyHost/Port if needed
 *
 * @returns HttpClient/*  w w  w.  ja  va2  s.c om*/
 */
private static HttpClient newHttpClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault());
    httpclient.setRoutePlanner(routePlanner);
    return httpclient;
}

From source file:org.codegist.crest.io.http.HttpClientFactoryTest.java

@Test
public void createWithOneShouldCreateDefaultHttpClient() throws Exception {

    DefaultHttpClient expected = mock(DefaultHttpClient.class);
    ProxySelectorRoutePlanner planner = mock(ProxySelectorRoutePlanner.class);
    ClientConnectionManager clientConnectionManager = mock(ClientConnectionManager.class);
    SchemeRegistry schemeRegistry = mock(SchemeRegistry.class);
    ProxySelector proxySelector = mock(ProxySelector.class);

    when(expected.getConnectionManager()).thenReturn(clientConnectionManager);
    when(clientConnectionManager.getSchemeRegistry()).thenReturn(schemeRegistry);

    mockStatic(ProxySelector.class);
    when(ProxySelector.getDefault()).thenReturn(proxySelector);

    whenNew(DefaultHttpClient.class).withNoArguments().thenReturn(expected);
    whenNew(ProxySelectorRoutePlanner.class).withArguments(schemeRegistry, proxySelector).thenReturn(planner);

    HttpClient actual = HttpClientFactory.create(crestConfig, getClass());
    assertSame(expected, actual);/*from w w  w .j a  v  a2 s  . co m*/

    verify(expected).setRoutePlanner(planner);
}

From source file:jp.ne.sakura.kkkon.java.net.socketimpl.testapp.android.SocketImplHookTestApp.java

/** Called when the activity is first created. */
@Override//from ww w. j a v  a  2 s. co  m
public void onCreate(Bundle savedInstanceState) {
    final Context context = this.getApplicationContext();

    {
        SocketImplHookFactory.initialize();
    }
    {
        ProxySelector proxySelector = ProxySelector.getDefault();
        Log.d(TAG, "proxySelector=" + proxySelector);
        if (null != proxySelector) {
            URI uri = null;
            try {
                uri = new URI("http://www.google.com/");
            } catch (URISyntaxException e) {
                Log.d(TAG, e.toString());
            }
            List<Proxy> proxies = proxySelector.select(uri);
            if (null != proxies) {
                for (final Proxy proxy : proxies) {
                    Log.d(TAG, " proxy=" + proxy);
                }
            }
        }
    }

    super.onCreate(savedInstanceState);

    /* Create a TextView and set its content.
     * the text is retrieved by calling a native
     * function.
     */
    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);

    TextView tv = new TextView(this);
    tv.setText("ExceptionHandler");
    layout.addView(tv);

    Button btn1 = new Button(this);
    btn1.setText("invoke Exception");
    btn1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            final int count = 2;
            int[] array = new int[count];
            int value = array[count]; // invoke IndexOutOfBOundsException
        }
    });
    layout.addView(btn1);

    {
        Button btn = new Button(this);
        btn.setText("upload http AsyncTask");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() {

                    @Override
                    protected Boolean doInBackground(String... paramss) {
                        Boolean result = true;
                        Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid());
                        try {
                            //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS)
                            Log.d(TAG, "fng=" + Build.FINGERPRINT);
                            final List<NameValuePair> list = new ArrayList<NameValuePair>(16);
                            list.add(new BasicNameValuePair("fng", Build.FINGERPRINT));

                            HttpPost httpPost = new HttpPost(paramss[0]);
                            //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) );
                            httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
                            DefaultHttpClient httpClient = new DefaultHttpClient();
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,
                                    new Integer(5 * 1000));
                            httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                                    new Integer(5 * 1000));
                            Log.d(TAG, "socket.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1));
                            Log.d(TAG, "connection.timeout=" + httpClient.getParams()
                                    .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1));
                            // <uses-permission android:name="android.permission.INTERNET"/>
                            // got android.os.NetworkOnMainThreadException, run at UI Main Thread
                            HttpResponse response = httpClient.execute(httpPost);
                            Log.d(TAG, "response=" + response.getStatusLine().getStatusCode());
                        } catch (Exception e) {
                            Log.d(TAG, "got Exception. msg=" + e.getMessage(), e);
                            result = false;
                        }
                        Log.d(TAG, "upload finish");
                        return result;
                    }

                };

                asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug");
                asyncTask.isCancelled();
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(0.0.0.0)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            destHost = InetAddress.getByName("0.0.0.0");
                            if (null != destHost) {
                                try {
                                    if (destHost.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " reachable");
                                    } else {
                                        Log.d(TAG, "destHost=" + destHost.toString() + " not reachable");
                                    }
                                } catch (IOException e) {

                                }
                            }
                        } catch (UnknownHostException e) {

                        }
                        Log.d(TAG, "destHost=" + destHost);
                    }
                });
                thread.start();
                try {
                    thread.join(1000);
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }
    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(www.google.com)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("www.google.com");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    {
        Button btn = new Button(this);
        btn.setText("pre DNS query(kkkon.sakura.ne.jp)");
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                isReachable = false;
                Thread thread = new Thread(new Runnable() {

                    public void run() {
                        try {
                            InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp");
                            if (null == dest) {
                                dest = destHost;
                            }
                            if (null != dest) {
                                try {
                                    if (dest.isReachable(5 * 1000)) {
                                        Log.d(TAG, "destHost=" + dest.toString() + " reachable");
                                        isReachable = true;
                                    } else {
                                        Log.d(TAG, "destHost=" + dest.toString() + " not reachable");
                                    }
                                    destHost = dest;
                                } catch (IOException e) {

                                }
                            } else {
                            }
                        } catch (UnknownHostException e) {
                            Log.d(TAG, "dns error" + e.toString());
                            destHost = null;
                        }
                        {
                            if (null != destHost) {
                                Log.d(TAG, "destHost=" + destHost);
                            }
                        }
                    }
                });
                thread.start();
                try {
                    thread.join();
                    {
                        final String addr = (null == destHost) ? ("") : (destHost.toString());
                        final String reachable = (isReachable) ? ("reachable") : ("not reachable");
                        Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable,
                                Toast.LENGTH_LONG);
                        toast.show();
                    }
                } catch (InterruptedException e) {

                }
            }
        });
        layout.addView(btn);
    }

    setContentView(layout);
}

From source file:org.hbird.business.celestrack.http.CelestrackReader.java

/**
 * Method to access the Celestrack website, download the TLE file ('elements'), extract the TLEs and
 * publish them to the system.//  w w  w  .ja v a  2s .co  m
 * 
 * @return 0 (always)
 * @throws Exception
 */
@Handler
public int read() throws Exception {

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

    long now = System.currentTimeMillis();

    for (String uri : part.getElements().split(":")) {
        HttpResponse response = client
                .execute(new HttpGet("http://www.celestrak.com/NORAD/elements/" + uri + ".txt"));

        if (response.getStatusLine().getStatusCode() == 200) {
            String text = readFully(response.getEntity().getContent());
            String elements[] = text.split("\n");

            for (int index = 0; index < elements.length; index += 3) {
                Satellite satellite = null;
                String name = elements[index].trim();
                Object object = catalogue.getSatelliteByName(name);
                if (object == null) {
                    /* Satellite unknown. Create placeholder object. */
                    // TODO - 18.05.2013, kimmell - create proper entity ID here
                    String entityID = name;
                    satellite = new Satellite(entityID, name);
                    publisher.publish(satellite);
                } else {
                    satellite = (Satellite) object;
                }

                TleOrbitalParameters parameters = new TleOrbitalParameters(satellite.getID() + "/TLE",
                        TleOrbitalParameters.class.getSimpleName());
                parameters.setSatelliteId(satellite.getID());
                parameters.setTleLine1(elements[index + 1].trim());
                parameters.setTleLine2(elements[index + 2].trim());
                publisher.publish(parameters);
            }
        }
    }

    return 0;
}

From source file:au.com.redboxresearchdata.harvester.httpclient.BasicHttpClient.java

/**
 * Gets an HTTP client. If authentication is required, the authenticate()
 * method must be called prior to this method.
 * /*from ww w  .  j  a  va  2s  .  c  om*/
 * @param auth set true to use authentication, false to skip authentication
 * @return an HTTP client
 */
public HttpClient getHttpClient(boolean auth) {
    HttpClient client = new HttpClient();
    try {
        URL url = new URL(baseUrl);
        //        log.info(baseUrl + "----------------------------1111------------");
        Proxy proxy = ProxySelector.getDefault().select(url.toURI()).get(0);
        if (!proxy.type().equals(Proxy.Type.DIRECT)) {
            InetSocketAddress address = (InetSocketAddress) proxy.address();
            String proxyHost = address.getHostName();
            int proxyPort = address.getPort();
            client.getHostConfiguration().setProxy(proxyHost, proxyPort);
            //          log.trace("Using proxy {}:{}", proxyHost, proxyPort);
        }
    } catch (Exception e) {
        //    log.warn("Failed to get proxy settings: " + e.getMessage());
    }
    if (auth && credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
        //  log.trace("Credentials: username={}", credentials.getUserName());
    }
    return client;
}