Example usage for org.apache.commons.httpclient HttpState setProxyCredentials

List of usage examples for org.apache.commons.httpclient HttpState setProxyCredentials

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpState setProxyCredentials.

Prototype

public void setProxyCredentials(AuthScope paramAuthScope, Credentials paramCredentials) 

Source Link

Usage

From source file:com.zimbra.common.httpclient.HttpClientUtil.java

public static int executeMethod(HttpClient client, HttpMethod method, HttpState state)
        throws HttpException, IOException {
    ProxyHostConfiguration proxyConfig = HttpProxyConfig.getProxyConfig(client.getHostConfiguration(),
            method.getURI().toString());
    if (proxyConfig != null && proxyConfig.getUsername() != null && proxyConfig.getPassword() != null) {
        if (state == null) {
            state = client.getState();//from   w  ww . ja  v  a2 s  . co m
            if (state == null) {
                state = new HttpState();
            }
        }
        state.setProxyCredentials(new AuthScope(proxyConfig.getHost(), proxyConfig.getPort()),
                new UsernamePasswordCredentials(proxyConfig.getUsername(), proxyConfig.getPassword()));
    }
    return client.executeMethod(proxyConfig, method, state);
}

From source file:com.google.api.ads.dfp.lib.AuthToken.java

/**
 * Sets the proxy for the HTTP client./*from  w w w.ja va2 s  . c  o  m*/
 *
 * @param httpClient the HTTP client to set the proxy for
 */
