Example usage for java.net Proxy address

List of usage examples for java.net Proxy address

Introduction

In this page you can find the example usage for java.net Proxy address.

Prototype

public SocketAddress address() 

Source Link

Document

Returns the socket address of the proxy, or null if its a direct connection.

Usage

From source file:org.jenkinsci.plugins.bitbucketNotifier.BitbucketNotifier.java

/**
 * Returns the HttpClient through which the REST call is made. Uses an
 * unsafe TrustStrategy in case the user specified a HTTPS URL and
 * set the ignoreUnverifiedSSLPeer flag.
 *
 * @param logger    the logger to log messages to
 * @param build//from  w w  w  .j av  a 2  s . c  o  m
 * @return         the HttpClient
 */
private HttpClient getHttpClient(PrintStream logger, AbstractBuild<?, ?> build) throws Exception {
    boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
    String bitbucketServer = bitbucketServerBaseUrl;
    DescriptorImpl descriptor = getDescriptor();

    // Determine if we are using the local or global settings
    String credentialsId = getCredentialsId();
    if (StringUtils.isBlank(credentialsId)) {
        credentialsId = descriptor.getCredentialsId();
    }

    Credentials credentials = CredentialsMatchers.firstOrNull(CredentialsProvider
            .lookupCredentials(CertificateCredentials.class, Jenkins.getInstance(), ACL.SYSTEM),
            CredentialsMatchers.withId(credentialsId));

    if ("".equals(bitbucketServer) || bitbucketServer == null) {
        bitbucketServer = descriptor.getBitbucketRootUrl();
    }
    if (!ignoreUnverifiedSSL) {
        ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl();
    }

    URL url = new URL(bitbucketServer);
    HttpClientBuilder builder = HttpClientBuilder.create();
    if (url.getProtocol().equals("https")
            && (ignoreUnverifiedSSL || credentials instanceof CertificateCredentials)) {
        // add unsafe trust manager to avoid thrown
        // SSLPeerUnverifiedException
        try {
            SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(
                    buildSslContext(ignoreUnverifiedSSL, credentials),
                    ignoreUnverifiedSSL ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : null);
            builder.setSSLSocketFactory(sslConnSocketFactory);

            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnSocketFactory).build();

            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);

            builder.setConnectionManager(ccm);
        } catch (NoSuchAlgorithmException nsae) {
            logger.println("Couldn't establish SSL context:");
            nsae.printStackTrace(logger);
        } catch (KeyManagementException kme) {
            logger.println("Couldn't initialize SSL context:");
            kme.printStackTrace(logger);
        } catch (KeyStoreException kse) {
            logger.println("Couldn't initialize SSL context:");
            kse.printStackTrace(logger);
        }
    }

    // Configure the proxy, if needed
    // Using the Jenkins methods handles the noProxyHost settings
    ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
    if (proxyConfig != null) {
        Proxy proxy = proxyConfig.createProxy(url.getHost());
        if (proxy != null && proxy.type() == Proxy.Type.HTTP) {
            SocketAddress addr = proxy.address();
            if (addr != null && addr instanceof InetSocketAddress) {
                InetSocketAddress proxyAddr = (InetSocketAddress) addr;
                HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort());
                builder = builder.setProxy(proxyHost);

                String proxyUser = proxyConfig.getUserName();
                if (proxyUser != null) {
                    String proxyPass = proxyConfig.getPassword();
                    BasicCredentialsProvider cred = new BasicCredentialsProvider();
                    cred.setCredentials(new AuthScope(proxyHost),
                            new UsernamePasswordCredentials(proxyUser, proxyPass));
                    builder = builder.setDefaultCredentialsProvider(cred)
                            .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
                }
            }
        }
    }

    return builder.build();
}

From source file:com.blackducksoftware.integration.hub.jenkins.PostBuildHubScan.java

