Example usage for org.apache.commons.httpclient.auth CredentialsProvider PROVIDER

List of usage examples for org.apache.commons.httpclient.auth CredentialsProvider PROVIDER

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.auth CredentialsProvider PROVIDER.

Prototype

String PROVIDER

To view the source code for org.apache.commons.httpclient.auth CredentialsProvider PROVIDER.

Click Source Link

Usage

From source file:net.adamcin.httpsig.http.apache3.Http3Util.java

public static void enableAuth(HttpClient client, Keychain keychain, KeyId keyId) {
    Signer signer = new Signer(keychain, keyId);
    CredentialsProvider credProvider = (CredentialsProvider) client.getParams()
            .getParameter(CredentialsProvider.PROVIDER);

    CredentialsProvider newProvider;// w w  w  .  ja v  a 2 s. c  o m
    if (credProvider instanceof SignerCredentialsProvider) {
        newProvider = new SignerCredentialsProvider(signer,
                ((SignerCredentialsProvider) credProvider).getDelegatee());
    } else {
        newProvider = new SignerCredentialsProvider(signer, credProvider);
    }

    client.getParams().setParameter(CredentialsProvider.PROVIDER, newProvider);
    AuthPolicy.registerAuthScheme(Constants.SCHEME, Http3SignatureAuthScheme.class);
    List<String> schemes = new ArrayList<String>();
    schemes.add(Constants.SCHEME);

    Collection authSchemePriority = (Collection) DefaultHttpParams.getDefaultParams()
            .getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY);
    if (authSchemePriority != null) {
        schemes.addAll(authSchemePriority);
    }
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, schemes);
}

From source file:com.alibaba.antx.config.resource.http.HttpSession.java

public HttpSession(ResourceDriver driver) {
    super(driver);

    client = new HttpClient();

    client.getParams().setAuthenticationPreemptive(true);
    client.getParams().setParameter(CredentialsProvider.PROVIDER, new CredentialsProvider() {
        public Credentials getCredentials(AuthScheme scheme, String host, int port, boolean proxy)
                throws CredentialsNotAvailableException {
            URI uri = ResourceContext.get().getCurrentURI();
            String username = ResourceContext.get().getCurrentUsername();
            Set visitedURIs = ResourceContext.get().getVisitedURIs();
            ResourceKey key = new ResourceKey(new ResourceURI(uri));
            String message;/*from w ww.ja  va2 s  . c  o  m*/

            message = "\n";
            message += "Authentication required.\n";
            message += "realm: " + scheme.getRealm() + "\n";
            message += "  uri: " + uri + "\n";

            UsernamePassword up = getResourceManager().getAuthenticationHandler().authenticate(message, uri,
                    username, visitedURIs.contains(key));

            visitedURIs.add(key);

            return new UsernamePasswordCredentials(up.getUsername(), up.getPassword());
        }
    });
}

From source file:com.abee.InteractiveAuthenticationExample.java

private void doDemo() throws IOException {

    HttpClient client = new HttpClient();
    client.getParams().setParameter(CredentialsProvider.PROVIDER, new ConsoleAuthPrompter());
    GetMethod httpget = new GetMethod("http://www.lauramares.com/kaira");
    httpget.setDoAuthentication(true);/*from w w w  .ja va 2 s . c  o m*/
    try {
        // execute the GET
        int status = client.executeMethod(httpget);
        // print the status and response
        System.out.println(httpget.getStatusLine().toString());
        System.out.println(httpget.getResponseBodyAsString());
    } finally {
        // release any connection resources used by the method
        httpget.releaseConnection();
    }
}

From source file:InteractiveAuthenticationExample.java

