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:org.sonarsource.sonarlint.core.util.ws.HttpConnectorTest.java

@Test
public void use_proxy_authentication() throws Exception {
    MockWebServer proxy = new MockWebServer();
    proxy.start();/*from w w w.j  av  a  2  s.  c o  m*/

    underTest = HttpConnector.newBuilder().url(serverUrl)
            .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHostName(), proxy.getPort())))
            .proxyCredentials("theProxyLogin", "theProxyPassword").build();

    GetRequest request = new GetRequest("api/issues/search");
    proxy.enqueue(new MockResponse().setResponseCode(407));
    proxy.enqueue(new MockResponse().setBody("OK!"));
    underTest.call(request);

    RecordedRequest recordedRequest = proxy.takeRequest();
    assertThat(recordedRequest.getHeader("Proxy-Authorization")).isNull();
    recordedRequest = proxy.takeRequest();
    assertThat(recordedRequest.getHeader("Proxy-Authorization"))
            .isEqualTo(basic("theProxyLogin", "theProxyPassword"));
}

From source file:com.bazaarvoice.seo.sdk.BVUIContentServiceProvider.java

private String loadContentFromHttp(URI path) {
    int connectionTimeout = Integer
            .parseInt(_bvConfiguration.getProperty(BVClientConfig.CONNECT_TIMEOUT.getPropertyName()));
    int socketTimeout = Integer
            .parseInt(_bvConfiguration.getProperty(BVClientConfig.SOCKET_TIMEOUT.getPropertyName()));
    String proxyHost = _bvConfiguration.getProperty(BVClientConfig.PROXY_HOST.getPropertyName());
    String charsetConfig = _bvConfiguration.getProperty(BVClientConfig.CHARSET.getPropertyName());
    Charset charset = null;//from  www .  j av  a  2  s.  c  om
    try {
        charset = charsetConfig == null ? Charset.defaultCharset() : Charset.forName(charsetConfig);
    } catch (Exception e) {
        _logger.error(BVMessageUtil.getMessage("ERR0024"));
        charset = Charset.defaultCharset();
    }

    String content = null;
    try {
        HttpURLConnection httpUrlConnection = null;
        URL url = path.toURL();

        if (!StringUtils.isBlank(proxyHost) && !"none".equalsIgnoreCase(proxyHost)) {
            int proxyPort = Integer
                    .parseInt(_bvConfiguration.getProperty(BVClientConfig.PROXY_PORT.getPropertyName()));
            SocketAddress socketAddress = new InetSocketAddress(proxyHost, proxyPort);
            Proxy proxy = new Proxy(Type.HTTP, socketAddress);
            httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
        } else {
            httpUrlConnection = (HttpURLConnection) url.openConnection();
        }

        httpUrlConnection.setConnectTimeout(connectionTimeout);
        httpUrlConnection.setReadTimeout(socketTimeout);

        InputStream is = httpUrlConnection.getInputStream();

        byte[] byteArray = IOUtils.toByteArray(is);
        is.close();

        if (byteArray == null) {
            throw new BVSdkException("ERR0025");
        }

        content = new String(byteArray, charset.name());
    } catch (MalformedURLException e) {
        //           e.printStackTrace();
    } catch (IOException e) {
        //           e.printStackTrace();
        if (e instanceof SocketTimeoutException) {
            throw new BVSdkException(e.getMessage());
        } else {
            throw new BVSdkException("ERR0012");
        }
    } catch (BVSdkException bve) {
        throw bve;
    }

    boolean isValidContent = BVUtilty.validateBVContent(content);
    if (!isValidContent) {
        throw new BVSdkException("ERR0025");
    }

    return content;
}

From source file:com.novartis.opensource.yada.adaptor.RESTAdaptor.java

/**
 * Gets the input stream from the {@link URLConnection} and stores it in 
 * the {@link YADAQueryResult} in {@code yq}
 * @see com.novartis.opensource.yada.adaptor.Adaptor#execute(com.novartis.opensource.yada.YADAQuery)
 */// w  w  w.jav  a 2s  . c  o  m
