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:youtube.transcription.Video.java

public void setProxy(String hostAddress, int port) { // Create Proxy for the current Video object
    proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(hostAddress, port));
}

From source file:io.github.bonigarcia.wdm.WdmHttpClient.java

Proxy createProxy(String proxyUrl) {
    URL url = determineProxyUrl(proxyUrl);
    if (url == null) {
        return null;
    }//from  www .j ava2s . c  o  m
    String proxyHost = url.getHost();
    int proxyPort = url.getPort() == -1 ? 80 : url.getPort();
    return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
}

From source file:org.sakaiproject.contentreview.compilatio.CompilatioAccountConnection.java

public void init() {

    log.info("init()");

    proxyHost = serverConfigurationService.getString("compilatio.proxyHost");

    proxyPort = serverConfigurationService.getString("compilatio.proxyPort");

    if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyPort)) {
        try {//from   w  w w. j a  v  a2  s.  co m
            SocketAddress addr = new InetSocketAddress(proxyHost, new Integer(proxyPort).intValue());
            proxy = new Proxy(Proxy.Type.HTTP, addr);
            log.debug("Using proxy: " + proxyHost + " " + proxyPort);
        } catch (NumberFormatException e) {
            log.debug("Invalid proxy port specified: " + proxyPort);
        }
    } else if (StringUtils.isNotBlank(System.getProperty("http.proxyHost"))) {
        try {
            SocketAddress addr = new InetSocketAddress(System.getProperty("http.proxyHost"),
                    new Integer(System.getProperty("http.proxyPort")).intValue());
            proxy = new Proxy(Proxy.Type.HTTP, addr);
            log.debug("Using proxy: " + System.getProperty("http.proxyHost") + " "
                    + System.getProperty("http.proxyPort"));
        } catch (NumberFormatException e) {
            log.debug("Invalid proxy port specified: " + System.getProperty("http.proxyPort"));
        }
    }

    secretKey = serverConfigurationService.getString("compilatio.secretKey");

    apiURL = serverConfigurationService.getString("compilatio.apiURL", DEFAULT_API_URL);

    // Timeout period in ms for network connections (default 180s). Set to 0 to disable timeout.
    compilatioConnTimeout = serverConfigurationService.getInt("compilatio.networkTimeout", DEFAULT_TIMEOUT);

}

From source file:org.emonocot.portal.http.StaticUsernameAndPasswordHttpClientFactory.java

/**
 * @param uri Set the uri/*from  w  w  w .ja  va  2s  .co  m*/
 * @param httpMethod set the httpMethod
 * @return a client http request object
 * @throws IOException if there is a problem
 */
public final ClientHttpRequest createRequest(final URI uri, final HttpMethod httpMethod) throws IOException {
    if (proxyHost != null && proxyPort != null) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        super.setProxy(proxy);
    }
    ClientHttpRequest clientHttpRequest = super.createRequest(uri, httpMethod);
    String unencoded = username + ":" + password;
    String encoded = new String(Base64.encodeBase64(unencoded.getBytes()));
    clientHttpRequest.getHeaders().add("Authorization", "Basic " + encoded);

    return clientHttpRequest;
}

From source file:org.wso2.extension.siddhi.device.utils.ClientUtils.java

public static OkHttpClient getSSLClient() {

    boolean isIgnoreHostnameVerification = Boolean
            .parseBoolean(System.getProperty("org.wso2" + ".ignoreHostnameVerification"));
    OkHttpClient okHttpClient;//from w  ww  . j a  v a2 s . com
    final String proxyHost = System.getProperty("http.proxyHost");
    final String proxyPort = System.getProperty("http.proxyPort");
    final String nonProxyHostsValue = System.getProperty("http.nonProxyHosts");

    final ProxySelector proxySelector = new ProxySelector() {
        @Override
        public List<Proxy> select(URI uri) {
            List<Proxy> proxyList = new ArrayList<>();
            String host = uri.getHost();

            if (!StringUtils.isEmpty(host)) {
                if (host.startsWith(DEFAULT_HOST_IP) || host.startsWith(DEFAULT_HOST)
                        || StringUtils.isEmpty(nonProxyHostsValue)
                        || StringUtils.contains(nonProxyHostsValue, host) || StringUtils.isEmpty(proxyHost)
                        || StringUtils.isEmpty(proxyPort)) {
                    proxyList.add(Proxy.NO_PROXY);
                } else {
                    proxyList.add(new Proxy(Proxy.Type.HTTP,
                            new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort))));
                }
            } else {
                log.error("Host is null. Host could not be empty or null");
            }
            return proxyList;
        }

        @Override
        public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
            throw new UnsupportedOperationException("Not supported yet.");
        }
    };

    X509TrustManager trustAllCerts = new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[0];
        }

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

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    };
    if (isIgnoreHostnameVerification) {
        okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(getSimpleTrustedSSLSocketFactory(), trustAllCerts)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }).proxySelector(proxySelector).build();
        return okHttpClient;
    } else {
        SSLSocketFactory trustedSSLSocketFactory = getTrustedSSLSocketFactory();
        okHttpClient = new OkHttpClient.Builder().sslSocketFactory(trustedSSLSocketFactory)
                .proxySelector(proxySelector).build();
        return okHttpClient;
    }
}