private void setProxy(HttpClient httpClient) {
    if (System.getProperty("http.proxyHost") != null && System.getProperty("http.proxyPort") != null) {
        httpClient.getHostConfiguration().setProxy(System.getProperty("http.proxyHost"),
                Integer.parseInt(System.getProperty("http.proxyPort")));

        if (System.getProperty("http.proxyUser") != null && System.getProperty("http.proxyPassword") != null) {
            HttpState state = new HttpState();
            state.setProxyCredentials(
                    new AuthScope(System.getProperty("http.proxyHost"),
                            Integer.parseInt(System.getProperty("http.proxyPort"))),
                    new UsernamePasswordCredentials(System.getProperty("http.proxyUser"),
                            System.getProperty("http.proxyPassword")));
            httpClient.setState(state);
        }
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.HttpClientFactoryProvider.java

public HttpClientFactory createHttpClientFactory(final Collection<HttpClientConfiguration> configurations) {
    return new HttpClientFactory() {
        @Override//from ww  w .ja  v a2 s . com
        public HttpClient createClient(String host, int port) {

            ApacheHttpClient31BackedHttpClient httpClient = createApacheClient();

            HostConfiguration hostConfiguration = new HostConfiguration();
            configureSsl(hostConfiguration, host, port, httpClient);
            configureProxy(hostConfiguration, httpClient);

            httpClient.setHostConfiguration(hostConfiguration);
            configureOAuth(httpClient);
            return httpClient;
        }

        private ApacheHttpClient31BackedHttpClient createApacheClient() {
            HttpClientConfig httpClientConfig = locateConfig(HttpClientConfig.class,
                    HttpClientConfig.newBuilder().build());

            HttpConnectionManager connectionManager = createConnectionManager(httpClientConfig);

            org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(
                    connectionManager);
            client.getParams().setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109);
            client.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            client.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
            client.getParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true);
            client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                    httpClientConfig.getSocketTimeoutInMillis() > 0
                            ? httpClientConfig.getSocketTimeoutInMillis()
                            : 0);
            client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
                    httpClientConfig.getSocketTimeoutInMillis() > 0
                            ? httpClientConfig.getSocketTimeoutInMillis()
                            : 0);

            return new ApacheHttpClient31BackedHttpClient(client,
                    httpClientConfig.getCopyOfHeadersForEveryRequest());

        }

        @SuppressWarnings("unchecked")
        private <T> T locateConfig(Class<? extends T> _class, T defaultConfiguration) {
            for (HttpClientConfiguration configuration : configurations) {
                if (_class.isInstance(configuration)) {
                    return (T) configuration;
                }
            }
            return defaultConfiguration;
        }

        private boolean hasValidProxyUsernameAndPasswordSettings(HttpClientProxyConfig httpClientProxyConfig) {
            return StringUtils.isNotBlank(httpClientProxyConfig.getProxyUsername())
                    && StringUtils.isNotBlank(httpClientProxyConfig.getProxyPassword());
        }

        private HttpConnectionManager createConnectionManager(HttpClientConfig config) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            if (config.getMaxConnectionsPerHost() > 0) {
                connectionManager.getParams()
                        .setDefaultMaxConnectionsPerHost(config.getMaxConnectionsPerHost());
            } else {
                connectionManager.getParams().setDefaultMaxConnectionsPerHost(Integer.MAX_VALUE);
            }
            if (config.getMaxConnections() > 0) {
                connectionManager.getParams().setMaxTotalConnections(config.getMaxConnections());
            }
            return connectionManager;
        }

        private void configureOAuth(ApacheHttpClient31BackedHttpClient httpClient) {
            HttpClientOAuthConfig httpClientOAuthConfig = locateConfig(HttpClientOAuthConfig.class, null);
            if (httpClientOAuthConfig != null) {
                String serviceName = httpClientOAuthConfig.getServiceName();
                HttpClientConsumerKeyAndSecretProvider consumerKeyAndSecretProvider = httpClientOAuthConfig
                        .getConsumerKeyAndSecretProvider();
                String consumerKey = consumerKeyAndSecretProvider.getConsumerKey(serviceName);
                if (StringUtils.isEmpty(consumerKey)) {
                    throw new RuntimeException(
                            "could create oauth client because consumerKey is null or empty for service:"
                                    + serviceName);
                }
                String consumerSecret = consumerKeyAndSecretProvider.getConsumerSecret(serviceName);
                if (StringUtils.isEmpty(consumerSecret)) {
                    throw new RuntimeException(
                            "could create oauth client because consumerSecret is null or empty for service:"
                                    + serviceName);
                }

                httpClient.setConsumerTokens(consumerKey, consumerSecret);
            }
        }

        private void configureProxy(HostConfiguration hostConfiguration,
                ApacheHttpClient31BackedHttpClient httpClient) {
            HttpClientProxyConfig httpClientProxyConfig = locateConfig(HttpClientProxyConfig.class, null);
            if (httpClientProxyConfig != null) {
                hostConfiguration.setProxy(httpClientProxyConfig.getProxyHost(),
                        httpClientProxyConfig.getProxyPort());
                if (hasValidProxyUsernameAndPasswordSettings(httpClientProxyConfig)) {
                    HttpState state = new HttpState();
                    state.setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(httpClientProxyConfig.getProxyUsername(),
                                    httpClientProxyConfig.getProxyPassword()));
                    httpClient.setState(state);
                }
            }
        }

        private void configureSsl(HostConfiguration hostConfiguration, String host, int port,
                ApacheHttpClient31BackedHttpClient httpClient) throws IllegalStateException {
            HttpClientSSLConfig httpClientSSLConfig = locateConfig(HttpClientSSLConfig.class, null);
            if (httpClientSSLConfig != null) {
                Protocol sslProtocol;
                if (httpClientSSLConfig.getCustomSSLSocketFactory() != null) {
                    sslProtocol = new Protocol(HTTPS_PROTOCOL, new CustomSecureProtocolSocketFactory(
                            httpClientSSLConfig.getCustomSSLSocketFactory()), SSL_PORT);
                } else {
                    sslProtocol = Protocol.getProtocol(HTTPS_PROTOCOL);
                }
                hostConfiguration.setHost(host, port, sslProtocol);
                httpClient.setUsingSSL();
            } else {
                hostConfiguration.setHost(host, port);
            }
        }
    };
}

From source file:com.twinsoft.convertigo.engine.ProxyManager.java

