Example usage for java.net Proxy NO_PROXY

List of usage examples for java.net Proxy NO_PROXY

Introduction

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

Prototype

Proxy NO_PROXY

To view the source code for java.net Proxy NO_PROXY.

Click Source Link

Document

A proxy setting that represents a DIRECT connection, basically telling the protocol handler not to use any proxying.

Usage

From source file:jetbrains.buildServer.buildTriggers.vcs.git.SNIHttpClientConnection.java

private HttpClient getClient() {
    if (client == null)
        client = new DefaultHttpClient();
    HttpParams params = client.getParams();
    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        isUsingProxy = true;//from w ww . j  a  v a 2  s.com
        InetSocketAddress adr = (InetSocketAddress) proxy.address();
        params.setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(adr.getHostName(), adr.getPort()));
    }
    if (timeout != null)
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout.intValue());
    if (readTimeout != null)
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout.intValue());
    if (followRedirects != null)
        params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, followRedirects.booleanValue());
    SSLSocketFactory sf = hostnameverifier != null ? new SNISSLSocketFactory(getSSLContext(), hostnameverifier)
            : new SNISSLSocketFactory(getSSLContext());
    Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
    client.getConnectionManager().getSchemeRegistry().register(https);
    return client;
}

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

/**
 * Is there a direct connection available? If I return <tt>true</tt> it is not
 * necessary to detect a proxy address./*w  w  w  .  j  a  v a2s .  c o m*/
 *
 * @return <tt>true</tt> if the is a direct connection to the internet
 */
public boolean directConnectionAvailable() {
    for (Proxy proxy : this.proxies) {
        if (Proxy.NO_PROXY.equals(proxy)) {
            return true;
        }
    }
    return false;
}

From source file:com.pras.conn._HttpConHandler.java

/**
 * @param urlStr HTTP URL//from   ww  w  . j a v  a 2  s  .  c o  m
 * @param type Type of Connection (POST, GET, PUT or DELETE)
 * @param httpHeaders HTTP headers
 * @param postData Data to be sent as a part of POST/PUT request
 * 
 * @return ATOM XML feed and Response/Error message
 */