private void doDemo() throws IOException {

    HttpClient client = new HttpClient();
    client.getParams().setParameter(CredentialsProvider.PROVIDER, new ConsoleAuthPrompter());
    GetMethod httpget = new GetMethod("http://target-host/requires-auth.html");
    httpget.setDoAuthentication(true);/*ww w.jav a  2s . co m*/
    try {
        // execute the GET
        int status = client.executeMethod(httpget);
        // print the status and response
        System.out.println(httpget.getStatusLine().toString());
        System.out.println(httpget.getResponseBodyAsString());
    } finally {
        // release any connection resources used by the method
        httpget.releaseConnection();
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpAuthenticationRequestFilter.java

public static void initRequestCredentials(SubmitContext context, String username, Settings settings,
        String password, String domain) {
    HttpClient httpClient = (HttpClient) context.getProperty(BaseHttpRequestTransport.HTTP_CLIENT);
    HttpMethod httpMethod = (HttpMethod) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    if (StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)) {
        httpClient.getParams().setAuthenticationPreemptive(false);
        httpMethod.setDoAuthentication(false);
    } else {//from  w  w  w  .  j a v a 2s. c  om
        // set preemptive authentication
        if (settings.getBoolean(HttpSettings.AUTHENTICATE_PREEMPTIVELY)) {
            httpClient.getParams().setAuthenticationPreemptive(true);
            HttpState state = (HttpState) context.getProperty(SubmitContext.HTTP_STATE_PROPERTY);

            if (state != null) {
                Credentials defaultcreds = new UsernamePasswordCredentials(username,
                        password == null ? "" : password);
                state.setCredentials(AuthScope.ANY, defaultcreds);
            }
        } else {
            httpClient.getParams().setAuthenticationPreemptive(false);
        }

        httpMethod.getParams().setParameter(CredentialsProvider.PROVIDER,
                new UPDCredentialsProvider(username, password, domain));

        httpMethod.setDoAuthentication(true);
    }
}

From source file:br.org.acessobrasil.nucleuSilva.util.PegarPaginaWEB.java

public PegarPaginaWEB() {
    // me parece que o construtor aqui apenas inicializa alguns parametros e
    // registra o protocolo

    httpClient = new HttpClient();
    ps = new PainelSenha();
    httpClient.getParams().setParameter(CredentialsProvider.PROVIDER, ps); // coloca
    // no/*from w w w .java2  s  .co m*/
    // objeto
    // httpclient
    // o
    // parametro
    // provider
    // associado
    // a ps
    EasySSLProtocolSocketFactory sssl = new EasySSLProtocolSocketFactory();
    // StrictSSLProtocolSocketFactory sssl = new
    // StrictSSLProtocolSocketFactory();
    // sssl.setHostnameVerification(false);
    Protocol easyhttps = new Protocol("https", sssl, 443);
    Protocol.registerProtocol("https", easyhttps);
}

From source file:com.sun.jersey.client.apache.DefaultApacheHttpMethodExecutor.java

@Override
public void executeMethod(final HttpMethod method, final ClientRequest cr) {
    final Map<String, Object> props = cr.getProperties();

    method.setDoAuthentication(true);//w ww .j a  v  a2  s.c  o  m

    final HttpMethodParams methodParams = method.getParams();

    // Set the handle cookies property
    if (!cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES)) {
        methodParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    }

    // Set the interactive and credential provider properties
    if (cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_INTERACTIVE)) {
        CredentialsProvider provider = (CredentialsProvider) props
                .get(ApacheHttpClientConfig.PROPERTY_CREDENTIALS_PROVIDER);
        if (provider == null) {
            provider = DEFAULT_CREDENTIALS_PROVIDER;
        }
        methodParams.setParameter(CredentialsProvider.PROVIDER, provider);
    } else {
        methodParams.setParameter(CredentialsProvider.PROVIDER, null);
    }

    // Set the read timeout
    final Integer readTimeout = (Integer) props.get(ApacheHttpClientConfig.PROPERTY_READ_TIMEOUT);
    if (readTimeout != null) {
        methodParams.setSoTimeout(readTimeout);
    }

    if (method instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entMethod = (EntityEnclosingMethod) method;

        if (cr.getEntity() != null) {
            final RequestEntityWriter re = getRequestEntityWriter(cr);
            final Integer chunkedEncodingSize = (Integer) props
                    .get(ApacheHttpClientConfig.PROPERTY_CHUNKED_ENCODING_SIZE);
            if (chunkedEncodingSize != null) {
                // There doesn't seems to be a way to set the chunk size.
                entMethod.setContentChunked(true);

                // It is not possible for a MessageBodyWriter to modify
                // the set of headers before writing out any bytes to
                // the OutputStream
                // This makes it impossible to use the multipart
                // writer that modifies the content type to add a boundary
                // parameter
                writeOutBoundHeaders(cr.getHeaders(), method);

                // Do not buffer the request entity when chunked encoding is
                // set
                entMethod.setRequestEntity(new RequestEntity() {

                    @Override
                    public boolean isRepeatable() {
                        return false;
                    }

                    @Override
                    public void writeRequest(OutputStream out) throws IOException {
                        re.writeRequestEntity(out);
                    }

                    @Override
                    public long getContentLength() {
                        return re.getSize();
                    }

                    @Override
                    public String getContentType() {
                        return re.getMediaType().toString();
                    }
                });

            } else {
                entMethod.setContentChunked(false);

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    re.writeRequestEntity(new CommittingOutputStream(baos) {

                        @Override
                        protected void commit() throws IOException {
                            writeOutBoundHeaders(cr.getMetadata(), method);
                        }
                    });
                } catch (IOException ex) {
                    throw new ClientHandlerException(ex);
                }

                final byte[] content = baos.toByteArray();
                entMethod.setRequestEntity(new RequestEntity() {

                    @Override
                    public boolean isRepeatable() {
                        return true;
                    }

                    @Override
                    public void writeRequest(OutputStream out) throws IOException {
                        out.write(content);
                    }

                    @Override
                    public long getContentLength() {
                        return content.length;
                    }

                    @Override
                    public String getContentType() {
                        return re.getMediaType().toString();
                    }
                });
            }
        } else {
            writeOutBoundHeaders(cr.getHeaders(), method);
        }
    } else {
        writeOutBoundHeaders(cr.getHeaders(), method);

        // Follow redirects
        method.setFollowRedirects(cr.getPropertyAsFeature(ApacheHttpClientConfig.PROPERTY_FOLLOW_REDIRECTS));
    }
    try {
        httpClient.executeMethod(getHostConfiguration(httpClient, props), method, getHttpState(props));
    } catch (Exception e) {
        method.releaseConnection();
        throw new ClientHandlerException(e);
    }
}

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