public void setAnonymAuth(HttpState httpState) {
    // Setting anonym authentication for proxy
    if ((!this.proxyServer.equals("")) && (!this.proxyUser.equals(""))) {
        httpState.setProxyCredentials(new AuthScope(AuthScope.ANY), new Credentials() {
        });/*from w  ww . j a va2  s. c o m*/

        Engine.logProxyManager.debug("(ProxyManager) Proxy credentials: anonym");
    }
}

From source file:com.twinsoft.convertigo.engine.ProxyManager.java

public void setBasicAuth(HttpState httpState) {
    // Setting basic authentication for proxy
    if ((!this.proxyServer.equals("")) && (!this.proxyUser.equals(""))) {
        httpState.setProxyCredentials(new AuthScope(this.proxyServer, -1, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(this.proxyUser, this.proxyPassword));

        Engine.logProxyManager.debug("(ProxyManager) Using credentials: " + promptUser
                + ", <password not logged, set engine logger log level to TRACE to see it>");
        Engine.logProxyManager.trace("(ProxyManager) Using password: " + proxyPassword);
    }//from   www . j a  v a2  s.co m
}

From source file:com.rallydev.integration.build.rest.RallyRestServiceTest.java

public void testRallyRestServiceBuildSuccessWithProxyAndAuth() throws Exception {
    MockControl httpStateMockControl1;/*  ww w  .j  av a 2 s  .  c  om*/
    HttpState httpStateMock1;

    httpStateMockControl1 = MockClassControl.createControl(HttpState.class);
    httpStateMock1 = (HttpState) httpStateMockControl1.getMock();
    httpStateMock1.setCredentials(new AuthScope("host", -1, null),
            new UsernamePasswordCredentials("user", "password"));
    httpStateMock1.setProxyCredentials(new AuthScope("proxyserver.mycompany.com", 3128, null),
            new UsernamePasswordCredentials("user@rallydev.com", "password"));
    httpStateMockControl1.replay();

    String xml = readFile(BUILD_SUCCESS_FILE);
    httpClientMockControl.expectAndReturn(httpClientMock.getHostConfiguration(), hostConfigurationMock);
    hostConfigurationMock.setProxy("proxyserver.mycompany.com", 3128);

    httpClientMockControl.expectAndReturn(httpClientMock.getState(), httpStateMock1);

    httpClientMockControl.expectAndReturn(httpClientMock.executeMethod(postMethodMock), HttpStatus.SC_OK);
    postMethodMockControl.expectAndReturn(postMethodMock.getResponseBodyAsStream(),
            readFileAsStream(BUILD_SUCCESS_RESPONSE_FILE));
    postMethodMock.releaseConnection();

    httpClientMockControl.replay();
    postMethodMockControl.replay();
    hostConfigurationMockControl.replay();

    rallyRestService.setProxyInfo("proxyserver.mycompany.com", 3128, "user@rallydev.com", "password");
    String response = rallyRestService.doCreate(xml, httpClientMock, postMethodMock);
    assertEquals(readFile(BUILD_SUCCESS_RESPONSE_FILE), response);
    httpStateMockControl.verify();
    hostConfigurationMockControl.verify();
    verify();
}

From source file:com.twinsoft.convertigo.engine.ProxyManager.java

public void setNtlmAuth(HttpState httpState) {
    // Setting NTLM authentication for proxy
    int indexSlash = this.proxyUser.indexOf("\\");
    String domain = this.proxyUser.substring(0, indexSlash);
    String username = this.proxyUser.substring(indexSlash + 1);

    Engine.logProxyManager.debug("(ProxyManager) Using NTLM authentication on domain: " + domain);

    httpState.setProxyCredentials(new AuthScope(this.proxyServer, -1, AuthScope.ANY_REALM),
            new NTCredentials(username, this.proxyPassword, this.proxyServer, domain));

}

From source file:com.zimbra.common.soap.SoapHttpTransport.java

public Element invoke(Element document, boolean raw, boolean noSession, String requestedAccountId,
        String changeToken, String tokenType, ResponseHandler respHandler)
        throws IOException, HttpException, ServiceException {
    PostMethod method = null;/*from  ww w.  ja  v  a  2 s  .  com*/

    try {
        // Assemble post method.  Append document name, so that the request
        // type is written to the access log.
        String uri, query;
        int i = mUri.indexOf('?');
        if (i >= 0) {
            uri = mUri.substring(0, i);
            query = mUri.substring(i);
        } else {
            uri = mUri;
            query = "";
        }
        if (!uri.endsWith("/"))
            uri += '/';
        uri += getDocumentName(document);
        method = new PostMethod(uri + query);

        // Set user agent if it's specified.
        String agentName = getUserAgentName();
        if (agentName != null) {
            String agentVersion = getUserAgentVersion();
            if (agentVersion != null)
                agentName += " " + agentVersion;
            method.setRequestHeader(new Header("User-Agent", agentName));
        }

        // the content-type charset will determine encoding used
        // when we set the request body
        method.setRequestHeader("Content-Type", getRequestProtocol().getContentType());
        if (getClientIp() != null) {
            method.setRequestHeader(RemoteIP.X_ORIGINATING_IP_HEADER, getClientIp());
            if (ZimbraLog.misc.isDebugEnabled()) {
                ZimbraLog.misc.debug("set remote IP header [%s] to [%s]", RemoteIP.X_ORIGINATING_IP_HEADER,
                        getClientIp());
            }
        }
        Element soapReq = generateSoapMessage(document, raw, noSession, requestedAccountId, changeToken,
                tokenType);
        String soapMessage = SoapProtocol.toString(soapReq, getPrettyPrint());
        HttpMethodParams params = method.getParams();

        method.setRequestEntity(new StringRequestEntity(soapMessage, null, "UTF-8"));

        if (getRequestProtocol().hasSOAPActionHeader())
            method.setRequestHeader("SOAPAction", mUri);

        if (mCustomHeaders != null) {
            for (Map.Entry<String, String> entry : mCustomHeaders.entrySet())
                method.setRequestHeader(entry.getKey(), entry.getValue());
        }

        String host = method.getURI().getHost();
        HttpState state = HttpClientUtil.newHttpState(getAuthToken(), host, this.isAdmin());
        String trustedToken = getTrustedToken();
        if (trustedToken != null) {
            state.addCookie(
                    new Cookie(host, ZimbraCookie.COOKIE_ZM_TRUST_TOKEN, trustedToken, "/", null, false));
        }
        params.setCookiePolicy(state.getCookies().length == 0 ? CookiePolicy.IGNORE_COOKIES
                : CookiePolicy.BROWSER_COMPATIBILITY);
        params.setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(mRetryCount - 1, true));
        params.setSoTimeout(mTimeout);
        params.setVersion(HttpVersion.HTTP_1_1);
        method.setRequestHeader("Connection", mKeepAlive ? "Keep-alive" : "Close");

        if (mHostConfig != null && mHostConfig.getUsername() != null && mHostConfig.getPassword() != null) {
            state.setProxyCredentials(new AuthScope(null, -1),
                    new UsernamePasswordCredentials(mHostConfig.getUsername(), mHostConfig.getPassword()));
        }

        if (mHttpDebugListener != null) {
            mHttpDebugListener.sendSoapMessage(method, soapReq, state);
        }

        int responseCode = mClient.executeMethod(mHostConfig, method, state);
        // SOAP allows for "200" on success and "500" on failure;
        //   real server issues will probably be "503" or "404"
        if (responseCode != HttpServletResponse.SC_OK
                && responseCode != HttpServletResponse.SC_INTERNAL_SERVER_ERROR)
            throw ServiceException.PROXY_ERROR(method.getStatusLine().toString(), uri);

        // Read the response body.  Use the stream API instead of the byte[]
        // version to avoid HTTPClient whining about a large response.
        InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream(),
                SoapProtocol.getCharset());
        String responseStr = "";

        try {
            if (respHandler != null) {
                respHandler.process(reader);
                return null;
            } else {
                responseStr = ByteUtil.getContent(reader, (int) method.getResponseContentLength(), false);
                Element soapResp = parseSoapResponse(responseStr, raw);

                if (mHttpDebugListener != null) {
                    mHttpDebugListener.receiveSoapMessage(method, soapResp);
                }
                return soapResp;
            }
        } catch (SoapFaultException x) {
            // attach request/response to the exception and rethrow
            x.setFaultRequest(soapMessage);
            x.setFaultResponse(responseStr.substring(0, Math.min(10240, responseStr.length())));
            throw x;
        }
    } finally {
        // Release the connection to the connection manager
        if (method != null)
            method.releaseConnection();

        // really not necessary if running in the server because the reaper thread
        // of our connection manager will take care it.
        // if called from CLI, all connections will be closed when the CLI
        // exits.  Leave it here anyway.
        if (!mKeepAlive)
            mClient.getHttpConnectionManager().closeIdleConnections(0);
    }
}