public void addProxySettingsToScanner(final IntLogger logger, final JenkinsScanExecutor scan)
        throws BDJenkinsHubPluginException, HubIntegrationException, URISyntaxException, MalformedURLException {
    final Jenkins jenkins = Jenkins.getInstance();
    if (jenkins != null) {
        final ProxyConfiguration proxyConfig = jenkins.proxy;
        if (proxyConfig != null) {

            final URL serverUrl = new URL(getHubServerInfo().getServerUrl());

            final Proxy proxy = ProxyConfiguration.createProxy(serverUrl.getHost(), proxyConfig.name,
                    proxyConfig.port, proxyConfig.noProxyHost);

            if (proxy != Proxy.NO_PROXY && proxy.address() != null) {
                final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
                if (StringUtils.isNotBlank(proxyAddress.getHostName()) && proxyAddress.getPort() != 0) {
                    if (StringUtils.isNotBlank(jenkins.proxy.getUserName())
                            && StringUtils.isNotBlank(jenkins.proxy.getPassword())) {
                        scan.setProxyHost(proxyAddress.getHostName());
                        scan.setProxyPort(proxyAddress.getPort());
                        scan.setProxyUsername(jenkins.proxy.getUserName());
                        scan.setProxyPassword(jenkins.proxy.getPassword());

                    } else {
                        scan.setProxyHost(proxyAddress.getHostName());
                        scan.setProxyPort(proxyAddress.getPort());
                    }//from   www.  j  ava  2s  .  c  o m
                    if (logger != null) {
                        logger.debug("Using proxy: '" + proxyAddress.getHostName() + "' at Port: '"
                                + proxyAddress.getPort() + "'");
                    }
                }
            }
        }
    }
}

From source file:com.blackducksoftware.integration.hub.jenkins.PostBuildHubScan.java

public void addProxySettingsToCLIInstaller(final IntLogger logger, final CLIRemoteInstall remoteCLIInstall)
        throws BDJenkinsHubPluginException, HubIntegrationException, URISyntaxException, MalformedURLException {
    final Jenkins jenkins = Jenkins.getInstance();
    if (jenkins != null) {
        final ProxyConfiguration proxyConfig = jenkins.proxy;
        if (proxyConfig != null) {

            final URL serverUrl = new URL(getHubServerInfo().getServerUrl());

            final Proxy proxy = ProxyConfiguration.createProxy(serverUrl.getHost(), proxyConfig.name,
                    proxyConfig.port, proxyConfig.noProxyHost);

            if (proxy != Proxy.NO_PROXY && proxy.address() != null) {
                final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
                if (StringUtils.isNotBlank(proxyAddress.getHostName()) && proxyAddress.getPort() != 0) {
                    if (StringUtils.isNotBlank(jenkins.proxy.getUserName())
                            && StringUtils.isNotBlank(jenkins.proxy.getPassword())) {
                        remoteCLIInstall.setProxyHost(proxyAddress.getHostName());
                        remoteCLIInstall.setProxyPort(proxyAddress.getPort());
                        remoteCLIInstall.setProxyUserName(jenkins.proxy.getUserName());
                        remoteCLIInstall.setProxyPassword(jenkins.proxy.getPassword());

                    } else {
                        remoteCLIInstall.setProxyHost(proxyAddress.getHostName());
                        remoteCLIInstall.setProxyPort(proxyAddress.getPort());
                    }//from w  w w . j  a v a 2  s . c o  m
                    if (logger != null) {
                        logger.debug("Using proxy: '" + proxyAddress.getHostName() + "' at Port: '"
                                + proxyAddress.getPort() + "'");
                    }
                }
            }
        }
    }
}

From source file:eu.operando.operandoapp.OperandoProxyStatus.java