@Override
public void execute(YADAQuery yq) throws YADAAdaptorExecutionException {
    boolean isPostPutPatch = this.method.equals(YADARequest.METHOD_POST)
            || this.method.equals(YADARequest.METHOD_PUT) || this.method.equals(YADARequest.METHOD_PATCH);
    resetCountParameter(yq);
    int rows = yq.getData().size() > 0 ? yq.getData().size() : 1;
    /*
     * Remember:
     * A row is an set of YADA URL parameter values, e.g.,
     * 
     *  x,y,z in this:      
     *    ...yada/q/queryname/p/x,y,z
     *  so 1 row
     *    
     *  or each of {col1:x,col2:y,col3:z} and {col1:a,col2:b,col3:c} in this:
     *    ...j=[{qname:queryname,DATA:[{col1:x,col2:y,col3:z},{col1:a,col2:b,col3:c}]}]
     *  so 2 rows
     */
    for (int row = 0; row < rows; row++) {
        String result = "";

        // creates result array and assigns it
        yq.setResult();
        YADAQueryResult yqr = yq.getResult();

        String urlStr = yq.getUrl(row);

        for (int i = 0; i < yq.getParamCount(row); i++) {
            Matcher m = PARAM_URL_RX.matcher(urlStr);
            if (m.matches()) {
                String param = yq.getVals(row).get(i);
                urlStr = urlStr.replaceFirst(PARAM_SYMBOL_RX, m.group(1) + param);
            }
        }

        l.debug("REST url w/params: [" + urlStr + "]");
        try {
            URL url = new URL(urlStr);
            URLConnection conn = null;

            if (this.hasProxy()) {
                String[] proxyStr = this.proxy.split(":");
                Proxy proxySvr = new Proxy(Proxy.Type.HTTP,
                        new InetSocketAddress(proxyStr[0], Integer.parseInt(proxyStr[1])));
                conn = url.openConnection(proxySvr);
            } else {
                conn = url.openConnection();
            }

            // basic auth
            if (url.getUserInfo() != null) {
                //TODO issue with '@' sign in pw, must decode first
                String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
                conn.setRequestProperty("Authorization", basicAuth);
            }

            // cookies
            if (yq.getCookies() != null && yq.getCookies().size() > 0) {
                String cookieStr = "";
                for (HttpCookie cookie : yq.getCookies()) {
                    cookieStr += cookie.getName() + "=" + cookie.getValue() + ";";
                }
                conn.setRequestProperty("Cookie", cookieStr);
            }

            if (yq.getHttpHeaders() != null && yq.getHttpHeaders().length() > 0) {
                l.debug("Processing custom headers...");
                @SuppressWarnings("unchecked")
                Iterator<String> keys = yq.getHttpHeaders().keys();
                while (keys.hasNext()) {
                    String name = keys.next();
                    String value = yq.getHttpHeaders().getString(name);
                    l.debug("Custom header: " + name + " : " + value);
                    conn.setRequestProperty(name, value);
                    if (name.equals(X_HTTP_METHOD_OVERRIDE) && value.equals(YADARequest.METHOD_PATCH)) {
                        l.debug("Resetting method to [" + YADARequest.METHOD_POST + "]");
                        this.method = YADARequest.METHOD_POST;
                    }
                }
            }

            HttpURLConnection hConn = (HttpURLConnection) conn;
            if (!this.method.equals(YADARequest.METHOD_GET)) {
                hConn.setRequestMethod(this.method);
                if (isPostPutPatch) {
                    //TODO make YADA_PAYLOAD case-insensitive and create an alias for it, e.g., ypl
                    // NOTE: YADA_PAYLOAD is a COLUMN NAME found in a JSONParams DATA object.  It 
                    //       is not a YADA param
                    String payload = yq.getDataRow(row).get(YADA_PAYLOAD)[0];
                    hConn.setDoOutput(true);
                    OutputStreamWriter writer;
                    writer = new OutputStreamWriter(conn.getOutputStream());
                    writer.write(payload.toString());
                    writer.flush();
                }
            }

            // debug
            Map<String, List<String>> map = conn.getHeaderFields();
            for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                l.debug("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
            }

            try (BufferedReader in = new BufferedReader(new InputStreamReader(hConn.getInputStream()))) {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    result += String.format("%1s%n", inputLine);
                }
            }
            yqr.addResult(row, result);
        } catch (MalformedURLException e) {
            String msg = "Unable to access REST source due to a URL issue.";
            throw new YADAAdaptorExecutionException(msg, e);
        } catch (IOException e) {
            String msg = "Unable to read REST response.";
            throw new YADAAdaptorExecutionException(msg, e);
        }
    }
}

