Example usage for java.net Proxy Proxy

List of usage examples for java.net Proxy Proxy

Introduction

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

Prototype

public Proxy(Type type, SocketAddress sa) 

Source Link

Document

Creates an entry representing a PROXY connection.

Usage

From source file:com.photon.phresco.framework.impl.SCMManagerImpl.java

void additionalAuthentication(String passPhrase) {
    final String passwordPhrase = passPhrase;
    JschConfigSessionFactory sessionFactory = new JschConfigSessionFactory() {
        @Override//from  w  w w .jav  a2 s .c o  m
        protected void configure(OpenSshConfig.Host hc, Session session) {
            CredentialsProvider provider = new CredentialsProvider() {
                @Override
                public boolean isInteractive() {
                    return false;
                }

                @Override
                public boolean supports(CredentialItem... items) {
                    return true;
                }

                @Override
                public boolean get(URIish uri, CredentialItem... items) throws UnsupportedCredentialItem {
                    for (CredentialItem item : items) {
                        if (item instanceof CredentialItem.StringType) {
                            ((CredentialItem.StringType) item).setValue(passwordPhrase);
                        }
                    }
                    return true;
                }
            };
            UserInfo userInfo = new CredentialsProviderUserInfo(session, provider);
            // Unknown host key for ssh
            java.util.Properties config = new java.util.Properties();
            config.put(STRICT_HOST_KEY_CHECKING, NO);
            session.setConfig(config);

            session.setUserInfo(userInfo);
        }
    };

    SshSessionFactory.setInstance(sessionFactory);

    /*
     * Enable clone of https url by trusting those urls
     */
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    final String https_proxy = System.getenv(HTTPS_PROXY);
    final String http_proxy = System.getenv(HTTP_PROXY);

    ProxySelector.setDefault(new ProxySelector() {
        final ProxySelector delegate = ProxySelector.getDefault();

        @Override
        public List<Proxy> select(URI uri) {
            // Filter the URIs to be proxied

            if (uri.toString().contains(HTTPS) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpsUri = new URI(https_proxy);
                    String host = httpsUri.getHost();
                    int port = httpsUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in https block of additionalAuthentication()");
                    }
                }
            }

            if (uri.toString().contains(HTTP) && StringUtils.isNotEmpty(http_proxy) && http_proxy != null) {
                try {
                    URI httpUri = new URI(http_proxy);
                    String host = httpUri.getHost();
                    int port = httpUri.getPort();
                    return Arrays.asList(new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(host, port)));
                } catch (URISyntaxException e) {
                    if (debugEnabled) {
                        S_LOGGER.debug("Url exception caught in http block of additionalAuthentication()");
                    }
                }
            }

            // revert to the default behaviour
            return delegate == null ? Arrays.asList(Proxy.NO_PROXY) : delegate.select(uri);
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            if (uri == null || sa == null || ioe == null) {
                throw new IllegalArgumentException("Arguments can't be null.");
            }
        }
    });

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance(SSL);
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (GeneralSecurityException e) {
        e.getLocalizedMessage();
    }
}

From source file:com.mobicage.rogerthat.Api.java

@SuppressWarnings("unchecked")
private Object wireRequest(final JSONObject request, final int attempt) throws RogerthatAPIException {
    final URL url;
    try {//from   w  ww  .  j  av a  2s  . c  o  m
        url = new URL(apiLocation);
    } catch (MalformedURLException e) {
        // Will never come here
        throw new RogerthatAPIException(e);
    }
    HttpURLConnection connection;
    try {
        if (proxyHost != null && proxyPort != 0) {
            // Adapt proxy settings
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            connection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }
    } catch (IOException e) {
        throw new RogerthatAPIException(e);
    }
    try {
        connection.setDoOutput(true);
        try {
            connection.setRequestMethod("POST");
        } catch (ProtocolException e) {
            // Will never come here
            throw new RogerthatAPIException(e);
        }
        connection.setRequestProperty("X-Nuntiuz-API-Key", apiKey);
        connection.setRequestProperty("Content-type", "application/json-rpc; charset=utf-8");
        connection.setReadTimeout(30000);
        Writer writer;
        try {
            writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            try {
                String jsonString = request.toJSONString();
                if (logging)
                    log.info("Sending request to Rogerthat:\n" + jsonString);
                writer.write(jsonString);
            } finally {
                writer.close();
            }
            switch (connection.getResponseCode()) {
            case HttpURLConnection.HTTP_OK:
                InputStream is = connection.getInputStream();
                try {
                    JSONObject result = (JSONObject) JSONValue
                            .parse(new BufferedReader(new InputStreamReader(is, "UTF-8")));
                    if (logging)
                        log.info("Result received from Rogerthat:\n" + result.toJSONString());
                    JSONObject error = (JSONObject) result.get("error");
                    if (error != null)
                        throw new RogerthatAPIException(Integer.parseInt(error.get("code").toString()),
                                (String) error.get("message"), error);
                    else
                        return result.get("result");
                } finally {
                    is.close();
                }
            case HttpURLConnection.HTTP_UNAUTHORIZED:
                throw new RogerthatAPIException(1000,
                        "Could not authenticate against Rogerth.at Messenger API! Check your api key.", null);
            case HttpURLConnection.HTTP_NOT_FOUND:
                throw new RogerthatAPIException(1000, "Rogerth.at Messenger API method not found!", null);
            default:
                if (attempt < 5)
                    return wireRequest(request, attempt + 1);
                else
                    throw new RogerthatAPIException(1000, "Could not send call to Rogerth.at Messenger!", null);
            }
        } catch (IOException e) {
            // Will never come here
            throw new RogerthatAPIException(e);
        }
    } finally {
        connection.disconnect();
    }
}