From source file:com.sap.wec.adtreco.be.ODataClientService.java

private HttpURLConnection initializeConnection(final String absoluteUri, final String contentType,
        final String httpMethod) {
    LOG.info("Initialize connection for URL: " + absoluteUri);
    HttpURLConnection connection = null;
    try {/*ww w .  j  a  v  a  2s .  c  om*/
        final URL url = new URL(absoluteUri);
        if (getProxyHost() != null) {
            final Proxy proxy = new Proxy(Proxy.Type.HTTP,
                    new InetSocketAddress(getProxyHost(), getProxyPort()));
            connection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            connection = (HttpURLConnection) url.openConnection();
        }
        connection.setRequestProperty(HTTP_HEADER_ACCEPT, contentType);
        connection.setRequestMethod(httpMethod);
        connection.setConnectTimeout(CONNECTION_TIMEOUT);
        connection.setReadTimeout(READ_TIMEOUT_RT);
    } catch (final IOException IOe) {
        (new Exception("Error initializing connection to CEI: " + absoluteUri, IOe)).printStackTrace();
    }

    if (HTTP_METHOD_POST.equals(httpMethod) || HTTP_METHOD_PUT.equals(httpMethod)) {
        connection.setDoOutput(true);
        connection.setRequestProperty(HTTP_HEADER_CONTENT_TYPE, contentType);
    }

    if (this.user != null) {
        String authorization = "Basic ";
        authorization += new String(Base64.encodeBase64((this.user + ":" + this.password).getBytes()));
        connection.setRequestProperty("Authorization", authorization);
    }
    LOG.info("End of initialize connection");
    return connection;
}

From source file:org.messic.server.api.tagwizard.discogs.DiscogsTAGWizardPlugin.java

private Proxy getProxy() {
    if (this.configuration != null) {
        String url = (String) this.configuration.get("proxy-url");
        String port = (String) this.configuration.get("proxy-port");
        if (url != null && port != null && url.length() > 0 && port.length() > 0) {
            SocketAddress addr = new InetSocketAddress(url, Integer.valueOf(port));
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
            return proxy;
        }/*from ww w . j  a v  a  2 s. c  o  m*/
    }
    return null;
}

From source file:org.okj.im.core.service.QQHttpService.java

/**
 * HTTP//w  w w  .  j  ava2 s. co  m
 * @param url
 * @param method
 * @param exParam
 * @return
 */
protected HttpURLConnection connect(String url, String method, ExParam exParam) {
    HttpURLConnection conn = null;
    try {
        URL serverUrl = new URL(url);
        if (proxyHost != null && proxyPort != null && !"".equals(proxyHost)) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            conn = (HttpURLConnection) serverUrl.openConnection(proxy);
        } else {
            conn = (HttpURLConnection) serverUrl.openConnection();
        }
        conn.setConnectTimeout(60000);
        conn.setReadTimeout(100000);
        System.setProperty("sun.net.client.defaultConnectTimeout", "60000");
        System.setProperty("sun.net.client.defaultReadTimeout", "100000");
        conn.setRequestMethod(method);// "POST" ,"GET"
        conn.addRequestProperty("Referer", refer);
        conn.addRequestProperty("Cookie", exParam.getCookie());
        conn.addRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Accept-Language", "zh-cn");
        conn.addRequestProperty("Accept-Encoding", "gzip, deflate");
        conn.addRequestProperty("Cache-Control", "no-cache");
        conn.addRequestProperty("Accept-Charset", "UTF-8;");
        conn.addRequestProperty("Host", "d.web2.qq.com");
        conn.addRequestProperty("User-Agent",
                "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.168 Chrome/18.0.1025.168 Safari/535.19");
        if (StringUtils.equalsIgnoreCase(method, HttpMethod.GET)) {
            conn.setDoInput(true);
            conn.connect();
        } else if (StringUtils.equalsIgnoreCase(method, HttpMethod.POST)) {
            conn.setDoInput(true);
            conn.setDoOutput(true);
            if (StringUtils.isNotBlank(exParam.getFilename())) {
                conn.setRequestProperty("Content-Type", "multipart/form-data");
            }
            conn.connect();
            if (StringUtils.isNotBlank(exParam.getContents())) {
                conn.getOutputStream().write(exParam.getContents().getBytes());
            }
            //
            if (StringUtils.isNotBlank(exParam.getFilename())) {
                uploadFile(exParam.getFilename(), conn.getOutputStream());
                LogUtils.info(LOGGER, "?, filename={0}", exParam.getFilename());
            }
        } else {
            LogUtils.warn(LOGGER, "your method is not implement");
            //throw new RuntimeException("your method is not implement");
        }
    } catch (Exception ex) {
        LogUtils.error(LOGGER, "httpclient?", ex);
    }
    return conn;
}