private void updateStatusView() {
    OperandoProxyStatus proxyStatus = OperandoProxyStatus.STOPPED;
    OperandoProxyLink proxyLink = OperandoProxyLink.INVALID;
    boolean isProxyRunning = MainUtil.isServiceRunning(mainContext.getContext(), ProxyService.class);
    boolean isProxyPaused = MainUtil.isProxyPaused(mainContext);
    if (isProxyRunning) {
        if (isProxyPaused) {
            proxyStatus = OperandoProxyStatus.PAUSED;
        } else {/*from  w w  w  .  j  a  v  a  2s.c  om*/
            proxyStatus = OperandoProxyStatus.ACTIVE;
        }
    }
    try {
        Proxy proxy = APL.getCurrentHttpProxyConfiguration();
        InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        if (proxyAddress != null) {
            //TODO: THIS SHOULD BE DYNAMIC
            String proxyHost = proxyAddress.getHostName();
            int proxyPort = proxyAddress.getPort();

            if (proxyHost.equals("127.0.0.1") && proxyPort == 8899) {
                proxyLink = OperandoProxyLink.VALID;
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    String info = "";
    try {
        InputStream is = getResources().openRawResource(R.raw.info_template);
        info = IOUtils.toString(is);
        IOUtils.closeQuietly(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
    info = info.replace("@@status@@", proxyStatus.name());
    info = info.replace("@@link@@", proxyLink.name());
    webView.loadDataWithBaseURL("", info, "text/html", "UTF-8", "");
    webView.setBackgroundColor(Color.TRANSPARENT); //TRANSPARENT
}

From source file:org.apache.cxf.transport.http.asyncclient.AsyncHTTPConduit.java

@Override
protected void setupConnection(Message message, Address address, HTTPClientPolicy csPolicy) throws IOException {
    if (factory.isShutdown()) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, address, csPolicy);
        return;/*from  w  ww  .  j  a va2s  . c  o m*/
    }
    boolean addressChanged = false;
    // need to do some clean up work on the URI address
    URI uri = address.getURI();
    String uriString = uri.toString();
    if (uriString.startsWith("hc://")) {
        try {
            uriString = uriString.substring(5);
            uri = new URI(uriString);
            addressChanged = true;
        } catch (URISyntaxException ex) {
            throw new MalformedURLException("unsupport uri: " + uriString);
        }
    }
    String s = uri.getScheme();
    if (!"http".equals(s) && !"https".equals(s)) {
        throw new MalformedURLException("unknown protocol: " + s);
    }

    Object o = message.getContextualProperty(USE_ASYNC);
    if (o == null) {
        o = factory.getUseAsyncPolicy();
    }
    switch (UseAsyncPolicy.getPolicy(o)) {
    case ALWAYS:
        o = true;
        break;
    case NEVER:
        o = false;
        break;
    case ASYNC_ONLY:
    default:
        o = !message.getExchange().isSynchronous();
        break;
    }

    // check tlsClientParameters from message header
    TLSClientParameters clientParameters = message.get(TLSClientParameters.class);
    if (clientParameters == null) {
        clientParameters = tlsClientParameters;
    }
    if (uri.getScheme().equals("https") && clientParameters != null
            && clientParameters.getSSLSocketFactory() != null) {
        //if they configured in an SSLSocketFactory, we cannot do anything
        //with it as the NIO based transport cannot use socket created from
        //the SSLSocketFactory.
        o = false;
    }
    if (!MessageUtils.isTrue(o)) {
        message.put(USE_ASYNC, Boolean.FALSE);
        super.setupConnection(message, addressChanged ? new Address(uriString, uri) : address, csPolicy);
        return;
    }
    if (StringUtils.isEmpty(uri.getPath())) {
        //hc needs to have the path be "/" 
        uri = uri.resolve("/");
        addressChanged = true;
    }

    message.put(USE_ASYNC, Boolean.TRUE);
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Asynchronous connection to " + uri.toString() + " has been set up");
    }
    message.put("http.scheme", uri.getScheme());
    String httpRequestMethod = (String) message.get(Message.HTTP_REQUEST_METHOD);
    if (httpRequestMethod == null) {
        httpRequestMethod = "POST";
        message.put(Message.HTTP_REQUEST_METHOD, httpRequestMethod);
    }
    final CXFHttpRequest e = new CXFHttpRequest(httpRequestMethod);
    BasicHttpEntity entity = new BasicHttpEntity() {
        public boolean isRepeatable() {
            return e.getOutputStream().retransmitable();
        }
    };
    entity.setChunked(true);
    entity.setContentType((String) message.get(Message.CONTENT_TYPE));
    e.setURI(uri);

    e.setEntity(entity);

    RequestConfig.Builder b = RequestConfig.custom().setConnectTimeout((int) csPolicy.getConnectionTimeout())
            .setSocketTimeout((int) csPolicy.getReceiveTimeout())
            .setConnectionRequestTimeout((int) csPolicy.getReceiveTimeout());
    Proxy p = proxyFactory.createProxy(csPolicy, uri);
    if (p != null && p.type() != Proxy.Type.DIRECT) {
        InetSocketAddress isa = (InetSocketAddress) p.address();
        HttpHost proxy = new HttpHost(isa.getHostName(), isa.getPort());
        b.setProxy(proxy);
    }
    e.setConfig(b.build());

    message.put(CXFHttpRequest.class, e);
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient.java

private void setClientProxyParams(String host, HttpClientBuilder builder) {
    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxyConfig = null;
    if (jenkins != null) {
        proxyConfig = jenkins.proxy;//from  w  w w  .  jav a 2 s  .  c o m
    }

    Proxy proxy = Proxy.NO_PROXY;
    if (proxyConfig != null) {
        proxy = proxyConfig.createProxy(host);
    }

    if (proxy.type() != Proxy.Type.DIRECT) {
        final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        LOGGER.fine("Jenkins proxy: " + proxy.address());
        builder.setProxy(new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort()));
        String username = proxyConfig.getUserName();
        String password = proxyConfig.getPassword();
        if (username != null && !"".equals(username.trim())) {
            LOGGER.fine("Using proxy authentication (user=" + username + ")");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            AuthCache authCache = new BasicAuthCache();
            authCache.put(HttpHost.create(proxyAddress.getHostName()), new BasicScheme());
            context = HttpClientContext.create();
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthCache(authCache);
        }
    }
}

From source file:org.jenkinsci.plugins.fod.FoDAPI.java

private HttpClient getHttpClient() {
    final String METHOD_NAME = CLASS_NAME + ".getHttpClient";
    PrintStream logger = FodBuilder.getLogger();

    if (null == this.httpClient) {
        HttpClientBuilder builder = HttpClientBuilder.create();
        if (null != proxyConfig) {
            String fodBaseUrl = null;

            if (null != this.baseUrl && !this.baseUrl.isEmpty()) {
                fodBaseUrl = this.baseUrl;
            } else {
                fodBaseUrl = PUBLIC_FOD_BASE_URL;
            }//from www .  j  a v  a2  s.c  o  m

            Proxy proxy = proxyConfig.createProxy(fodBaseUrl);
            InetSocketAddress address = (InetSocketAddress) proxy.address();
            HttpHost proxyHttpHost = new HttpHost(address.getHostName(), address.getPort(),
                    proxy.address().toString().indexOf("https") != 0 ? "http" : "https");
            builder.setProxy(proxyHttpHost);

            if (null != proxyConfig.getUserName() && !proxyConfig.getUserName().trim().equals("")
                    && null != proxyConfig.getPassword() && !proxyConfig.getPassword().trim().equals("")) {
                Credentials credentials = new UsernamePasswordCredentials(proxyConfig.getUserName(),
                        proxyConfig.getPassword());
                AuthScope authScope = new AuthScope(address.getHostName(), address.getPort());
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(authScope, credentials);
                builder.setDefaultCredentialsProvider(credsProvider);
            }
            logger.println(METHOD_NAME + ": using proxy configuration: " + proxyHttpHost.getSchemeName() + "://"
                    + proxyHttpHost.getHostName() + ":" + proxyHttpHost.getPort());
        }
        this.httpClient = builder.build();
    }
    return this.httpClient;
}

From source file:com.xmlcalabash.library.ApacheHttpRequest.java

public void run() throws SaxonApiException {
    super.run();//from  w ww.j av  a2 s .co  m

    XdmNode requestDoc = source.read();
    XdmNode start = S9apiUtils.getDocumentElement(requestDoc);

    if (!c_request.equals(start.getNodeName())) {
        throw new UnsupportedOperationException("Not a c:http-request!");
    }

    // Check for valid attributes
    XdmSequenceIterator iter = start.axisIterator(Axis.ATTRIBUTE);
    boolean ok = true;
    while (iter.hasNext()) {
        XdmNode attr = (XdmNode) iter.next();
        QName name = attr.getNodeName();
        if (_method.equals(name) || _href.equals(name) || _detailed.equals(name) || _status_only.equals(name)
                || _username.equals(name) || _password.equals(name) || _auth_method.equals(name)
                || _send_authorization.equals(name) || _override_content_type.equals(name)) {
            // nop
        } else {
            if (XMLConstants.DEFAULT_NS_PREFIX.equals(name.getNamespaceURI())) {
                throw new XProcException("Unsupported attribute on c:http-request: " + name);
            }
        }
    }

    method = start.getAttributeValue(_method);
    statusOnly = "true".equals(start.getAttributeValue(_status_only));
    detailed = "true".equals(start.getAttributeValue(_detailed));
    overrideContentType = start.getAttributeValue(_override_content_type);

    if (start.getAttributeValue(_href) == null) {
        throw new XProcException("The 'href' attribute must be specified on p:http-request");
    }

    requestURI = start.getBaseURI().resolve(start.getAttributeValue(_href));

    if ("file".equals(requestURI.getScheme())) {
        doFile();
        return;
    }

    client = new HttpClient();

    String timeOutStr = step.getExtensionAttribute(cx_timeout);
    if (timeOutStr != null) {
        HttpMethodParams params = client.getParams();
        params.setSoTimeout(Integer.parseInt(timeOutStr));
    }

    ProxySelector proxySelector = ProxySelector.getDefault();
    List<Proxy> plist = proxySelector.select(requestURI);
    // I have no idea what I'm expected to do if I get more than one...
    if (plist.size() > 0) {
        Proxy proxy = plist.get(0);
        switch (proxy.type()) {
        case DIRECT:
            // nop;
            break;
        case HTTP:
            // This can't cause a ClassCastException, right?
            InetSocketAddress addr = (InetSocketAddress) proxy.address();
            String host = addr.getHostName();
            int port = addr.getPort();
            client.getHostConfiguration().setProxy(host, port);
            break;
        default:
            // FIXME: send out a log message
            break;
        }
    }

    if (start.getAttributeValue(_username) != null) {
        String user = start.getAttributeValue(_username);
        String pass = start.getAttributeValue(_password);
        String meth = start.getAttributeValue(_auth_method);

        if (meth == null || !("basic".equals(meth.toLowerCase()) || "digest".equals(meth.toLowerCase()))) {
            throw XProcException.stepError(3, "Unsupported auth-method: " + meth);
        }

        String host = requestURI.getHost();
        int port = requestURI.getPort();
        AuthScope scope = new AuthScope(host, port);

        UsernamePasswordCredentials cred = new UsernamePasswordCredentials(user, pass);

        client.getState().setCredentials(scope, cred);
    }

    iter = start.axisIterator(Axis.CHILD);
    XdmNode body = null;
    while (iter.hasNext()) {
        XdmNode event = (XdmNode) iter.next();
        // FIXME: What about non-whitespace text nodes?
        if (event.getNodeKind() == XdmNodeKind.ELEMENT) {
            if (body != null) {
                throw new UnsupportedOperationException("Elements follow c:multipart or c:body");
            }

            if (XProcConstants.c_header.equals(event.getNodeName())) {
                headers.add(new Header(event.getAttributeValue(_name), event.getAttributeValue(_value)));
            } else if (XProcConstants.c_multipart.equals(event.getNodeName())
                    || XProcConstants.c_body.equals(event.getNodeName())) {
                body = event;
            } else {
                throw new UnsupportedOperationException("Unexpected request element: " + event.getNodeName());
            }
        }
    }

    HttpMethodBase httpResult;

    if (method == null) {
        throw new XProcException("Method must be specified.");
    }

    if ("get".equals(method.toLowerCase())) {
        httpResult = doGet();
    } else if ("post".equals(method.toLowerCase())) {
        httpResult = doPost(body);
    } else if ("put".equals(method.toLowerCase())) {
        httpResult = doPut(body);
    } else if ("head".equals(method.toLowerCase())) {
        httpResult = doHead();
    } else {
        throw new UnsupportedOperationException("Unrecognized http method: " + method);
    }

    TreeWriter tree = new TreeWriter(runtime);
    tree.startDocument(requestURI);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(httpResult);

        String contentType = getContentType(httpResult);
        if (overrideContentType != null) {
            if ((xmlContentType(contentType) && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("text/") && overrideContentType.startsWith("image/"))
                    || (contentType.startsWith("image/") && xmlContentType(overrideContentType))
                    || (contentType.startsWith("image/") && overrideContentType.startsWith("text/"))
                    || (contentType.startsWith("multipart/") && !overrideContentType.startsWith("multipart/"))
                    || (!contentType.startsWith("multipart/")
                            && overrideContentType.startsWith("multipart/"))) {
                throw XProcException.stepError(30);
            }

            //System.err.println(overrideContentType + " overrides " + contentType);
            contentType = overrideContentType;
        }

        if (detailed) {
            tree.addStartElement(XProcConstants.c_response);
            tree.addAttribute(_status, "" + statusCode);
            tree.startContent();

            for (Header header : httpResult.getResponseHeaders()) {
                // I don't understand why/how HeaderElement parsing works. I get very weird results.
                // So I'm just going to go the long way around...
                String h = header.toString();
                int cp = h.indexOf(":");
                String name = header.getName();
                String value = h.substring(cp + 1).trim();

                tree.addStartElement(XProcConstants.c_header);
                tree.addAttribute(_name, name);
                tree.addAttribute(_value, value);
                tree.startContent();
                tree.addEndElement();
            }

            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }

            tree.addEndElement();
        } else {
            if (statusOnly) {
                // Skip reading the result
            } else {
                // Read the response body.
                InputStream bodyStream = httpResult.getResponseBodyAsStream();
                readBodyContent(tree, bodyStream, httpResult);
            }
        }
    } catch (Exception e) {
        throw new XProcException(e);
    } finally {
        // Release the connection.
        httpResult.releaseConnection();
    }

    tree.endDocument();

    XdmNode resultNode = tree.getResult();

    result.write(resultNode);
}

