Search in sources :

Example 51 with Proxy

use of java.net.Proxy in project intellij-community by JetBrains.

the class ProxyModule method setupProxy.

private void setupProxy(@NotNull Command command) {
    SVNURL repositoryUrl = command.requireRepositoryUrl();
    Proxy proxy = AuthenticationService.getIdeaDefinedProxy(repositoryUrl);
    if (proxy != null) {
        String hostGroup = ensureGroupForHost(command, repositoryUrl.getHost());
        InetSocketAddress address = (InetSocketAddress) proxy.address();
        command.put("--config-option");
        command.put(String.format("servers:%s:http-proxy-host=%s", hostGroup, address.getHostName()));
        command.put("--config-option");
        command.put(String.format("servers:%s:http-proxy-port=%s", hostGroup, address.getPort()));
    }
}
Also used : Proxy(java.net.Proxy) SVNURL(org.tmatesoft.svn.core.SVNURL) InetSocketAddress(java.net.InetSocketAddress)

Example 52 with Proxy

use of java.net.Proxy in project mc-dev by Bukkit.

the class HttpUtilities method a.

private static String a(URL url, String s, boolean flag) {
    try {
        Proxy proxy = MinecraftServer.getServer() == null ? null : MinecraftServer.getServer().aq();
        if (proxy == null) {
            proxy = Proxy.NO_PROXY;
        }
        HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection(proxy);
        httpurlconnection.setRequestMethod("POST");
        httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpurlconnection.setRequestProperty("Content-Length", "" + s.getBytes().length);
        httpurlconnection.setRequestProperty("Content-Language", "en-US");
        httpurlconnection.setUseCaches(false);
        httpurlconnection.setDoInput(true);
        httpurlconnection.setDoOutput(true);
        DataOutputStream dataoutputstream = new DataOutputStream(httpurlconnection.getOutputStream());
        dataoutputstream.writeBytes(s);
        dataoutputstream.flush();
        dataoutputstream.close();
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream()));
        StringBuffer stringbuffer = new StringBuffer();
        String s1;
        while ((s1 = bufferedreader.readLine()) != null) {
            stringbuffer.append(s1);
            stringbuffer.append('\r');
        }
        bufferedreader.close();
        return stringbuffer.toString();
    } catch (Exception exception) {
        if (!flag) {
            b.error("Could not post to " + url, exception);
        }
        return "";
    }
}
Also used : Proxy(java.net.Proxy) HttpURLConnection(java.net.HttpURLConnection) InputStreamReader(java.io.InputStreamReader) DataOutputStream(java.io.DataOutputStream) BufferedReader(java.io.BufferedReader) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 53 with Proxy

use of java.net.Proxy in project AntennaPod by AntennaPod.

the class AntennapodHttpClient method newBuilder.

/**
     * Creates a new HTTP client.  Most users should just use
     * getHttpClient() to get the standard AntennaPod client,
     * but sometimes it's necessary for others to have their own
     * copy so that the clients don't share state.
     * @return http client
     */
