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.orange.cloud.servicebroker.filter.core.config.OkHttpClientConfig.java

@Bean
public OkHttpClient squareHttpClient() {
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override/* ww w.  j  a v a 2s.co  m*/
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCerts() };

    SSLSocketFactory sslSocketFactory = null;
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        sslSocketFactory = (SSLSocketFactory) sc.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        new IllegalArgumentException(e);
    }

    log.info("===> configuring OkHttp");
    OkHttpClient.Builder ohc = new OkHttpClient.Builder().protocols(Arrays.asList(Protocol.HTTP_1_1))
            .followRedirects(true).followSslRedirects(true).hostnameVerifier(hostnameVerifier)
            .sslSocketFactory(sslSocketFactory).addInterceptor(LOGGING_INTERCEPTOR);

    if ((this.proxyHost != null) && (this.proxyHost.length() > 0)) {
        log.info("Activating proxy on host {} port {}", this.proxyHost, this.proxyPort);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxyHost, this.proxyPort));
        ohc.proxy(proxy);
        ohc.proxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Arrays.asList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress socket, IOException e) {
                throw new IllegalArgumentException("connection to proxy failed", e);
            }
        });
    }

    return ohc.build();
}

From source file:be.agiv.security.client.ClientProxySelector.java

/**
 * Sets the proxy for the (hostname of the) given location.
 * /* w  w w .j a  va  2 s.  c o  m*/
 * @param location
 *            the location on which the proxy settings apply.
 * @param proxyHost
 *            the host of the proxy.
 * @param proxyPort
 *            the port of the proxy.
 * @param proxyType
 *            the type of the proxy.
 */
public void setProxy(String location, String proxyHost, int proxyPort, Type proxyType) {
    String hostname;
    try {
        hostname = new URL(location).getHost();
    } catch (MalformedURLException e) {
        throw new RuntimeException("URL error: " + e.getMessage(), e);
    }
    if (null == proxyHost) {
        LOG.debug("removing proxy for: " + hostname);
        this.proxies.remove(hostname);
    } else {
        LOG.debug("setting proxy for: " + hostname);
        this.proxies.put(hostname, new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort)));
    }
}

From source file:net.ymate.module.webproxy.impl.DefaultModuleCfg.java