From source file:com.cloudbees.jenkins.plugins.bitbucket.server.client.BitbucketServerAPIClient.java

private void setClientProxyParams(String host, HttpClientBuilder builder) {
    Jenkins jenkins = Jenkins.getInstance();
    ProxyConfiguration proxyConfig = null;
    if (jenkins != null) {
        proxyConfig = jenkins.proxy;/*w  w  w .jav  a 2 s  .  c  om*/
    }

    final Proxy proxy;

    if (proxyConfig != null) {
        URI hostURI = URI.create(host);
        proxy = proxyConfig.createProxy(hostURI.getHost());
    } else {
        proxy = Proxy.NO_PROXY;
    }

    if (proxy.type() != Proxy.Type.DIRECT) {
        final InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
        LOGGER.log(Level.FINE, "Jenkins proxy: {0}", proxy.address());
        builder.setProxy(new HttpHost(proxyAddress.getHostName(), proxyAddress.getPort()));
        String username = proxyConfig.getUserName();
        String password = proxyConfig.getPassword();
        if (username != null && !"".equals(username.trim())) {
            LOGGER.fine("Using proxy authentication (user=" + username + ")");
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            AuthCache authCache = new BasicAuthCache();
            authCache.put(HttpHost.create(proxyAddress.getHostName()), new BasicScheme());
            context = HttpClientContext.create();
            context.setCredentialsProvider(credentialsProvider);
            context.setAuthCache(authCache);
        }
    }
}