@NonNull
public static OkHttpClient.Builder newBuilder() {
    Log.d(TAG, "Creating new instance of HTTP client");
    System.setProperty("http.maxConnections", String.valueOf(MAX_CONNECTIONS));
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    // detect 301 Moved permanently and 308 Permanent Redirect
    builder.networkInterceptors().add(chain -> {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (response.code() == HttpURLConnection.HTTP_MOVED_PERM || response.code() == StatusLine.HTTP_PERM_REDIRECT) {
            String location = response.header("Location");
            if (location.startsWith("/")) {
                HttpUrl url = request.url();
                location = url.scheme() + "://" + url.host() + location;
            } else if (!location.toLowerCase().startsWith("http://") && !location.toLowerCase().startsWith("https://")) {
                HttpUrl url = request.url();
                String path = url.encodedPath();
                String newPath = path.substring(0, path.lastIndexOf("/") + 1) + location;
                location = url.scheme() + "://" + url.host() + newPath;
            }
            try {
                DBWriter.updateFeedDownloadURL(request.url().toString(), location).get();
            } catch (Exception e) {
                Log.e(TAG, Log.getStackTraceString(e));
            }
        }
        return response;
    });
    // set cookie handler
    CookieManager cm = new CookieManager();
    cm.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
    builder.cookieJar(new JavaNetCookieJar(cm));
    // set timeouts
    builder.connectTimeout(CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    builder.writeTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS);
    // configure redirects
    builder.followRedirects(true);
    builder.followSslRedirects(true);
    ProxyConfig config = UserPreferences.getProxyConfig();
    if (config.type != Proxy.Type.DIRECT) {
        int port = config.port > 0 ? config.port : ProxyConfig.DEFAULT_PORT;
        SocketAddress address = InetSocketAddress.createUnresolved(config.host, port);
        Proxy proxy = new Proxy(config.type, address);
        builder.proxy(proxy);
        if (!TextUtils.isEmpty(config.username)) {
            String credentials = Credentials.basic(config.username, config.password);
            builder.interceptors().add(chain -> {
                Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
                return chain.proceed(request);
            });
        }
    }
    if (16 <= Build.VERSION.SDK_INT && Build.VERSION.SDK_INT < 21) {
        builder.sslSocketFactory(new CustomSslSocketFactory(), trustManager());
    }
    return builder;
}
Also used : JavaNetCookieJar(okhttp3.JavaNetCookieJar) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) Response(okhttp3.Response) Proxy(java.net.Proxy) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress) CookieManager(java.net.CookieManager) NonNull(android.support.annotation.NonNull)

Example 54 with Proxy

use of java.net.Proxy in project AntennaPod by AntennaPod.

the class ProxyDialog method createDialog.