public Response doConnect(String urlStr, int type, HashMap<String, String> httpHeaders, String postData) {

    String res = null;
    HttpURLConnection con = null;
    Response response = new Response();
    String TAG = "HttpConHandler";

    try {
        /*
         * IMPORTANT: 
         * User SHOULD provide URL Encoded Parms
         */
        Log.enableLog();
        Log.p(TAG, "URL=" + urlStr);

        // Somehow Eclipse is not detecting Proxy
        // HTTP Proxy
        //         System.getProperties().put("http.proxyHost", "168.219.61.250");
        //         System.getProperties().put("http.proxyPort", "8080");
        // HTTPS Proxy
        //         System.getProperties().put("https.proxyHost", "168.219.61.252");
        //         System.getProperties().put("https.proxyPort", "8080");
        // TODO: Remove proxy
        // DROCA Initialisation du Proxy
        Log.p(TAG, "doConnect init proxy");
        Proxy proxy = Proxy.NO_PROXY;
        proxy = getProxy();
        //         Log.p(TAG, "doConnect new URL BEFORE");
        URL url = new URL(urlStr);
        //         Log.p(TAG, "doConnect new URL AFTER");
        //         Log.p(TAG, "doConnect url.openConnection BEFORE");
        con = (HttpURLConnection) url.openConnection(proxy);
        Log.p(TAG, "doConnect url.openConnection AFTER");
        //
        //         URL url = new URL(urlStr);
        //         con = (HttpURLConnection) url.openConnection();

        //con.setInstanceFollowRedirects(false);

        OutputStream out = null;

        // Set headers
        /*
         * All subsequent request to Google Spreadsheet/Data API
         * should include following 2 Headers
         */
        //con.setRequestProperty("Authorization", "GoogleLogin auth="+ authToken);
        //con.setRequestProperty("GData-Version", "3.0");

        if (httpHeaders != null) {
            Log.p(TAG, "Number of HTTP Headers: " + httpHeaders.size());
            Iterator<String> keys = httpHeaders.keySet().iterator();
            while (keys.hasNext()) {
                String k = keys.next();
                con.setRequestProperty(k, httpHeaders.get(k));
            }
        }

        Log.p(TAG, "doConnect type:" + type);
        if (type == HTTP_POST) {
            //            Log.p(TAG, "doConnect HTTP_POST 1");
            con.setDoOutput(true);
            //            Log.p(TAG, "doConnect HTTP_POST 2");
            out = con.getOutputStream();
            //            Log.p(TAG, "doConnect HTTP_POST 3");
            out.write(postData.getBytes());
            //            Log.p(TAG, "doConnect HTTP_POST 4");
            out.flush();
            //            Log.p(TAG, "doConnect HTTP_POST 5");
        } else if (type == HTTP_GET) {
            //            Log.p(TAG, "doConnect HTTP_GET 1");
            con.setDoInput(true);
            //            Log.p(TAG, "doConnect HTTP_GET 2");
        } else if (type == HTTP_DELETE) {
            //            Log.p(TAG, "doConnect HTTP_DELETE 1");
            con.setRequestMethod("DELETE");
            //            Log.p(TAG, "doConnect HTTP_DELETE 2");
            con.connect();
            //            Log.p(TAG, "doConnect HTTP_DELETE 3");
        } else if (type == HTTP_PUT) {
            //            Log.p(TAG, "doConnect HTTP_PUT 1");
            con.setRequestMethod("PUT");
            //            Log.p(TAG, "doConnect HTTP_PUT 2");
            // Send Data
            con.setDoOutput(true);
            //            Log.p(TAG, "doConnect HTTP_PUT 3");
            out = con.getOutputStream();
            //            Log.p(TAG, "doConnect HTTP_PUT 4");
            out.write(postData.getBytes());
            //            Log.p(TAG, "doConnect HTTP_PUT 5");
            out.flush();
            //            Log.p(TAG, "doConnect HTTP_PUT 6");
        }

        // Read Response Code
        //         Log.p(TAG, "doConnect response.setResponseCode con.getResponseCode():"+con.getResponseCode()+" BEFORE");
        response.setResponseCode("" + con.getResponseCode());
        //         Log.p(TAG, "doConnect response.setResponseCode AFTER");
        //         Log.p(TAG, "doConnect response.setResponseCode con.setResponseMessage():"+con.getResponseMessage()+" BEFORE");
        response.setResponseMessage(con.getResponseMessage());
        //         Log.p(TAG, "doConnect response.setResponseCode AFTER");

        // Read InputStream
        //         Log.p(TAG, "doConnect response.setResponseCode con.getInputStream BEFORE");
        BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
        //         Log.p(TAG, "doConnect response.setResponseCode con.getInputStream AFTER");
        StringBuffer strBuf = new StringBuffer();
        String line = "";
        //         Log.p(TAG, "doConnect response.setResponseCode reader.readLine() BEFORE");
        try {
            while ((line = reader.readLine()) != null) {
                //               Log.p(TAG, "doConnect response.setResponseCode reader.readLine() line:"+line);
                strBuf.append(line);
            }
        }
        // DROCA : Pour contourner une erreur (pb genere quant connexion via proxy)
        // Message : [HttpConHandler] Error in reading response: java.net.SocketException: Socket is closed
        catch (Exception ex) {
            Log.p(TAG, "Error in reading response: " + ex.toString());
        }
        //         Log.p(TAG, "doConnect response.setResponseCode reader.readLine() AFTER");

        //         Log.p(TAG, "doConnect response.setResponseCode reader.close() BEFORE");
        reader.close();
        //         Log.p(TAG, "doConnect response.setResponseCode reader.close() AFTER");

        if (out != null)
            out.close();

        res = strBuf.toString();

        response.setOutput(res);

        Log.p(TAG, "Response from Google Server: \n" + res);

    } catch (Exception ex) {

        Log.p(TAG, "Error in connection: " + ex.toString());
        // Oops Exception
        response.setError(true);

        // Set Exception
        response.setException(ex);

        if (con == null)
            return response;

        InputStream error_in = con.getErrorStream();

        if (error_in == null)
            return response;

        // Read the error stream
        BufferedReader reader = new BufferedReader(new InputStreamReader(error_in));
        if (reader == null)
            return response;

        StringBuffer errStrBuf = new StringBuffer();
        String line = "";

        try {
            while ((line = reader.readLine()) != null)
                errStrBuf.append(line);

            // Set Error Stream Message
            response.setErrorStreamMsg(errStrBuf.toString());

            reader.close();

            // Display error on logging console
            response.printErrorLog();

        } catch (Exception e) {
            Log.p(TAG, "Error in reading Stream: " + e.getMessage());
        }
    }
    return response;
}

From source file:org.seedstack.hub.infra.vcs.ProxySelectorServiceTest.java

private void assertNoProxy(List<Proxy> select) {
    Assertions.assertThat(select).containsExactly(Proxy.NO_PROXY);
}

From source file:test.integ.be.fedict.trust.SSLTrustValidatorTest.java