From source file:com.msopentech.thali.CouchDBListener.ThaliListener.java

/**
 * Starts the server on a new thread using a key and database files recorded in the specified directory and listening on
 * the specified port./*from ww w .j  a va  2 s .  com*/
 * @param context
 * @param port
 * @param onionProxyManager
 */
public void startServer(final Context context, final int port, final OnionProxyManager onionProxyManager)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    this.onionProxyManager = onionProxyManager;
    serverStarted = true;
    if (context == null) {
        throw new RuntimeException();
    }

    final KeyStore finalClientKeyStore = ThaliCryptoUtilities
            .getThaliKeyStoreByAnyMeansNecessary(context.getFilesDir());
    serverPublicKey = ThaliCryptoUtilities.getAppKeyFromKeyStore(finalClientKeyStore);

    new Thread(new Runnable() {
        public void run() {
            // First start the Tor listener so we know what SOCKS proxy port we are listening on
            try {
                if (onionProxyManager.startWithRepeat(120, 5) == false) {
                    Log.e(CblLogTags.TAG_THALI_LISTENER, "Could not start Onion Proxy Manager!");
                    stopServer();
                }
                onionProxyManager.enableNetwork(true);
                socksProxy = new Proxy(Proxy.Type.SOCKS,
                        new InetSocketAddress("127.0.0.1", onionProxyManager.getIPv4LocalHostSocksPort()));

                Log.i(CblLogTags.TAG_THALI_LISTENER,
                        "Socks port for TOR is " + onionProxyManager.getIPv4LocalHostSocksPort());

                // Now we can configure the listener with the proxy to use to talk to SOCKS
                if (configureManagerObjectForListener(finalClientKeyStore, socksProxy, context)) {
                    configureListener(context, port);
                }

                // Now we can configure the hidden service because we know what local port the listener is using
                String onionDomainName = onionProxyManager.publishHiddenService(DefaultThaliDeviceHubPort,
                        getSocketStatus().getPort());
                hiddenServiceAddress = new HttpKeyURL(serverPublicKey, onionDomainName,
                        DefaultThaliDeviceHubPort, null, null, null);

                ObjectMapper mapper = new ObjectMapper();
                Log.i(CblLogTags.TAG_THALI_LISTENER,
                        "Tor Http Key Values: " + mapper.writeValueAsString(buildHttpKeys()));
            } catch (InterruptedException e) {
                Log.e(CblLogTags.TAG_THALI_LISTENER, "Could not start TOR Onion Proxy", e);
            } catch (IOException e) {
                Log.e(CblLogTags.TAG_THALI_LISTENER, "Could not start TOR Onion Proxy", e);
            }
        }
    }).start();

    try {
        // Can't do this in Android because it would be on the main thread and caused an AndroidBlockGuardPolicy.onNetwork
        // If we ever care we can always just run it on a separate thread but it doesn't seem worth it.
        if (OsData.getOsType() != OsData.OsType.Android) {
            Log.w(CblLogTags.TAG_THALI_LISTENER,
                    "Local address is: " + getHttpKeys().getLocalMachineIPHttpKeyURL());
        }
    } catch (InterruptedException e) {
        Log.e(CblLogTags.TAG_THALI_LISTENER, "Failed trying to log address", e);
    } catch (UnknownHostException e) {
        Log.e(CblLogTags.TAG_THALI_LISTENER, "Failed trying to log address", e);
    } catch (IOException e) {
        Log.e(CblLogTags.TAG_THALI_LISTENER, "Failed trying to log address", e);
    }
}

From source file:jetbrains.buildServer.clouds.azure.arm.connector.AzureApiConnectorImpl.java

/**
 * Configures http proxy settings./*from  w w w  .j a v a2  s.  co  m*/
 *
 * @param builder is a http builder.
 */