public DefaultModuleCfg(YMP owner) {
    Map<String, String> _moduleCfgs = owner.getConfig().getModuleConfigs(IWebProxy.MODULE_NAME);
    ///*from   w  w  w. j a v a 2 s.  c o  m*/
    __serviceBaseUrl = _moduleCfgs.get("service_base_url");
    if (StringUtils.isBlank(__serviceBaseUrl)) {
        throw new NullArgumentException("service_base_url");
    }
    if (!StringUtils.startsWithIgnoreCase(__serviceBaseUrl, "http://")
            && !StringUtils.startsWithIgnoreCase(__serviceBaseUrl, "https://")) {
        throw new IllegalArgumentException("Argument service_base_url must be start with http or https");
    } else if (StringUtils.endsWith(__serviceBaseUrl, "/")) {
        __serviceBaseUrl = StringUtils.substringBeforeLast(__serviceBaseUrl, "/");
    }
    //
    __serviceRequestPrefix = StringUtils.trimToEmpty(_moduleCfgs.get("service_request_prefix"));
    if (StringUtils.isNotBlank(__serviceRequestPrefix)
            && !StringUtils.startsWith(__serviceRequestPrefix, "/")) {
        __serviceRequestPrefix = "/" + __serviceRequestPrefix;
    }
    //
    __useProxy = BlurObject.bind(_moduleCfgs.get("use_proxy")).toBooleanValue();
    if (__useProxy) {
        Proxy.Type _proxyType = Proxy.Type
                .valueOf(StringUtils.defaultIfBlank(_moduleCfgs.get("proxy_type"), "HTTP").toUpperCase());
        int _proxyPrort = BlurObject.bind(StringUtils.defaultIfBlank(_moduleCfgs.get("proxy_port"), "80"))
                .toIntValue();
        String _proxyHost = _moduleCfgs.get("proxy_host");
        if (StringUtils.isBlank(_proxyHost)) {
            throw new NullArgumentException("proxy_host");
        }
        __proxy = new Proxy(_proxyType, new InetSocketAddress(_proxyHost, _proxyPrort));
    }
    //
    __useCaches = BlurObject.bind(_moduleCfgs.get("use_caches")).toBooleanValue();
    __instanceFollowRedirects = BlurObject.bind(_moduleCfgs.get("instance_follow_redirects")).toBooleanValue();
    //
    __connectTimeout = BlurObject.bind(_moduleCfgs.get("connect_timeout")).toIntValue();
    __readTimeout = BlurObject.bind(_moduleCfgs.get("read_timeout")).toIntValue();
    //
    __transferBlackList = Arrays
            .asList(StringUtils.split(StringUtils.trimToEmpty(_moduleCfgs.get("transfer_blacklist")), "|"));
    //
    __transferHeaderEnabled = BlurObject.bind(_moduleCfgs.get("transfer_header_enabled")).toBooleanValue();
    //
    if (__transferHeaderEnabled) {
        String[] _filters = StringUtils
                .split(StringUtils.lowerCase(_moduleCfgs.get("transfer_header_whitelist")), "|");
        if (_filters != null && _filters.length > 0) {
            __transferHeaderWhiteList = Arrays.asList(_filters);
        } else {
            __transferHeaderWhiteList = Collections.emptyList();
        }
        //
        _filters = StringUtils.split(StringUtils.lowerCase(_moduleCfgs.get("transfer_header_blacklist")), "|");
        if (_filters != null && _filters.length > 0) {
            __transferHeaderBlackList = Arrays.asList(_filters);
        } else {
            __transferHeaderBlackList = Collections.emptyList();
        }
        //
        _filters = StringUtils.split(StringUtils.lowerCase(_moduleCfgs.get("response_header_whitelist")), "|");
        if (_filters != null && _filters.length > 0) {
            __responseHeaderWhiteList = Arrays.asList(_filters);
        } else {
            __responseHeaderWhiteList = Collections.emptyList();
        }
    } else {
        __transferHeaderWhiteList = Collections.emptyList();
        __transferHeaderBlackList = Collections.emptyList();
        //
        __responseHeaderWhiteList = Collections.emptyList();
    }
}

From source file:ovh.tgrhavoc.aibot.RealmsUtil.java

private static Proxy wrapProxy(ProxyData proxy) {
    if (proxy == null
            || (proxy.getType() != ProxyData.ProxyType.HTTP && proxy.getType() != ProxyData.ProxyType.SOCKS))
        return null;
    return new Proxy(proxy.getType() == ProxyData.ProxyType.HTTP ? Proxy.Type.HTTP : Proxy.Type.SOCKS,
            new InetSocketAddress(proxy.getHostName(), proxy.getPort()));
}

From source file:com.none.tom.simplerssreader.net.FeedDownloader.java