protected void createGetMethod(String url) {
    getMethod = new GetMethod(url);
    getMethod.setFollowRedirects(true);//from   w  w w .ja v  a  2s .  c  om
    getMethod.setDoAuthentication(true);
    getMethod.getParams().setParameter(CredentialsProvider.PROVIDER, new WsdlCredentialsProvider());

    if (SoapUI.getSettings().getBoolean(HttpSettings.AUTHENTICATE_PREEMPTIVELY)) {
        HttpClientSupport.getHttpClient().getParams().setAuthenticationPreemptive(true);
    } else {
        HttpClientSupport.getHttpClient().getParams().setAuthenticationPreemptive(false);
    }
}

From source file:com.globalsight.everest.webapp.applet.admin.customer.FileSystemApplet.java

/**
 * Sets up the HttpClient to use a proxy if one needs to be used.
 * Also sets up for proxy authentication (NTLM and Basic)
 * /*from  w  w  w  . j  av  a 2s  .  c  o m*/
 * @param p_httpClient
 */
private void setUpClientForProxy(HttpClient p_client) throws Exception {
    //first see if a proxy needs to be used at all
    //detectProxyInfoFromSystem() is known to work at Dell
    //        ProxyInfo proxyInfo = detectProxyInfoFromSystem();

    //detectProxyInfoFromBrowser() is probably more correct,
    String urlPrefix = AppletHelper.getUrlPrefix(this);
    String servletUrl = getParameter(AppletHelper.SERVLET_URL);
    String randID = getParameter(AppletHelper.RANDOM);
    String servletLocation = urlPrefix + servletUrl + randID;
    ProxyInfo proxyInfo = GlobalSightProxyInfo.detectProxyInfoFromBrowser(new URL(servletLocation));

    if (proxyInfo != null) {
        System.out.println("---- Setting up client for proxy.");
        //set to use proxy
        p_client.getHostConfiguration().setProxy(proxyInfo.getHost(), proxyInfo.getPort());

        //set to authenticate to proxy if need be
        p_client.getParams().setParameter(CredentialsProvider.PROVIDER, s_authPrompter);
    } else {
        System.out.println("---- No need to set client for proxy.");
    }
}

From source file:nz.net.kallisti.emusicj.network.http.proxy.HttpClientProvider.java

public HttpClient getHttpClient() {
    HttpState state = getState();/*from w w  w . ja  v a  2 s. co  m*/
    HttpClient client = new HttpClient();
    client.setState(state);
    if (!prefs.getProxyHost().equals("") && prefs.usingProxy()) {
        HostConfiguration hostConf = new HostConfiguration();
        hostConf.setProxy(prefs.getProxyHost(), prefs.getProxyPort());
        client.setHostConfiguration(hostConf);
        client.getParams().setParameter(CredentialsProvider.PROVIDER, proxyCredsProvider);
    }
    return client;
}