private static void configureProxy(@NotNull final OkHttpClient.Builder builder) {
    // Set HTTP proxy
    final String httpProxyHost = TeamCityProperties.getProperty(HTTP_PROXY_HOST);
    final int httpProxyPort = TeamCityProperties.getInteger(HTTP_PROXY_PORT, 80);
    if (!StringUtil.isEmpty(httpProxyHost)) {
        builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpProxyHost, httpProxyPort)));
    }

    // Set HTTPS proxy
    final String httpsProxyHost = TeamCityProperties.getProperty(HTTPS_PROXY_HOST);
    final int httpsProxyPort = TeamCityProperties.getInteger(HTTPS_PROXY_PORT, 443);
    if (!StringUtil.isEmpty(httpsProxyHost)) {
        builder.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(httpsProxyHost, httpsProxyPort)));
    }

    // Set proxy authentication
    final String httpProxyUser = TeamCityProperties.getProperty(HTTP_PROXY_USER);
    final String httpProxyPassword = TeamCityProperties.getProperty(HTTP_PROXY_PASSWORD);
    if (!StringUtil.isEmpty(httpProxyUser)) {
        builder.proxyAuthenticator(new CredentialsAuthenticator(httpProxyUser, httpProxyPassword));
    }
}

From source file:org.kawanfw.sql.api.client.RemoteDriverUtil.java

/**
 * Create a Proxy instance from a Proxy.toString() representation 
 * Example: HTTP @ www.kawansoft.com/195.154.226.82:8080
 * @param proxyToString   the proxy in Proxy.toString() format
 * @return the build proxy//from   w  ww  .j  ava2  s  .c om
 */

public static Proxy buildProxy(String proxyToString) {
    if (proxyToString == null) {
        throw new NullPointerException("ip is null!");
    }

    if (!proxyToString.contains(" @ ")) {
        throw new IllegalArgumentException("Malformed Proxy.toString() format: @ separator is missing.");
    }

    // Get the type
    String type = StringUtils.substringBefore(proxyToString, " @ ");
    if (type == null) {
        throw new IllegalArgumentException("Malformed Proxy.toString() format: no Type");
    }

    type = type.trim();

    debug("Proxy.Type.DIRECT: " + Proxy.Type.DIRECT.toString());

    if (!type.equals(Proxy.Type.DIRECT.toString()) && !type.equals(Proxy.Type.HTTP.toString())
            && !type.equals(Proxy.Type.SOCKS.toString())) {
        throw new IllegalArgumentException(
                "Malformed Proxy.toString() format: Type does not contain DIRECT / HTTP / SOCKS: " + type
                        + ":");
    }

    String hostname = null;
    String portStr = null;
    int port = 0;

    if (proxyToString.contains("@ /")) {
        // Case 1 : HTTP @ /195.154.226.82:8080
        // no hostname IP only
        hostname = StringUtils.substringBetween(proxyToString, "/", ":");
    } else {
        // Case 2 : HTTP @ localhost/127.0.0.1:8080
        // hostname followed by ip or /subaddress
        hostname = StringUtils.substringBetween(proxyToString, " @ ", "/");
        String ip = StringUtils.substringBetween(proxyToString, "/", ":");

        // if ip string is in IP format, dont take in account the ip after /
        // If not, following / is the hostname
        if (validateIpFormat(ip)) {
            hostname = StringUtils.substringBetween(proxyToString, " @ ", "/");
        } else {
            hostname = StringUtils.substringBetween(proxyToString, " @ ", ":");
        }

    }

    portStr = StringUtils.substringAfter(proxyToString, ":");

    if (StringUtils.isNumeric(portStr)) {
        port = Integer.parseInt(portStr);
    } else {
        throw new IllegalArgumentException(
                "Malformed Proxy.toString() format: does not contain numeric port: " + proxyToString);
    }

    Proxy proxy = new Proxy(Type.valueOf(type), new InetSocketAddress(hostname, port));
    return proxy;
}

From source file:cc.arduino.net.CustomProxySelector.java

