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:ovh.tgrhavoc.aibot.auth.YggdrasilAuthService.java

private 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.hpe.application.automation.tools.common.rest.RestClient.java

public static URLConnection openConnection(final ProxyInfo proxyInfo, String urlString) throws IOException {
    Proxy proxy = null;/*from   w ww.  j  a va2 s  . c  o  m*/
    URL url = new URL(urlString);

    if (proxyInfo != null && StringUtils.isNotBlank(proxyInfo._host)
            && StringUtils.isNotBlank(proxyInfo._port)) {
        int port = Integer.parseInt(proxyInfo._port.trim());
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyInfo._host, port));
    }

    if (proxy != null && StringUtils.isNotBlank(proxyInfo._userName)
            && StringUtils.isNotBlank(proxyInfo._password)) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyInfo._userName, proxyInfo._password.toCharArray()); //To change body of overridden methods use File | Settings | File Templates.
            }
        };
        Authenticator.setDefault(authenticator);
    }

    if (proxy == null) {
        return url.openConnection();
    }

    return url.openConnection(proxy);
}

From source file:com.machinepublishers.jbrowserdriver.StreamConnectionClient.java

private static Socket newSocket(final HttpContext context) throws IOException {
    InetSocketAddress proxySocks = (InetSocketAddress) context.getAttribute("proxy.socks.address");
    Socket socket;/*from   w  w w .  j a v  a 2  s .c o m*/
    if (proxySocks != null) {
        socket = new Socket(new Proxy(Proxy.Type.SOCKS, proxySocks));
    } else {
        socket = new Socket();
    }
    socket.setTcpNoDelay(true);
    socket.setKeepAlive(true);
    return socket;
}

From source file:org.bremersee.sms.GoyyaSmsService.java

/**
 * Creates the URL connection./*from  w ww  . j a va2s .  co  m*/
 * 
 * @param url
 *            the URL
 * @return the URL connection
 * @throws IOException
 *             if creation of the URL connection fails
 */
protected HttpURLConnection createHttpURLConnection(final String url) throws IOException {

    URL sendUrl = new URL(url);

    HttpURLConnection con = null;

    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null) {

        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        con = (HttpURLConnection) sendUrl.openConnection(proxy);
        if (StringUtils.isNotBlank(proxyUsername)) {
            String passwd = proxyPassword != null ? proxyPassword : "";
            String authValue = proxyUsername + ":" + passwd;
            String headerValue = Base64.encodeBase64String(authValue.getBytes("utf-8"));
            con.setRequestProperty("Proxy-Authorization", "Basic " + headerValue);
        }

    } else {

        con = (HttpURLConnection) sendUrl.openConnection();
    }

    try {
        if (url.toString().toLowerCase().startsWith("https")) {
            HttpsURLConnection secCon = (HttpsURLConnection) con;
            secCon.setHostnameVerifier(createAllHostnamesVerifier());
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, createTrustAllManagers(), new SecureRandom());
            secCon.setSSLSocketFactory(sc.getSocketFactory());
        }

    } catch (NoSuchAlgorithmException e) {
        IOException ise = new IOException(e);
        // log.error("Creating HttpURLConnection failed.", ise);
        throw ise;

    } catch (KeyManagementException e) {
        IOException ise = new IOException(e);
        // log.error("Creating HttpURLConnection failed.", ise);
        throw ise;
    }

    return con;
}

From source file:com.yahoo.sql4d.sql4ddriver.DDataSource.java

/**
 * All commands.//from   www.  j  a  va  2 s.  c om
 * @return 
 */
private Either<String, Either<JSONArray, JSONObject>> fireCommand(String endPoint, String optData,
        String httpType) {
    StringBuilder buff = new StringBuilder();
    try {
        URL url = null;
        try {
            url = new URL(String.format(coordinatorUrl + endPoint, coordinatorHost, coordinatorPort));
        } catch (MalformedURLException ex) {
            Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex);
            return new Left<>("Bad Url : " + ex);
        }
        Proxy proxy = Proxy.NO_PROXY;
        if (proxyHost != null) {
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        }
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection(proxy);
        httpConnection.setRequestMethod(httpType);
        httpConnection.addRequestProperty("content-type", "application/json");
        httpConnection.setDoOutput(true);
        if ("POST".equals(httpType) && optData != null) {
            httpConnection.getOutputStream().write(optData.getBytes());
        }

        if (httpConnection.getResponseCode() == 500 || httpConnection.getResponseCode() == 404) {
            return new Left<>(String.format("Http %d : %s \n", httpConnection.getResponseCode(),
                    httpConnection.getResponseMessage()));
        }

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
        String line = null;
        while ((line = stdInput.readLine()) != null) {
            buff.append(line);
        }
    } catch (IOException ex) {
        Logger.getLogger(DDataSource.class.getName()).log(Level.SEVERE, null, ex);
    }
    JSONArray possibleResArray = null;
    try {
        possibleResArray = new JSONArray(buff.toString());
        return new Right<String, Either<JSONArray, JSONObject>>(
                new Left<JSONArray, JSONObject>(possibleResArray));
    } catch (JSONException je) {
        try {
            JSONObject possibleResObj = new JSONObject(buff.toString());
            return new Right<String, Either<JSONArray, JSONObject>>(
                    new Right<JSONArray, JSONObject>(possibleResObj));
        } catch (JSONException je2) {
            return new Left<>(String.format("Recieved data %s not in json format. \n", buff.toString()));
        }
    }
}

