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:eu.esdihumboldt.util.http.ProxyUtil.java

/**
 * Tries to find the system's proxy configuration for a given URI
 * /*  www . ja  va2 s. co  m*/
 * @param uri the URI
 * @return the proxy configuration (host and port)
 */
public static Proxy findProxy(URI uri) {
    init();

    // BUGFIX: Don't use this property since it makes the connection hang!
    // Rather set the proxy through the system properties
    // "http.proxyHost" and "http.proxyPort".
    // System.setProperty("java.net.useSystemProxies", "true");

    List<Proxy> proxies = ProxySelector.getDefault().select(uri);
    if (proxies != null && proxies.size() > 0) {
        for (Proxy proxy : proxies) {
            if (proxy.type() == Proxy.Type.HTTP) {
                return proxy;
            }
        }
    }

    return Proxy.NO_PROXY;

    /*
     * The following code is obsolete System properties are handled
     * correctly by proxy selector The only thing that the code supports
     * additionally is setting using a proxy for the host that is the proxy
     * host
     */
    /*
     * String strProxyHost = System.getProperty("http.proxyHost"); String
     * strProxyPort = System.getProperty("http.proxyPort"); String
     * strNonProxyHosts = System.getProperty("http.nonProxyHosts"); String[]
     * nonProxyHosts; if (strNonProxyHosts != null) { nonProxyHosts =
     * strNonProxyHosts.split("\\|"); } else { nonProxyHosts = new
     * String[0]; }
     * 
     * if (strProxyHost != null && strProxyPort != null) { boolean noProxy =
     * false; for (int i = 0; i < nonProxyHosts.length; ++i) { if
     * (nonProxyHosts[i].equalsIgnoreCase(uri.getHost())) { noProxy = true;
     * break; } }
     * 
     * if (!noProxy) { int proxyPort = Integer.parseInt(strProxyPort);
     * return new InetSocketAddress(strProxyHost, proxyPort); } }
     * 
     * return null;
     */
}

From source file:mdretrieval.FileFetcher.java

public static InputStream fetchFileFromUrl(String urlString) {

    InputStream inputStream = null;

    Proxy proxy = ServerConstants.isProxyEnabled
            ? new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ServerConstants.hostname, ServerConstants.port))
            : Proxy.NO_PROXY;

    URL url;//  w w w  . j  av a 2 s  . c  o  m
    try {
        url = new URL(urlString);
        url.openConnection();

        if (proxy != Proxy.NO_PROXY && proxy.type() != Proxy.Type.DIRECT) {
            inputStream = url.openConnection(proxy).getInputStream();
        } else {
            inputStream = url.openConnection().getInputStream();
        }
    } catch (MalformedURLException e) {
        GUIrefs.displayAlert("Invalid URL " + urlString + "- \\n malformed expression");
        e.printStackTrace();
        inputStream = null;
    } catch (IOException ioe) {
        GUIrefs.displayAlert("Cannot read from " + StringUtilities.escapeQuotes(urlString) + "- IOException");
        ioe.printStackTrace();
        inputStream = null;
    }

    return inputStream;
}

From source file:jp.go.nict.langrid.management.logic.service.HttpClientUtil.java

/**
 * //  ww  w .j a  v  a 2  s .  c  om
 * 
 */
public static HttpClient createHttpClientWithHostConfig(URL url) {
    HttpClient client = new HttpClient();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
        if (port == -1) {
            port = 80;
        }
    }
    if ((url.getProtocol().equalsIgnoreCase("https")) && (sslSocketFactory != null)) {
        Protocol https = new Protocol("https",
                (ProtocolSocketFactory) new SSLSocketFactorySSLProtocolSocketFactory(sslSocketFactory), port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), https);
    } else {
        Protocol http = new Protocol("http", new SocketFactoryProtocolSocketFactory(SocketFactory.getDefault()),
                port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), http);
    }
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
        for (Proxy p : proxies) {
            if (p.equals(Proxy.NO_PROXY))
                continue;
            if (!p.type().equals(Proxy.Type.HTTP))
                continue;
            InetSocketAddress addr = (InetSocketAddress) p.address();
            client.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
            break;
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return client;
}

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