@Test
public void testValidation() throws Exception {
    Proxy proxy = Proxy.NO_PROXY;
    // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
    // "proxy.yourict.net", 8080));
    NetworkConfig networkConfig = null; // new
    // NetworkConfig("proxy.yourict.net",
    // 8080);/*  w  ww . j av  a  2s.  co  m*/
    // URL url = new URL("https://eid.belgium.be/"); // OK
    // URL url = new URL("https://www.fortisbanking.be"); // OK
    // URL url = new URL("https://www.e-contract.be/"); // OK
    // URL url = new URL("https://idp.services.belgium.be"); // OK
    // URL url = new URL("https://idp.int.belgium.be"); // OK
    //URL url = new URL("https://test.eid.belgium.be/");
    URL url = new URL("https://www.cloudflare.com/");

    // URL url = new URL("https://www.facebook.com");
    // URL url = new URL("https://www.twitter.com");
    // URL url = new URL("https://www.mozilla.org");
    // URL url = new URL("https://www.verisign.com/");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(proxy);
    connection.connect();
    Certificate[] serverCertificates = connection.getServerCertificates();
    List<X509Certificate> certificateChain = new LinkedList<>();
    for (Certificate certificate : serverCertificates) {
        X509Certificate x509Cert = (X509Certificate) certificate;
        certificateChain.add(x509Cert);
        LOG.debug("certificate subject: " + x509Cert.getSubjectX500Principal());
        LOG.debug("certificate issuer: " + x509Cert.getIssuerX500Principal());
    }

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate rootCertificate = (X509Certificate) certificateFactory.generateCertificate(
            SSLTrustValidatorTest.class.getResourceAsStream("/ecc/AddTrustExternalCARoot.crt"));
    certificateChain.add(rootCertificate);

    MemoryCertificateRepository certificateRepository = new MemoryCertificateRepository();
    certificateRepository.addTrustPoint(certificateChain.get(certificateChain.size() - 1));

    //certificateRepository.addTrustPoint(rootCertificate);
    TrustValidator trustValidator = new TrustValidator(certificateRepository);
    trustValidator.setAlgorithmPolicy(new AlgorithmPolicy() {

        @Override
        public void checkSignatureAlgorithm(String signatureAlgorithm, Date validationDate)
                throws SignatureException {
            LOG.debug("signature algo: " + signatureAlgorithm);
            // allow all
        }
    });

    // next is kind of a default trust linked pattern.
    TrustValidatorDecorator trustValidatorDecorator = new TrustValidatorDecorator(networkConfig);
    trustValidatorDecorator.addDefaultTrustLinkerConfig(trustValidator);

    // operate
    trustValidator.isTrusted(certificateChain);
}

From source file:it.publisys.liferay.hook.shibboleth.ShibbolethPostLogoutAction.java

/**
 * Effettua una {@link HttpURLConnection} inviando anche i cookies
 *
 * @param url     url//from   w w w .  jav  a  2s .com
 * @param cookies cookies
 * @return response code
 */