From source file:com.hpe.application.automation.tools.rest.RestClient.java

/**
 * Open http connection//  w w w .j a  v a2  s .c  o  m
 */
public static URLConnection openConnection(final ProxyInfo proxyInfo, String urlString) throws IOException {
    Proxy proxy = null;
    URL url = new URL(urlString);
    if (proxyInfo != null && StringUtils.isNotBlank(proxyInfo._host)
            && StringUtils.isNotBlank(proxyInfo._port)) {
        int port = Integer.parseInt(proxyInfo._port.trim());
        proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyInfo._host, port));
    }
    if (proxy != null && StringUtils.isNotBlank(proxyInfo._userName)
            && StringUtils.isNotBlank(proxyInfo._password)) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(proxyInfo._userName, proxyInfo._password.toCharArray()); //To change body of overridden methods use File | Settings | File Templates.
            }
        };
        Authenticator.setDefault(authenticator);
    }
    if (proxy == null) {
        return url.openConnection();
    }
    return url.openConnection(proxy);
}

From source file:org.eclipse.mylyn.commons.tests.net.WebUtilTest.java

public void testLocationConnectProxy() throws Exception {
    String url = "http://foo/bar";
    final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
    AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
        public Proxy getProxyForHost(String host, String proxyType) {
            return proxy;
        }//w  ww. j a v  a 2s  . c o m
    });
    HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);

    testProxy.addResponse(TestProxy.OK);

    GetMethod method = new GetMethod(WebUtil.getRequestPath(url));
    int statusCode = client.executeMethod(hostConfiguration, method);
    assertEquals(200, statusCode);

    Message request = testProxy.getRequest();
    assertEquals("GET http://foo/bar HTTP/1.1", request.request);
}

From source file:org.eclipse.mylyn.commons.tests.net.WebUtilTest.java

public void testLocationConnectProxyHttpAuth() throws Exception {
    String url = "http://foo/bar";
    final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
    WebLocation location = new WebLocation(url, "", "", new IProxyProvider() {
        public Proxy getProxyForHost(String host, String proxyType) {
            return proxy;
        }/*from w  ww  .ja  va 2  s .  com*/
    });
    location.setCredentials(AuthenticationType.HTTP, "user", "pass");
    HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
    client.getParams().setAuthenticationPreemptive(true);

    Message response = new Message("HTTP/1.1 401 Authentication required");
    response.headers.add("WWW-Authenticate: Basic realm=\"Foo\"");
    testProxy.addResponse(response);
    testProxy.addResponse(TestProxy.OK);

    GetMethod method = new GetMethod(url);
    int statusCode = client.executeMethod(hostConfiguration, method);
    assertEquals(401, statusCode);

    Message request = testProxy.getRequest();
    assertEquals("GET http://foo/bar HTTP/1.1", request.request);
    assertEquals("Basic dXNlcjpwYXNz", request.getHeaderValue("Authorization"));
}

From source file:com.sunchenbin.store.feilong.core.net.URLConnectionUtil.java

/**
 * ?./*  ww  w . j a  v a2 s .c  om*/
 * 
 * @param proxyAddress
 *            the proxy address
 * @param proxyPort
 *            ?? <br>
 *            A valid port value is between 0 ~ 65535. <br>
 *            A port number of zero will let the system pick up an ephemeral port in a bind operation.
 * @return the proxy
 * @see java.net.Proxy.Type.HTTP
 * @see java.net.InetSocketAddress#InetSocketAddress(String, int)
 */
private static Proxy getProxy(String proxyAddress, Integer proxyPort) {
    if (Validator.isNotNullOrEmpty(proxyAddress) && Validator.isNotNullOrEmpty(proxyPort)) {
        SocketAddress socketAddress = new InetSocketAddress(proxyAddress, proxyPort);
        return new Proxy(Proxy.Type.HTTP, socketAddress);
    }
    return null;
}

From source file:org.eclipse.mylyn.commons.tests.net.WebUtilTest.java

public void testLocationConnectProxyNoProxyCredentials() throws Exception {
    String url = "http://foo/bar";
    final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
    AbstractWebLocation location = new WebLocation(url, "user", "pass", new IProxyProvider() {
        public Proxy getProxyForHost(String host, String proxyType) {
            return proxy;
        }//from ww w.  ja v a2s  . c  om
    });
    HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);

    Message response = new Message("HTTP/1.1 407 Proxy authentication required");
    response.headers.add("Proxy-Authenticate: Basic realm=\"Foo\"");
    testProxy.addResponse(response);
    testProxy.addResponse(TestProxy.OK);

    GetMethod method = new GetMethod(url);
    int statusCode = client.executeMethod(hostConfiguration, method);
    assertEquals(407, statusCode);

    Message request = testProxy.getRequest();
    assertEquals("GET http://foo/bar HTTP/1.1", request.request);

    assertFalse("Expected HttpClient to close connection", testProxy.hasRequest());
}