private Proxy manualProxy() {
    setAuthenticator(preferences.get(Constants.PREF_PROXY_MANUAL_USERNAME),
            preferences.get(Constants.PREF_PROXY_MANUAL_PASSWORD));
    Proxy.Type type = Proxy.Type.valueOf(preferences.get(Constants.PREF_PROXY_MANUAL_TYPE));
    return new Proxy(type, new InetSocketAddress(preferences.get(Constants.PREF_PROXY_MANUAL_HOSTNAME),
            Integer.valueOf(preferences.get(Constants.PREF_PROXY_MANUAL_PORT))));
}

From source file:com.ericsson.eiffel.remrem.semantics.clone.PrepareLocalEiffelSchemas.java

/**
 * This method is used get the proxy instance by using user provided proxy details
 * // w ww  . j a  va2 s  .co m
 * @param httpProxyUrl proxy url configured in property file
 * @param httpProxyPort proxy port configured in property file
 * @param httpProxyUsername proxy username to authenticate
 * @param httpProxyPassword proxy password to authenticate
 * @return proxy instance
 */
private Proxy getProxy(final String httpProxyUrl, final String httpProxyPort, final String httpProxyUsername,
        final String httpProxyPassword) {
    if (!httpProxyUrl.isEmpty() && !httpProxyPort.isEmpty()) {
        final InetSocketAddress socket = InetSocketAddress.createUnresolved(httpProxyUrl,
                Integer.parseInt(httpProxyPort));
        if (!httpProxyUsername.isEmpty() && !httpProxyPassword.isEmpty()) {
            Authenticator authenticator = new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    LOGGER.info("proxy authentication called");
                    return (new PasswordAuthentication(httpProxyUsername, httpProxyPassword.toCharArray()));
                }
            };
            Authenticator.setDefault(authenticator);
        }
        return new Proxy(Proxy.Type.HTTP, socket);
    }
    return null;
}

From source file:org.jmxtrans.embedded.output.LibratoWriter.java

/**
 * Load settings//from w ww .j  a  va2  s  .c o  m
 */
@Override
public void start() {
    try {
        url = new URL(getStringSetting(SETTING_URL, DEFAULT_LIBRATO_API_URL));

        user = getStringSetting(SETTING_USERNAME);
        token = getStringSetting(SETTING_TOKEN);
        basicAuthentication = Base64Variants.getDefaultVariant()
                .encode((user + ":" + token).getBytes(Charset.forName("US-ASCII")));

        if (getStringSetting(SETTING_PROXY_HOST, null) != null
                && !getStringSetting(SETTING_PROXY_HOST).isEmpty()) {
            proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getStringSetting(SETTING_PROXY_HOST),
                    getIntSetting(SETTING_PROXY_PORT)));
        }

        libratoApiTimeoutInMillis = getIntSetting(SETTING_LIBRATO_API_TIMEOUT_IN_MILLIS,
                DEFAULT_LIBRATO_API_TIMEOUT_IN_MILLIS);

        source = getStringSetting(SETTING_SOURCE, DEFAULT_SOURCE);
        source = getStrategy().resolveExpression(source);

        logger.info("Start Librato writer connected to '{}', proxy {} with user '{}' ...", url, proxy, user);
    } catch (MalformedURLException e) {
        throw new EmbeddedJmxTransException(e);
    }
}

From source file:org.apache.olingo.odata2.fit.client.util.Client.java

private HttpURLConnection connect(final String absoluteUri, final String contentType, final String httpMethod)
        throws IOException, HttpException {
    URL url = new URL(absoluteUri);
    HttpURLConnection connection;
    if (useProxy) {
        Proxy proxy = new Proxy(protocol, new InetSocketAddress(this.proxy, port));
        connection = (HttpURLConnection) url.openConnection(proxy);
    } else {/*from w  w  w. j a  v  a  2 s .  co  m*/
        connection = (HttpURLConnection) url.openConnection();
    }
    connection.setRequestMethod(httpMethod);
    connection.setRequestProperty("Accept", contentType);

    if (useAuthentication) {
        String authorization = "Basic ";
        authorization += new String(Base64.encodeBase64((username + ":" + password).getBytes()));
        connection.setRequestProperty("Authorization", authorization);
    }

    connection.connect();

    checkStatus(connection);

    return connection;
}