private int _connect(String url, String cookies) {
    int responseCode = -1;
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws CertificateException {
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }

    HttpURLConnection connection = null;
    try {
        URL _url = new URL(url);
        connection = (HttpURLConnection) _url.openConnection(Proxy.NO_PROXY);
        connection.setRequestProperty("Cookie", cookies);
        connection.setReadTimeout(5000);
        connection.setRequestMethod("GET");

        responseCode = connection.getResponseCode();
        _log.info("Logout Shibb response code: " + responseCode);

        if (responseCode == 200 && _log.isDebugEnabled()) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder _buffer = new StringBuilder();
                String line = null;
                while ((line = br.readLine()) != null) {
                    _buffer.append(line);
                }
                _log.debug(_buffer.toString());
            } finally {
                if (br != null) {
                    br.close();
                }
            }

        }

    } catch (MalformedURLException mue) {
        mue.printStackTrace(System.err);
    } catch (IOException ioe) {
        ioe.printStackTrace(System.err);
    } finally {
        try {
            if (connection != null) {
                connection.disconnect();
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }
    return responseCode;
}

From source file:com.collabnet.ccf.pi.cee.pt.v50.CollabNetConnectionFactory.java

public TrackerWebServicesClient createConnection(String systemId, String systemKind, String repositoryId,
        String repositoryKind, String connectionInfo, String credentialInfo,
        ConnectionManager<TrackerWebServicesClient> connectionManager) throws ConnectionException {
    if (StringUtils.isEmpty(repositoryId)) {
        throw new IllegalArgumentException("Repository Id cannot be null");
    }/*from  w  w w.j  a  v  a 2 s.c o  m*/

    String username = null;
    String password = null;
    if (credentialInfo != null) {
        String[] splitCredentials = credentialInfo.split(PARAM_DELIMITER);
        if (splitCredentials != null) {
            if (splitCredentials.length == 1) {
                username = splitCredentials[0];
                password = "";
            } else if (splitCredentials.length == 2) {
                username = splitCredentials[0];
                password = splitCredentials[1];
            } else {
                String message = "Credentials info is not valid " + credentialInfo;
                log.error(message);
                throw new IllegalArgumentException(message);
            }
        }
    }
    String projectName = null;
    if (repositoryId != null) {
        String[] splitProjectName = repositoryId.split(":");
        if (splitProjectName != null) {
            if (splitProjectName.length >= 1) {
                projectName = splitProjectName[0];
            } else {
                throw new IllegalArgumentException("Repository id " + repositoryId + " is not valid."
                        + " Could not extract project name from repository id");
            }
        }
    }
    String url = connectionInfo.substring(0, connectionInfo.indexOf("://") + 3) + projectName + "."
            + connectionInfo.substring(connectionInfo.indexOf("://") + 3);
    TrackerWebServicesClient twsclient = null;
    try {
        Proxy proxy = null;
        if (proxyUsed) {
            if (StringUtils.isEmpty(this.proxyHost)) {
                throw new IllegalArgumentException("Proxy host is not valid." + this.proxyHost);
            } else if (this.proxyPort == -1) {
                throw new IllegalArgumentException("Proxy port is not valid " + this.proxyPort);
            }
            Proxy.Type type = null;
            try {
                type = Proxy.Type.valueOf(this.proxyType);
            } catch (Exception e) {
                throw new IllegalArgumentException("Proxy type is not valid " + this.proxyType
                        + ". Proxy type should either be HTTP or SOCKS");
            }
            InetSocketAddress socketAddress = new InetSocketAddress(this.proxyHost, this.proxyPort);

            proxy = new Proxy(type, socketAddress);
        } else {
            proxy = Proxy.NO_PROXY;
        }
        twsclient = TrackerClientManager.getInstance().createClient(url, username, password, null, null, proxy);
    } catch (MalformedURLException e) {
        String message = "Exception when trying to get the Web Services client";
        log.error(message, e);
        throw new ConnectionException(message, e);
    }
    return twsclient;
}

From source file:cc.arduino.net.CustomProxySelector.java

private Proxy makeProxyFrom(String proxyConfigs) {
    String proxyConfig = proxyConfigs.split(";")[0];
    if (proxyConfig.startsWith("DIRECT")) {
        return Proxy.NO_PROXY;
    }/*from   ww w.  java 2s. c om*/
    Proxy.Type type;
    if (proxyConfig.startsWith("PROXY")) {
        type = Proxy.Type.HTTP;
        proxyConfig = proxyConfig.replace("PROXY ", "");
    } else {
        type = Proxy.Type.SOCKS;
        proxyConfig = proxyConfig.replace("SOCKS ", "");
    }
    String[] hostPort = proxyConfig.split(":");
    return new Proxy(type, new InetSocketAddress(hostPort[0], Integer.valueOf(hostPort[1])));
}

From source file:org.eclipse.jgit.transport.http.apache.HttpClientConnection.java

private HttpClient getClient() {
    if (client == null) {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
            isUsingProxy = true;/*from w w  w.j a v  a 2s.  c  o  m*/
            InetSocketAddress adr = (InetSocketAddress) proxy.address();
            clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
        }
        if (timeout != null) {
            configBuilder.setConnectTimeout(timeout.intValue());
        }
        if (readTimeout != null) {
            configBuilder.setSocketTimeout(readTimeout.intValue());
        }
        if (followRedirects != null) {
            configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
        }
        if (hostnameverifier != null) {
            SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(),
                    hostnameverifier);
            clientBuilder.setSSLSocketFactory(sslConnectionFactory);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionFactory)
                    .register("http", PlainConnectionSocketFactory.INSTANCE).build();
            clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        }
        clientBuilder.setDefaultRequestConfig(configBuilder.build());
        client = clientBuilder.build();
    }

    return client;
}

From source file:hudson.ProxyConfiguration.java

public static Proxy createProxy(String host, String name, int port, String noProxyHost) {
    if (host != null && noProxyHost != null) {
        for (Pattern p : getNoProxyHostPatterns(noProxyHost)) {
            if (p.matcher(host).matches())
                return Proxy.NO_PROXY;
        }//from  w  w w  .j  av a 2  s .  c  o m
    }
    return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(name, port));
}