From source file:com.liferay.portal.util.HttpImpl.java

public void proxifyState(HttpState httpState, HostConfiguration hostConfiguration) {

    Credentials proxyCredentials = _proxyCredentials;

    String host = hostConfiguration.getHost();

    if (isProxyHost(host) && (proxyCredentials != null)) {
        AuthScope scope = new AuthScope(_PROXY_HOST, _PROXY_PORT, null);

        httpState.setProxyCredentials(scope, proxyCredentials);
    }//from w w  w .  j ava  2s . co  m
}

From source file:com.eviware.soapui.impl.wsdl.support.http.ProxyUtils.java

public static HostConfiguration initProxySettings(Settings settings, HttpState httpState,
        HostConfiguration hostConfiguration, String urlString, PropertyExpansionContext context) {
    boolean enabled = proxyEnabled;

    // check system properties first
    String proxyHost = System.getProperty("http.proxyHost");
    String proxyPort = System.getProperty("http.proxyPort");
    if (proxyHost == null && enabled)
        proxyHost = PropertyExpander.expandProperties(context, settings.getString(ProxySettings.HOST, ""));
    if (proxyPort == null && proxyHost != null && enabled)
        proxyPort = PropertyExpander.expandProperties(context, settings.getString(ProxySettings.PORT, ""));

    if (!StringUtils.isNullOrEmpty(proxyHost) && !StringUtils.isNullOrEmpty(proxyPort)) {
        // check excludes
        String[] excludes = PropertyExpander
                .expandProperties(context, settings.getString(ProxySettings.EXCLUDES, "")).split(",");

        try {/*  ww  w  .j ava  2 s .c  o  m*/
            URL url = new URL(urlString);

            if (!excludes(excludes, url.getHost(), url.getPort())) {
                hostConfiguration.setProxy(proxyHost, Integer.parseInt(proxyPort));

                String proxyUsername = PropertyExpander.expandProperties(context,
                        settings.getString(ProxySettings.USERNAME, null));
                String proxyPassword = PropertyExpander.expandProperties(context,
                        settings.getString(ProxySettings.PASSWORD, null));

                if (proxyUsername != null && proxyPassword != null) {
                    Credentials proxyCreds = new UsernamePasswordCredentials(proxyUsername,
                            proxyPassword == null ? "" : proxyPassword);

                    // check for nt-username
                    int ix = proxyUsername.indexOf('\\');
                    if (ix > 0) {
                        String domain = proxyUsername.substring(0, ix);
                        if (proxyUsername.length() > ix + 1) {
                            String user = proxyUsername.substring(ix + 1);
                            proxyCreds = new NTCredentials(user, proxyPassword, proxyHost, domain);
                        }
                    }

                    httpState.setProxyCredentials(AuthScope.ANY, proxyCreds);
                }
            }
        } catch (MalformedURLException e) {
            SoapUI.logError(e);
        }
    }

    return hostConfiguration;
}