From source file:si.mazi.rescu.HttpTemplate.java

/**
 * Constructor//from   w ww.j  a v  a2s .com
 */
public HttpTemplate() {
    objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    // Always use UTF8
    defaultHttpHeaders.put("Accept-Charset", CHARSET_UTF_8);
    // Assume form encoding by default (typically becomes application/json or application/xml)
    defaultHttpHeaders.put("Content-Type", "application/x-www-form-urlencoded");
    // Accept text/plain by default (typically becomes application/json or application/xml)
    defaultHttpHeaders.put("Accept", "text/plain");
    // User agent provides statistics for servers, but some use it for content negotiation so fake good agents
    defaultHttpHeaders.put("User-Agent", "ResCU JDK/6 AppleWebKit/535.7 Chrome/16.0.912.36 Safari/535.7"); // custom User-Agent

    if (Config.getProxyPort() == null || Config.getProxyHost() == null) {
        proxy = Proxy.NO_PROXY;
    } else {
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(Config.getProxyHost(), Config.getProxyPort()));
        log.info("Using proxy {}", proxy);
    }
}

From source file:org.owasp.jbrofuzz.update.StartUpdateChecker.java

/**
 * <p>/*from   w  w w .j  a va2  s  . c  o m*/
 * Static method for getting the current online version of JBroFuzz.
 * </p>
 * 
 * <p>
 * This method makes a connection to the OWASP web site, checking for the
 * latest version number.
 * </p>
 * 
 * @return double of the version or 0.0 in case of an error
 * 
 * @author subere@uncon.org
 * @version 2.5
 * @since 1.3
 */
private static double getWebsiteVersion() {

    String response = "";
    BufferedReader instream = null;

    try {

        final URL url = new URL(JBroFuzzFormat.URL_WEBSITE);
        final URLConnection urlc;

        final boolean proxyEnabled = JBroFuzz.PREFS.getBoolean(JBroFuzzPrefs.UPDATE[0].getId(), false);
        if (proxyEnabled) {

            final String proxy = JBroFuzz.PREFS.get(JBroFuzzPrefs.UPDATE[1].getId(), "");
            final int port = JBroFuzz.PREFS.getInt(JBroFuzzPrefs.UPDATE[2].getId(), -1);
            // A note here, proxy has no http:// or https://
            Proxy myProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy, port));
            urlc = url.openConnection(myProxy);
            // Username:Password, yawn

            final boolean proxyReqAuth = JBroFuzz.PREFS.getBoolean(JBroFuzzPrefs.UPDATE[3].getId(), false);
            if (proxyReqAuth) {

                final String user = JBroFuzz.PREFS.get(JBroFuzzPrefs.UPDATE[5].getId(), "");
                final String pass = JBroFuzz.PREFS.get(JBroFuzzPrefs.UPDATE[6].getId(), "");
                final String encodedPassword = EncoderHashCore.encode(user + ":" + pass, "Base64");
                urlc.setRequestProperty("Proxy-Authorization", "Basic " + encodedPassword);
            }

        } else {

            urlc = url.openConnection();

        }
        urlc.setRequestProperty("User-Agent", "JBroFuzz/" + JBroFuzzFormat.VERSION);

        final int statusCode = ((HttpURLConnection) urlc).getResponseCode();

        if (statusCode == HttpURLConnection.HTTP_OK) {

            instream = new BufferedReader(new InputStreamReader(urlc.getInputStream()));

            // Typically returns -1
            final long contentLength = urlc.getContentLength();

            if (contentLength > Integer.MAX_VALUE) {
                return ZERO_VERSION;
            }

            int count;
            int limit = 0;
            final StringBuffer body = new StringBuffer(Character.MAX_VALUE);
            // 
            while (((count = instream.read()) != -1) && (limit < Character.MAX_VALUE)) {
                body.append((char) count);
                limit++;
            }
            instream.close();

            response = body.toString();

        } else {
            return ZERO_VERSION;
        } // else statement for a 200 response

    } catch (final IOException e) {
        return ZERO_VERSION;
    } finally {
        IOUtils.closeQuietly(instream);
    }

    if (!response.equalsIgnoreCase("")) {

        final Pattern pattern1 = Pattern.compile("Current version is (\\d.\\d)");
        final Matcher match1 = pattern1.matcher(response);
        if (match1.find()) {
            final String webVersion = match1.group().substring(19, 22);

            try {
                // Return the value, if found
                return Double.parseDouble(webVersion);

            } catch (final NumberFormatException e) {
                // Return 0.0 if an error occurs
                return ZERO_VERSION;

            }

        } else {
            return ZERO_VERSION;
        }
    }
    return ZERO_VERSION;
}