@SuppressWarnings("ConstantConditions")
public static InputStream getInputStream(final Context context, final String feedUrl) {
    final ConnectivityManager manager = context.getSystemService(ConnectivityManager.class);
    final NetworkInfo info = manager.getActiveNetworkInfo();

    if (info == null || !info.isConnected()) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK);
        LogUtils.logError("No network connection");
        return null;
    }/*from  w w  w .  ja v  a2  s.  co m*/

    URL url;
    try {
        url = new URL(feedUrl);
    } catch (final MalformedURLException e) {
        ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_BAD_REQUEST, e);
        return null;
    }

    final boolean[] networkPrefs = DefaultSharedPrefUtils.getNetworkPreferences(context);
    final boolean useHttpTorProxy = networkPrefs[0];
    final boolean httpsOnly = networkPrefs[1];
    final boolean followRedir = networkPrefs[2];

    for (int nrRedirects = 0;; nrRedirects++) {
        if (nrRedirects >= HTTP_NR_REDIRECTS_MAX) {
            ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_TOO_MANY_REDIRECTS);
            LogUtils.logError("Too many redirects");
            return null;
        }

        HttpURLConnection conn = null;

        try {
            if (httpsOnly && url.getProtocol().equalsIgnoreCase("http")) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTPS_ONLY);
                LogUtils.logError("Attempting insecure connection");
                return null;
            }

            if (useHttpTorProxy) {
                conn = (HttpURLConnection) url.openConnection(new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(InetAddress.getByName(HTTP_PROXY_TOR_IP), HTTP_PROXY_TOR_PORT)));
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }

            conn.setRequestProperty("Accept-Charset", StandardCharsets.UTF_8.name());

            conn.setConnectTimeout(HTTP_URL_DEFAULT_TIMEOUT);
            conn.setReadTimeout(HTTP_URL_DEFAULT_TIMEOUT);

            conn.connect();

            final int responseCode = conn.getResponseCode();

            switch (responseCode) {
            case HttpURLConnection.HTTP_OK:
                return getInputStream(conn.getInputStream());
            case HttpURLConnection.HTTP_MOVED_PERM:
            case HttpURLConnection.HTTP_MOVED_TEMP:
            case HttpURLConnection.HTTP_SEE_OTHER:
            case HTTP_TEMP_REDIRECT:
                if (followRedir) {
                    final String location = conn.getHeaderField("Location");
                    url = new URL(url, location);

                    if (responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
                        SharedPrefUtils.updateSubscriptionUrl(context, url.toString());
                    }
                    continue;
                }
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_FOLLOW_REDIRECT_DENIED);
                LogUtils.logError("Couldn't follow redirect");
                return null;
            default:
                if (responseCode < 0) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_RESPONSE);
                    LogUtils.logError("No valid HTTP response");
                    return null;
                } else if (responseCode >= 400 && responseCode <= 500) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_CLIENT);
                } else if (responseCode >= 500 && responseCode <= 600) {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_SERVER);
                } else {
                    ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED);
                }
                LogUtils.logError("Error " + responseCode + ": " + conn.getResponseMessage());
                return null;
            }
        } catch (final IOException e) {
            if ((e instanceof ConnectException && e.getMessage().equals("Network is unreachable"))
                    || e instanceof SocketTimeoutException || e instanceof UnknownHostException) {
                ErrorHandler.setErrno(ErrorHandler.ERROR_NETWORK, e);
            } else {
                ErrorHandler.setErrno(ErrorHandler.ERROR_HTTP_UNHANDLED, e);
            }
            return null;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }
}

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

private void initializeProxiesFromConfiguration() {
    Configuration proxyConfig = application.getConfiguration().subset(PROXY);

    if (!proxyConfig.isEmpty()) {
        if (!proxyConfig.containsKey(TYPE)) {
            throw new ConfigurationException("Missing \"type\"  in the proxy configuration.");
        }//w  w  w  . j  a  v  a  2 s.com
        String type = proxyConfig.getString(TYPE);

        if (!proxyConfig.containsKey(HOST)) {
            throw new ConfigurationException("Missing \"url\" in the proxy configuration.");
        }
        String url = proxyConfig.getString(HOST);

        if (!proxyConfig.containsKey(PORT)) {
            throw new ConfigurationException("Missing \"port\"  in the proxy configuration.");
        }
        int port = proxyConfig.getInt(PORT);

        String[] exclusionsConfig = proxyConfig.getStringArray(EXCLUSIONS);
        if (exclusionsConfig != null) {
            exclusions = Arrays.stream(exclusionsConfig).map(this::makePattern).collect(toList());
        }
        proxy = Optional.of(new Proxy(Proxy.Type.valueOf(type), new InetSocketAddress(url, port)));
    } else {
        proxy = Optional.empty();
        exclusions = new ArrayList<>();
    }
}

From source file:com.norconex.commons.lang.url.URLStreamer.java

/**
 * Streams URL content.//from w w w . ja v a2s .  c om
 * @param url the URL to stream
 * @param creds credentials for a protected URL
 * @param proxy proxy to use to stream the URL
 * @param proxyCreds credentials to access the proxy
 * @return a URL content InputStream
 */
public static InputStream stream(String url, Credentials creds, HttpHost proxy, Credentials proxyCreds) {
    try {
        URLConnection conn = null;
        if (proxy != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Streaming with proxy: " + proxy.getHostName() + ":" + proxy.getPort());
            }
            Proxy p = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHostName(), proxy.getPort()));
            //Authenticator.
            conn = new URL(url).openConnection(p);
            if (proxyCreds != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("Streaming with proxy credentials.");
                }
                conn.setRequestProperty("Proxy-Authorization",
                        base64BasicAuth(proxyCreds.getUsername(), proxyCreds.getPassword()));
            }
        } else {
            conn = new URL(url).openConnection();
        }
        if (creds != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Streaming with credentials.");
            }
            conn.setRequestProperty("Authorization", base64BasicAuth(creds.getUsername(), creds.getPassword()));
        }
        return responseInputStream(conn);
    } catch (IOException e) {
        throw new URLException("Could not stream URL: " + url, e);
    }
}