public Dialog createDialog() {
    dialog = new MaterialDialog.Builder(context).title(R.string.pref_proxy_title).customView(R.layout.proxy_settings, true).positiveText(R.string.proxy_test_label).negativeText(R.string.cancel_label).onPositive((dialog1, which) -> {
        if (!testSuccessful) {
            dialog.getActionButton(DialogAction.POSITIVE).setEnabled(false);
            test();
            return;
        }
        String type = (String) ((Spinner) dialog1.findViewById(R.id.spType)).getSelectedItem();
        ProxyConfig proxy;
        if (Proxy.Type.valueOf(type) == Proxy.Type.DIRECT) {
            proxy = ProxyConfig.direct();
        } else {
            String host = etHost.getText().toString();
            String port = etPort.getText().toString();
            String username = etUsername.getText().toString();
            if (TextUtils.isEmpty(username)) {
                username = null;
            }
            String password = etPassword.getText().toString();
            if (TextUtils.isEmpty(password)) {
                password = null;
            }
            int portValue = 0;
            if (!TextUtils.isEmpty(port)) {
                portValue = Integer.valueOf(port);
            }
            proxy = ProxyConfig.http(host, portValue, username, password);
        }
        UserPreferences.setProxyConfig(proxy);
        AntennapodHttpClient.reinit();
        dialog.dismiss();
    }).onNegative((dialog1, which) -> dialog1.dismiss()).autoDismiss(false).build();
    View view = dialog.getCustomView();
    spType = (Spinner) view.findViewById(R.id.spType);
    String[] types = { Proxy.Type.DIRECT.name(), Proxy.Type.HTTP.name() };
    ArrayAdapter<String> adapter = new ArrayAdapter<>(context, android.R.layout.simple_spinner_item, types);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spType.setAdapter(adapter);
    ProxyConfig proxyConfig = UserPreferences.getProxyConfig();
    spType.setSelection(adapter.getPosition(proxyConfig.type.name()));
    etHost = (EditText) view.findViewById(R.id.etHost);
    if (!TextUtils.isEmpty(proxyConfig.host)) {
        etHost.setText(proxyConfig.host);
    }
    etHost.addTextChangedListener(requireTestOnChange);
    etPort = (EditText) view.findViewById(R.id.etPort);
    if (proxyConfig.port > 0) {
        etPort.setText(String.valueOf(proxyConfig.port));
    }
    etPort.addTextChangedListener(requireTestOnChange);
    etUsername = (EditText) view.findViewById(R.id.etUsername);
    if (!TextUtils.isEmpty(proxyConfig.username)) {
        etUsername.setText(proxyConfig.username);
    }
    etUsername.addTextChangedListener(requireTestOnChange);
    etPassword = (EditText) view.findViewById(R.id.etPassword);
    if (!TextUtils.isEmpty(proxyConfig.password)) {
        etPassword.setText(proxyConfig.username);
    }
    etPassword.addTextChangedListener(requireTestOnChange);
    if (proxyConfig.type == Proxy.Type.DIRECT) {
        enableSettings(false);
        setTestRequired(false);
    }
    spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            enableSettings(position > 0);
            setTestRequired(position > 0);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            enableSettings(false);
        }
    });
    txtvMessage = (TextView) view.findViewById(R.id.txtvMessage);
    checkValidity();
    return dialog;
}
Also used : Context(android.content.Context) SocketAddress(java.net.SocketAddress) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Dialog(android.app.Dialog) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) Observable(rx.Observable) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) MDButton(com.afollestad.materialdialogs.internal.MDButton) Patterns(android.util.Patterns) Proxy(java.net.Proxy) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Response(okhttp3.Response) AdapterView(android.widget.AdapterView) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Request(okhttp3.Request) Subscriber(rx.Subscriber) R(de.danoeh.antennapod.R) ContextCompat(android.support.v4.content.ContextCompat) TextUtils(android.text.TextUtils) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) ProxyConfig(de.danoeh.antennapod.core.service.download.ProxyConfig) Spinner(android.widget.Spinner) TimeUnit(java.util.concurrent.TimeUnit) ArrayAdapter(android.widget.ArrayAdapter) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Subscription(rx.Subscription) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) ProxyConfig(de.danoeh.antennapod.core.service.download.ProxyConfig) View(android.view.View) AdapterView(android.widget.AdapterView) TextView(android.widget.TextView) AdapterView(android.widget.AdapterView) ArrayAdapter(android.widget.ArrayAdapter)

Example 55 with Proxy

use of java.net.Proxy in project AntennaPod by AntennaPod.

the class ProxyDialog method test.