From source file:com.dwdesign.tweetings.util.Utils.java

public static Proxy getProxy(final Context context) {
    if (context == null)
        return null;
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final boolean enable_proxy = prefs.getBoolean(PREFERENCE_KEY_ENABLE_PROXY, false);
    if (!enable_proxy)
        return Proxy.NO_PROXY;
    final String proxy_host = prefs.getString(PREFERENCE_KEY_PROXY_HOST, null);
    final int proxy_port = parseInt(prefs.getString(PREFERENCE_KEY_PROXY_PORT, "-1"));
    if (!isNullOrEmpty(proxy_host) && proxy_port > 0) {
        final SocketAddress addr = InetSocketAddress.createUnresolved(proxy_host, proxy_port);
        return new Proxy(Proxy.Type.HTTP, addr);
    }/*from   w  w  w . j a  v a  2 s.  c om*/
    return Proxy.NO_PROXY;
}

From source file:org.mariotaku.twidere.util.Utils.java

public static Proxy getProxy(final Context context) {
    if (context == null)
        return null;
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final boolean enable_proxy = prefs.getBoolean(PREFERENCE_KEY_ENABLE_PROXY, false);
    if (!enable_proxy)
        return Proxy.NO_PROXY;
    final String proxy_host = prefs.getString(PREFERENCE_KEY_PROXY_HOST, null);
    final int proxy_port = parseInt(prefs.getString(PREFERENCE_KEY_PROXY_PORT, "-1"));
    if (!isEmpty(proxy_host) && proxy_port > 0) {
        final SocketAddress addr = InetSocketAddress.createUnresolved(proxy_host, proxy_port);
        return new Proxy(Proxy.Type.HTTP, addr);
    }// w ww.  ja  v  a2 s  .  com
    return Proxy.NO_PROXY;
}

From source file:de.vanita5.twittnuker.util.Utils.java

public static Proxy getProxy(final Context context) {
    if (context == null)
        return null;
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final boolean enable_proxy = prefs.getBoolean(KEY_ENABLE_PROXY, false);
    if (!enable_proxy)
        return Proxy.NO_PROXY;
    final String proxyHost = prefs.getString(KEY_PROXY_HOST, null);
    final int proxyPort = ParseUtils.parseInt(prefs.getString(KEY_PROXY_PORT, "-1"));
    if (!isEmpty(proxyHost) && proxyPort >= 0 && proxyPort < 65535) {
        final SocketAddress addr = InetSocketAddress.createUnresolved(proxyHost, proxyPort);
        return new Proxy(Proxy.Type.HTTP, addr);
    }/*from  w ww .  j a  va 2 s . co m*/
    return Proxy.NO_PROXY;
}

From source file:com.irccloud.android.NetworkConnection.java