@Override
public List<Proxy> select(URI uri) {
    if (uri == null) {
        throw new IllegalArgumentException("URI can't be null.");
    }//from  w w w.  j  a  va  2s  .c  om
    String protocol = uri.getScheme();
    if (("http".equalsIgnoreCase(protocol) || "https".equalsIgnoreCase(protocol)) && isNotExcluded(uri)) {
        return Lists.newArrayList(proxy.orElse(Proxy.NO_PROXY));
    }
    if (defaultProxySelector != null) {
        return defaultProxySelector.select(uri);
    } else {
        ArrayList<Proxy> l = new ArrayList<>();
        l.add(Proxy.NO_PROXY);
        return l;
    }
}

From source file:org.mozilla.mozstumbler.service.core.http.HttpUtil.java

private URLConnection openConnectionWithProxy(URL url) throws IOException {
    Proxy proxy = Proxy.NO_PROXY;

    ProxySelector proxySelector = ProxySelector.getDefault();
    if (proxySelector != null) {
        URI uri;/*w ww .j  a  va 2 s .c  o m*/
        try {
            uri = url.toURI();
        } catch (URISyntaxException e) {
            IOException ioe = new IOException(url.toString());
            ioe.initCause(e);
            throw ioe;
        }

        List<Proxy> proxies = proxySelector.select(uri);
        if (proxies != null && !proxies.isEmpty()) {
            proxy = proxies.get(0);
        }
    }

    return url.openConnection(proxy);
}

From source file:org.ttrssreader.net.JavaJSONConnector.java

protected InputStream doRequest(Map<String, String> params) {
    try {//from w  w  w  .j  ava2 s.c o m
        if (sessionId != null)
            params.put(SID, sessionId);

        JSONObject json = new JSONObject(params);
        byte[] outputBytes = json.toString().getBytes("UTF-8");

        logRequest(json);

        URL url = Controller.getInstance().url();
        HttpURLConnection con = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);

        // Content
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");
        con.setRequestProperty("Content-Length", Integer.toString(outputBytes.length));

        // Timeouts
        long timeoutSocket = (Controller.getInstance().lazyServer()) ? 15 * Utils.MINUTE : 10 * Utils.SECOND;
        con.setReadTimeout((int) timeoutSocket);
        con.setConnectTimeout((int) (8 * Utils.SECOND));

        // HTTP-Basic Authentication
        if (base64NameAndPw != null)
            con.setRequestProperty("Authorization", "Basic " + base64NameAndPw);

        // Add POST data
        con.getOutputStream().write(outputBytes);

        // Try to check for HTTP Status codes
        int code = con.getResponseCode();
        if (code >= 400 && code < 600) {
            hasLastError = true;
            lastError = "Server returned status: " + code + " (Message: " + con.getResponseMessage() + ")";
            return null;
        }

        // Everything is fine!
        return con.getInputStream();

    } catch (SSLPeerUnverifiedException e) {
        // Probably related: http://stackoverflow.com/questions/6035171/no-peer-cert-not-sure-which-route-to-take
        // Not doing anything here since this error should happen only when no certificate is received from the
        // server.
        Log.w(TAG, "SSLPeerUnverifiedException in doRequest(): " + formatException(e));
    } catch (SSLException e) {
        if ("No peer certificate".equals(e.getMessage())) {
            // Handle this by ignoring it, this occurrs very often when the connection is instable.
            Log.w(TAG, "SSLException in doRequest(): " + formatException(e));
        } else {
            hasLastError = true;
            lastError = "SSLException in doRequest(): " + formatException(e);
        }
    } catch (InterruptedIOException e) {
        Log.w(TAG, "InterruptedIOException in doRequest(): " + formatException(e));
    } catch (SocketException e) {
        // http://stackoverflow.com/questions/693997/how-to-set-httpresponse-timeout-for-android-in-java/1565243
        // #1565243
        Log.w(TAG, "SocketException in doRequest(): " + formatException(e));
    } catch (Exception e) {
        hasLastError = true;
        lastError = "Exception in doRequest(): " + formatException(e);
    }

    return null;
}

From source file:de.mpg.escidoc.services.common.util.ProxyHelper.java

/**
 * Returns <code>java.net.Proxy</code> class for <code>java.net.URL.openConnection</code>
 * creation//  w  w w .j  a  v a2 s.c  om
 *
 * @param url url
 *
 * @throws Exception
 */