private void test() {
    if (subscription != null) {
        subscription.unsubscribe();
    }
    if (!checkValidity()) {
        setTestRequired(true);
        return;
    }
    TypedArray res = context.getTheme().obtainStyledAttributes(new int[] { android.R.attr.textColorPrimary });
    int textColorPrimary = res.getColor(0, 0);
    res.recycle();
    String checking = context.getString(R.string.proxy_checking);
    txtvMessage.setTextColor(textColorPrimary);
    txtvMessage.setText("{fa-circle-o-notch spin} " + checking);
    txtvMessage.setVisibility(View.VISIBLE);
    subscription = Observable.create(new Observable.OnSubscribe<Response>() {

        @Override
        public void call(Subscriber<? super Response> subscriber) {
            String type = (String) spType.getSelectedItem();
            String host = etHost.getText().toString();
            String port = etPort.getText().toString();
            String username = etUsername.getText().toString();
            String password = etPassword.getText().toString();
            int portValue = 8080;
            if (!TextUtils.isEmpty(port)) {
                portValue = Integer.valueOf(port);
            }
            SocketAddress address = InetSocketAddress.createUnresolved(host, portValue);
            Proxy.Type proxyType = Proxy.Type.valueOf(type.toUpperCase());
            Proxy proxy = new Proxy(proxyType, address);
            OkHttpClient.Builder builder = AntennapodHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).proxy(proxy);
            builder.interceptors().clear();
            OkHttpClient client = builder.build();
            if (!TextUtils.isEmpty(username)) {
                String credentials = Credentials.basic(username, password);
                client.interceptors().add(chain -> {
                    Request request = chain.request().newBuilder().header("Proxy-Authorization", credentials).build();
                    return chain.proceed(request);
                });
            }
            Request request = new Request.Builder().url("http://www.google.com").head().build();
            try {
                Response response = client.newCall(request).execute();
                subscriber.onNext(response);
            } catch (IOException e) {
                subscriber.onError(e);
            }
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread()).subscribe(response -> {
        int colorId;
        String icon;
        String result;
        if (response.isSuccessful()) {
            colorId = R.color.download_success_green;
            icon = "{fa-check}";
            result = context.getString(R.string.proxy_test_successful);
        } else {
            colorId = R.color.download_failed_red;
            icon = "{fa-close}";
            result = context.getString(R.string.proxy_test_failed);
        }
        int color = ContextCompat.getColor(context, colorId);
        txtvMessage.setTextColor(color);
        String message = String.format("%s %s: %s", icon, result, response.message());
        txtvMessage.setText(message);
        setTestRequired(!response.isSuccessful());
    }, error -> {
        String icon = "{fa-close}";
        String result = context.getString(R.string.proxy_test_failed);
        int color = ContextCompat.getColor(context, R.color.download_failed_red);
        txtvMessage.setTextColor(color);
        String message = String.format("%s %s: %s", icon, result, error.getMessage());
        txtvMessage.setText(message);
        setTestRequired(true);
    });
}
Also used : Context(android.content.Context) SocketAddress(java.net.SocketAddress) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Dialog(android.app.Dialog) Editable(android.text.Editable) TypedArray(android.content.res.TypedArray) Observable(rx.Observable) UserPreferences(de.danoeh.antennapod.core.preferences.UserPreferences) MDButton(com.afollestad.materialdialogs.internal.MDButton) Patterns(android.util.Patterns) Proxy(java.net.Proxy) Schedulers(rx.schedulers.Schedulers) View(android.view.View) Response(okhttp3.Response) AdapterView(android.widget.AdapterView) AntennapodHttpClient(de.danoeh.antennapod.core.service.download.AntennapodHttpClient) Request(okhttp3.Request) Subscriber(rx.Subscriber) R(de.danoeh.antennapod.R) ContextCompat(android.support.v4.content.ContextCompat) TextUtils(android.text.TextUtils) DialogAction(com.afollestad.materialdialogs.DialogAction) IOException(java.io.IOException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) ProxyConfig(de.danoeh.antennapod.core.service.download.ProxyConfig) Spinner(android.widget.Spinner) TimeUnit(java.util.concurrent.TimeUnit) ArrayAdapter(android.widget.ArrayAdapter) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Subscription(rx.Subscription) EditText(android.widget.EditText) TextWatcher(android.text.TextWatcher) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Observable(rx.Observable) Response(okhttp3.Response) Proxy(java.net.Proxy) TypedArray(android.content.res.TypedArray) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Aggregations

Proxy (java.net.Proxy)132 InetSocketAddress (java.net.InetSocketAddress)71 URL (java.net.URL)44 IOException (java.io.IOException)35 Test (org.junit.Test)22 URI (java.net.URI)21 ProxySelector (java.net.ProxySelector)20 HttpURLConnection (java.net.HttpURLConnection)19 SocketAddress (java.net.SocketAddress)19 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)13 URISyntaxException (java.net.URISyntaxException)11 ServerSocket (java.net.ServerSocket)10 Socket (java.net.Socket)9 PasswordAuthentication (java.net.PasswordAuthentication)8 InterruptedIOException (java.io.InterruptedIOException)6 URLConnection (java.net.URLConnection)6 SSLServerSocket (javax.net.ssl.SSLServerSocket)6 List (java.util.List)5 SSLSocket (javax.net.ssl.SSLSocket)5 OkHttpClient (okhttp3.OkHttpClient)5