public String fetch(URL url, String postdata, String sk, String token, HashMap<String, String> headers)
        throws Exception {
    HttpURLConnection conn = null;

    Proxy proxy = null;//w  w  w .  j av  a 2 s  . co  m
    String host = null;
    int port = -1;

    if (Build.VERSION.SDK_INT < 11) {
        Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
        proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url + " via proxy: " + host);
    } else {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url);
    }

    if (url.getProtocol().toLowerCase().equals("https")) {
        HttpsURLConnection https = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
        if (url.getHost().equals(IRCCLOUD_HOST))
            https.setSSLSocketFactory(IRCCloudSocketFactory);
        conn = https;
    } else {
        conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    }

    conn.setConnectTimeout(5000);
    conn.setReadTimeout(5000);
    conn.setUseCaches(false);
    conn.setRequestProperty("User-Agent", useragent);
    conn.setRequestProperty("Accept", "application/json");
    if (headers != null) {
        for (String key : headers.keySet()) {
            conn.setRequestProperty(key, headers.get(key));
        }
    }
    if (sk != null)
        conn.setRequestProperty("Cookie", "session=" + sk);
    if (token != null)
        conn.setRequestProperty("x-auth-formtoken", token);
    if (postdata != null) {
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        OutputStream ostr = null;
        try {
            ostr = conn.getOutputStream();
            ostr.write(postdata.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ostr != null)
                ostr.close();
        }
    }
    BufferedReader reader = null;
    String response = "";

    try {
        ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via WiFi");
        } else {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via mobile");
        }
    } catch (Exception e) {
    }

    try {
        if (conn.getInputStream() != null) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()), 512);
        }
    } catch (IOException e) {
        if (conn.getErrorStream() != null) {
            reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()), 512);
        }
    }

    if (reader != null) {
        response = toString(reader);
        reader.close();
    }
    conn.disconnect();
    return response;
}

From source file:com.atlauncher.data.Settings.java

public Proxy getProxy() {
    if (!this.enableProxy) {
        return null;
    }/*  w ww .  ja va2s .  com*/
    if (this.proxy == null) {
        Type type;
        if (this.proxyType.equals("HTTP")) {
            type = Proxy.Type.HTTP;
        } else if (this.proxyType.equals("SOCKS")) {
            type = Proxy.Type.SOCKS;
        } else if (this.proxyType.equals("DIRECT")) {
            type = Proxy.Type.DIRECT;
        } else {
            // Oh noes, problem!
            LogManager.warn("Tried to set proxy type to " + this.proxyType
                    + " which is not valid! Proxy support " + "disabled!");
            this.enableProxy = false;
            return null;
        }
        this.proxy = new Proxy(type, new InetSocketAddress(this.proxyHost, this.proxyPort));
    }
    return this.proxy;
}

From source file:com.atlauncher.data.Settings.java

public Proxy getProxyForAuth() {
    if (!this.enableProxy) {
        return Proxy.NO_PROXY;
    }//w  w  w.  j  a v a 2s  .  c  o m
    if (this.proxy == null) {
        Type type;
        if (this.proxyType.equals("HTTP")) {
            type = Proxy.Type.HTTP;
        } else if (this.proxyType.equals("SOCKS")) {
            type = Proxy.Type.SOCKS;
        } else if (this.proxyType.equals("DIRECT")) {
            type = Proxy.Type.DIRECT;
        } else {
            // Oh noes, problem!
            LogManager.warn("Tried to set proxy type to " + this.proxyType
                    + " which is not valid! Proxy support " + "disabled!");
            this.enableProxy = false;
            return Proxy.NO_PROXY;
        }
        this.proxy = new Proxy(type, new InetSocketAddress(this.proxyHost, this.proxyPort));
    }
    return this.proxy;
}

From source file:com.irccloud.android.NetworkConnection.java

public Bitmap fetchImage(URL url, boolean cacheOnly) throws Exception {
    HttpURLConnection conn = null;

    Proxy proxy = null;/* ww  w .ja v  a  2 s.co  m*/
    String host = null;
    int port = -1;

    if (Build.VERSION.SDK_INT < 11) {
        Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
        proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url + " via proxy: " + host);
    } else {
        Crashlytics.log(Log.DEBUG, TAG, "Requesting: " + url);
    }

    if (url.getProtocol().toLowerCase().equals("https")) {
        HttpsURLConnection https = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
        if (url.getHost().equals(IRCCLOUD_HOST))
            https.setSSLSocketFactory(IRCCloudSocketFactory);
        conn = https;
    } else {
        conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    }

    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setUseCaches(true);
    conn.setRequestProperty("User-Agent", useragent);
    if (cacheOnly)
        conn.addRequestProperty("Cache-Control", "only-if-cached");
    Bitmap bitmap = null;

    try {
        ConnectivityManager cm = (ConnectivityManager) IRCCloudApplication.getInstance()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI) {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via WiFi");
        } else {
            Crashlytics.log(Log.DEBUG, TAG, "Loading via mobile");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        if (conn.getInputStream() != null) {
            bitmap = BitmapFactory.decodeStream(conn.getInputStream());
        }
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        e.printStackTrace();
    }

    conn.disconnect();
    return bitmap;
}