public static Proxy getProxy(final String url) {
    Proxy proxy = Proxy.NO_PROXY;

    getProxyProperties();

    if (proxyHost != null) {
        if (!findUrlInNonProxyHosts(url)) {
            SocketAddress proxyAddress = new InetSocketAddress(proxyHost, Integer.valueOf(proxyPort));
            proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
        }
    }

    return proxy;
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.intragrid.HttpClientUtil.java

/**
 * /*from   w  ww  .  ja  v  a  2  s  .co  m*/
 * 
 */
public static HttpClient createHttpClientWithHostConfig(URL url) {
    HttpClient client = new HttpClient();
    int port = url.getPort();
    if (port == -1) {
        port = url.getDefaultPort();
        if (port == -1) {
            port = 80;
        }
    }
    if ((url.getProtocol().equalsIgnoreCase("https")) && (sslSocketFactory != null)) {
        Protocol https = new Protocol("https",
                (ProtocolSocketFactory) new SSLSocketFactorySSLProtocolSocketFactory(sslSocketFactory), port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), https);
    } else {
        Protocol http = new Protocol("http", new SocketFactoryProtocolSocketFactory(SocketFactory.getDefault()),
                port);
        client.getHostConfiguration().setHost(url.getHost(), url.getPort(), http);
    }
    try {
        List<Proxy> proxies = ProxySelector.getDefault().select(url.toURI());
        for (Proxy p : proxies) {
            if (p.equals(Proxy.NO_PROXY))
                continue;
            if (!p.type().equals(Proxy.Type.HTTP))
                continue;
            InetSocketAddress addr = (InetSocketAddress) p.address();
            client.getHostConfiguration().setProxy(addr.getHostName(), addr.getPort());
            client.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", ""));
            break;
        }
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return client;
}

From source file:org.finra.herd.dao.helper.UrlHelper.java

/**
 * Reads JSON from a specified URL.// w  ww .  j  a  va2 s  . c om
 *
 * @param url the url
 *
 * @return the JSON object
 */
public JSONObject parseJsonObjectFromUrl(String url) {
    try {
        // Get proxy information.
        Proxy proxy;
        String httpProxyHost = configurationHelper.getProperty(ConfigurationValue.HTTP_PROXY_HOST);
        Integer httpProxyPort = configurationHelper.getProperty(ConfigurationValue.HTTP_PROXY_PORT,
                Integer.class);
        if (StringUtils.isNotBlank(httpProxyHost) && httpProxyPort != null) {
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort));
        } else {
            proxy = Proxy.NO_PROXY;
        }

        // Open an input stream as per specified URL.
        InputStream inputStream = urlOperations.openStream(new URL(url), proxy);

        try {
            // Parse the JSON object from the input stream.
            JSONParser jsonParser = new JSONParser();
            return (JSONObject) jsonParser.parse(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
        } catch (ParseException e) {
            throw new IllegalArgumentException(
                    String.format("Failed to parse JSON object from the URL: url=\"%s\"", url), e);
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        throw new IllegalArgumentException(String.format("Failed to read JSON from the URL: url=\"%s\"", url),
                e);
    }
}

From source file:net.sf.zekr.engine.network.NetworkController.java

public Proxy getProxy(String uri) throws URISyntaxException {
    Proxy proxy;/*from   ww w . ja  v a2s. co m*/
    if (SYSTEM_PROXY.equalsIgnoreCase(defaultProxy)) {
        List<Proxy> proxyList = proxySelector.select(new URI(uri));
        proxy = (Proxy) proxyList.get(0);
        if (proxy.address() == null) {
            proxy = Proxy.NO_PROXY;
        }
    } else if (MANUAL_PROXY.equalsIgnoreCase(defaultProxy)) {
        SocketAddress sa = InetSocketAddress.createUnresolved(proxyServer, proxyPort);
        Proxy.Type type = Proxy.Type.HTTP.name().equalsIgnoreCase(proxyType) ? Proxy.Type.HTTP
                : Proxy.Type.SOCKS.name().equalsIgnoreCase(proxyType) ? Proxy.Type.SOCKS : Proxy.Type.DIRECT;
        proxy = new Proxy(type, sa);
    } else {
        proxy = Proxy.NO_PROXY;
    }
    return proxy;
}