From source file:edu.brandeis.cs.planner.utils.WsdlClient.java

public void setProxy(String host, int port) {
    // https://docs.oracle.com/javase/7/docs/api/java/net/doc-files/net-properties.html
    AxisProperties.setProperty("http.proxyHost", host);
    AxisProperties.setProperty("http.proxyPort", String.valueOf(port));
    AxisProperties.setProperty("https.proxyHost", host);
    AxisProperties.setProperty("https.proxyPort", String.valueOf(port));
    SocketAddress address = new InetSocketAddress(host, port);
    proxy = new Proxy(Proxy.Type.HTTP, address);
}

From source file:org.graylog2.alarmcallbacks.pagerduty.PagerDutyClient.java

public void trigger(final Stream stream, final AlertCondition.CheckResult checkResult)
        throws AlarmCallbackException {
    final URL url;
    try {//ww  w  .  j a  va 2  s.  c  o  m
        url = new URL(API_URL);
    } catch (MalformedURLException e) {
        throw new AlarmCallbackException("Malformed URL for PagerDuty API.", e);
    }

    final HttpURLConnection conn;
    try {
        if (httpProxyUri != null) {
            final InetSocketAddress proxyAddress = new InetSocketAddress(httpProxyUri.getHost(),
                    httpProxyUri.getPort());
            final Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
            conn = (HttpURLConnection) url.openConnection(proxy);
        } else {
            conn = (HttpURLConnection) url.openConnection();
        }
        conn.setRequestMethod("POST");
    } catch (IOException e) {
        throw new AlarmCallbackException("Error while opening connection to PagerDuty API.", e);
    }

    conn.setDoOutput(true);

    try (final OutputStream requestStream = conn.getOutputStream()) {
        final PagerDutyEvent event = buildPagerDutyEvent(stream, checkResult);
        requestStream.write(objectMapper.writeValueAsBytes(event));
        requestStream.flush();

        final InputStream responseStream;
        if (conn.getResponseCode() == 200) {
            responseStream = conn.getInputStream();
        } else {
            responseStream = conn.getErrorStream();
        }

        final PagerDutyResponse response = objectMapper.readValue(responseStream, PagerDutyResponse.class);
        if ("success".equals(response.status)) {
            LOG.debug("Successfully sent event to PagerDuty with incident key {}", response.incidentKey);
        } else {
            LOG.warn("Error while creating event at PagerDuty: {} ({})", response.message, response.errors);
            throw new AlarmCallbackException("Error while creating event at PagerDuty: " + response.message);
        }
    } catch (IOException e) {
        throw new AlarmCallbackException("Could not POST event trigger to PagerDuty API.", e);
    }
}

From source file:net.dv8tion.jda.audio.player.URLPlayer.java

public void setAudioUrl(URL urlOfResource, int bufferSize) throws IOException, UnsupportedAudioFileException {
    if (urlOfResource == null)
        throw new IllegalArgumentException(
                "A null URL was provided to the Player! Cannot find resource to play from a null URL!");

    this.urlOfResource = urlOfResource;
    URLConnection conn = null;//ww w.  j  av  a2s  .  c  o m
    HttpHost jdaProxy = api.getGlobalProxy();
    if (jdaProxy != null) {
        InetSocketAddress proxyAddress = new InetSocketAddress(jdaProxy.getHostName(), jdaProxy.getPort());
        Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyAddress);
        conn = urlOfResource.openConnection(proxy);
    } else {
        conn = urlOfResource.openConnection();
    }
    if (conn == null)
        throw new IllegalArgumentException(
                "The provided URL resulted in a null URLConnection! Does the resource exist?");

    conn.setRequestProperty("user-agent", userAgent);
    this.resourceStream = conn.getInputStream();
    bufferedResourceStream = new BufferedInputStream(resourceStream, bufferSize);
    setAudioSource(AudioSystem.getAudioInputStream(bufferedResourceStream));
}