Example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getCredentialsProvider.

Prototype

public synchronized final CredentialsProvider getCredentialsProvider() 

Source Link

Usage

From source file:com.google.code.maven.plugin.http.client.ProxyTest.java

@Test
public void testPrepare() {
    proxy.setHost("localhost");
    proxy.setPort(8080);/*from   w  w  w . j a v  a2 s .c  om*/
    DefaultHttpClient client = new DefaultHttpClient();
    proxy.prepare(client);
    HttpHost httpHost = (HttpHost) client.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY);
    Assert.assertNotNull(httpHost);
    Assert.assertEquals(httpHost.getHostName(), proxy.getHost());
    Assert.assertEquals(httpHost.getPort(), proxy.getPort());
    Assert.assertEquals(httpHost.getSchemeName(), HttpHost.DEFAULT_SCHEME_NAME);

    Credentials credentials = new Credentials();
    credentials.setLogin("login");
    credentials.setPassword("password");
    proxy.setCredentials(credentials);
    client = new DefaultHttpClient();
    proxy.prepare(client);
    httpHost = (HttpHost) client.getParams().getParameter(ConnRoutePNames.DEFAULT_PROXY);
    Assert.assertNotNull(httpHost);
    Assert.assertEquals(httpHost.getHostName(), proxy.getHost());
    Assert.assertEquals(httpHost.getPort(), proxy.getPort());
    Assert.assertEquals(httpHost.getSchemeName(), HttpHost.DEFAULT_SCHEME_NAME);
    org.apache.http.auth.Credentials credentials2 = client.getCredentialsProvider()
            .getCredentials(new AuthScope("localhost", 8080));
    Assert.assertNotNull(credentials2);
    Assert.assertEquals("login", credentials2.getUserPrincipal().getName());
    Assert.assertEquals("password", credentials2.getPassword());
}

From source file:com.marklogic.client.tutorial.util.Bootstrapper.java

/**
 * Programmatic invocation.//from  w  w w  .j  av  a  2 s .  c  om
 * @param configServer   the configuration server for creating the REST server
 * @param restServer   the specification of the REST server
 */
public void makeServer(ConfigServer configServer, RESTServer restServer)
        throws ClientProtocolException, IOException, XMLStreamException, FactoryConfigurationError {

    DefaultHttpClient client = new DefaultHttpClient();

    String host = configServer.getHost();
    int configPort = configServer.getPort();

    Authentication authType = configServer.getAuthType();
    if (authType != null) {
        List<String> prefList = new ArrayList<String>();
        if (authType == Authentication.BASIC)
            prefList.add(AuthPolicy.BASIC);
        else if (authType == Authentication.DIGEST)
            prefList.add(AuthPolicy.DIGEST);
        else
            throw new IllegalArgumentException("Unknown authentication type: " + authType.name());
        client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, prefList);

        String configUser = configServer.getUser();
        String configPassword = configServer.getPassword();
        client.getCredentialsProvider().setCredentials(new AuthScope(host, configPort),
                new UsernamePasswordCredentials(configUser, configPassword));
    }

    BasicHttpContext context = new BasicHttpContext();

    StringEntity content = new StringEntity(restServer.toXMLString());
    content.setContentType("application/xml");

    HttpPost poster = new HttpPost("http://" + host + ":" + configPort + "/v1/rest-apis");
    poster.setEntity(content);

    HttpResponse response = client.execute(poster, context);
    //poster.releaseConnection();

    StatusLine status = response.getStatusLine();

    int statusCode = status.getStatusCode();
    String statusPhrase = status.getReasonPhrase();

    client.getConnectionManager().shutdown();

    if (statusCode >= 300) {
        throw new RuntimeException("Failed to create REST server: " + statusCode + " " + statusPhrase + "\n"
                + "Please check the server log for detail");
    }
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Executes the method and return the result. Handle ask for password
 * when hitting password protected site.
 * Keep asking for password till user clicks cancel or enters correct
 * password. When 'remember password' is checked password is saved, if this
 * password and username are not correct clear them, if there are correct
 * they stay saved./*from   w  ww  . ja  va2  s.  c o m*/
 * @param httpClient the configured http client to use.
 * @param req the request for now it is get or post.
 * @param redirectHandler handles redirection, should we redirect and
 * the actual redirect.
 * @param parameters if we are redirecting we can use already filled
 * username and password in order to avoid asking the user twice.
 *
 * @return the result http entity.
 */
private static HttpEntity executeMethod(DefaultHttpClient httpClient, HttpRequestBase req,
        RedirectHandler redirectHandler, List<NameValuePair> parameters) throws Throwable {
    // do it when response (first execution) or till we are unauthorized
    HttpResponse response = null;
    int redirects = 0;
    while (response == null || response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED
            || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
        // if we were unauthorized, lets clear the method and recreate it
        // for new connection with new credentials.
        if (response != null && (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED
                || response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN)) {
            if (logger.isDebugEnabled())
                logger.debug("Will retry http connect and " + "credentials input as latest are not correct!");

            throw new AuthenticationException("Authorization needed");
        } else
            response = httpClient.execute(req);

        // if user click cancel no need to retry, stop trying
        if (!((HTTPCredentialsProvider) httpClient.getCredentialsProvider()).retry()) {
            if (logger.isDebugEnabled())
                logger.debug("User canceled credentials input.");
            break;
        }

        // check for post redirect as post redirects are not handled
        // automatically
        // RFC2616 (10.3 Redirection 3xx).
        // The second request (forwarded method) can only be a GET or HEAD.
        Header locationHeader = response.getFirstHeader("location");

        if (locationHeader != null && req instanceof HttpPost
                && (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY
                        || response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY
                        || response.getStatusLine().getStatusCode() == HttpStatus.SC_SEE_OTHER)
                && redirects < MAX_REDIRECTS) {
            HttpRequestBase oldreq = req;
            oldreq.abort();

            String newLocation = locationHeader.getValue();

            // lets ask redirection handler if any
            if (redirectHandler != null && redirectHandler.handleRedirect(newLocation, parameters)) {
                return null;
            }

            req = new HttpGet(newLocation);
            req.setParams(oldreq.getParams());
            req.setHeaders(oldreq.getAllHeaders());

            redirects++;
            response = httpClient.execute(req);
        }
    }

    // if we finally managed to login return the result.
    if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        return response.getEntity();
    }

    // is user has canceled no result needed.
    return null;
}

From source file:org.mariotaku.twidere.util.httpclient.HttpClientImpl.java

public HttpClientImpl(final HttpClientConfiguration conf) {
    this.conf = conf;
    final SchemeRegistry registry = new SchemeRegistry();
    final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY
            : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", factory, 443));
    final HttpParams params = new BasicHttpParams();
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient client = new DefaultHttpClient(cm, params);
    final HttpParams client_params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(client_params, conf.getHttpConnectionTimeout());
    HttpConnectionParams.setSoTimeout(client_params, conf.getHttpReadTimeout());

    if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(//from   ww w . j  av a  2s  . co m
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
        }
    }
    this.client = client;
}

From source file:org.mariotaku.twidere.util.net.HttpClientImpl.java

public HttpClientImpl(final HttpClientConfiguration conf) {
    this.conf = conf;
    final SchemeRegistry registry = new SchemeRegistry();
    final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY
            : SSLSocketFactory.getSocketFactory();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", factory, 443));
    final HttpParams params = new BasicHttpParams();
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient client = new DefaultHttpClient(cm, params);
    final HttpParams clientParams = client.getParams();
    HttpConnectionParams.setConnectionTimeout(clientParams, conf.getHttpConnectionTimeout());
    HttpConnectionParams.setSoTimeout(clientParams, conf.getHttpReadTimeout());

    if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(//from ww  w. ja v a 2  s  .c o  m
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
        }
    }
    this.client = client;
}

From source file:com.dwdesign.tweetings.util.httpclient.HttpClientImpl.java

public HttpClientImpl(final HttpClientConfiguration conf) {
    this.conf = conf;
    final SchemeRegistry registry = new SchemeRegistry();
    //final SSLSocketFactory factory = conf.isSSLErrorIgnored() ? TRUST_ALL_SSL_SOCKET_FACTORY : SSLSocketFactory
    //   .getSocketFactory();
    final SSLSocketFactory factory = TRUST_ALL_SSL_SOCKET_FACTORY;
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    registry.register(new Scheme("https", factory, 443));
    final HttpParams params = new BasicHttpParams();
    final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
    final DefaultHttpClient client = new DefaultHttpClient(cm, params);
    final HttpParams client_params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(client_params, conf.getHttpConnectionTimeout());
    HttpConnectionParams.setSoTimeout(client_params, conf.getHttpReadTimeout());

    if (conf.getHttpProxyHost() != null && !conf.getHttpProxyHost().equals("")) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        if (conf.getHttpProxyUser() != null && !conf.getHttpProxyUser().equals("")) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug("Proxy AuthPassword: "
                        + z_T4JInternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }/*  w  w  w .j  a va2 s.c  o  m*/
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
        }
    }
    this.client = client;
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST//from   ww  w. jav  a2  s. co  m
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */
private JSONObject executeQueryAuthPost(String query, SparqlResultTypes resultType) throws Exception {

    if (resultType == null) {
        resultType = getDefaultResultType();
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getPostURL());
    String resultsFormat = this.getContentType(resultType);
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    // add params
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("query", query));
    params.add(new BasicNameValuePair("format", resultsFormat));
    params.add(new BasicNameValuePair("default-graph-uri", this.dataset));

    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // finish new stuff

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity entity = response_http.getEntity();
    String responseTxt = EntityUtils.toString(entity, "UTF-8");

    // some diagnostic output
    if (responseTxt == null) {
        System.err.println("the response text was null!");
    }

    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    JSONObject resp;
    try {
        resp = (JSONObject) JSONValue.parse(responseTxt);
    } catch (Exception e) {
        entity.getContent().close();
        throw new Exception("Cannot parse query result into JSON: " + responseTxt);
    }

    if (resp == null) {
        System.err.println("the response could not be transformed into json");

        if (responseTxt.contains("Error")) {
            entity.getContent().close();
            throw new Exception(responseTxt);
        }
        entity.getContent().close();
        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(resp, resultType);
        entity.getContent().close();

        return procResp;
    }
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST//w w  w. jav  a2 s  .c om
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */

public JSONObject executeAuthUploadOwl(byte[] owl) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getUploadURL());
    String resultsFormat = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.addTextBody("graph-uri", this.dataset);
    builder.addBinaryBody("res-file", owl);
    HttpEntity entity = builder.build();
    httppost.setEntity(entity);

    /*  THIS IS THE MULTIPART FORMAT WE NEED TO SEND.
            
    Content-Type: multipart/form-data; boundary=---------------------------32932166721282
    Content-Length: 234
            
    -----------------------------32932166721282
    Content-Disposition: form-data; name="graph-uri"
            
    http://www.kdl.ge.com/changeme
    -----------------------------32932166721282
    Content-Disposition: form-data; name="res-file"; filename="employee.owl"
    Content-Type: application/octet-stream
            
    <rdf:RDF
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:owl="http://www.w3.org/2002/07/owl#"
        xmlns="http://kdl.ge.com/pd/employee#"
        xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
      .
      .
      .
    </rdf:RDF>
            
    -----------------------------32932166721282--
            
     */

    executeTestQuery();

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity resp_entity = response_http.getEntity();
    // get response with HTML tags removed
    String responseTxt = EntityUtils.toString(resp_entity, "UTF-8").replaceAll("\\<.*?>", " ");

    SimpleResultSet ret = new SimpleResultSet();

    if (responseTxt.trim().isEmpty()) {
        // success or bad login :-(
        ret.setSuccess(true);
    } else {
        ret.setSuccess(false);
        ret.addRationaleMessage(responseTxt);
    }
    resp_entity.getContent().close();
    return ret.toJson();
}

From source file:com.marklogic.client.example.util.Bootstrapper.java

/**
 * Programmatic invocation.//from  www.  j a v  a 2s. c om
 * @param configServer   the configuration server for creating the REST server
 * @param restServer   the specification of the REST server
 */
public void makeServer(ConfigServer configServer, RESTServer restServer)
        throws ClientProtocolException, IOException, FactoryConfigurationError {

    DefaultHttpClient client = new DefaultHttpClient();

    String host = configServer.getHost();
    int configPort = configServer.getPort();

    // TODO: SSL
    Authentication authType = configServer.getAuthType();
    if (authType != null) {
        List<String> prefList = new ArrayList<String>();
        if (authType == Authentication.BASIC)
            prefList.add(AuthPolicy.BASIC);
        else if (authType == Authentication.DIGEST)
            prefList.add(AuthPolicy.DIGEST);
        else
            throw new IllegalArgumentException("Unknown authentication type: " + authType.name());
        client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, prefList);

        String configUser = configServer.getUser();
        String configPassword = configServer.getPassword();
        client.getCredentialsProvider().setCredentials(new AuthScope(host, configPort),
                new UsernamePasswordCredentials(configUser, configPassword));
    }

    BasicHttpContext context = new BasicHttpContext();

    StringEntity content;
    try {
        content = new StringEntity(restServer.toXMLString());
    } catch (XMLStreamException e) {
        throw new IOException("Could not create payload to bootstrap server.");
    }
    content.setContentType("application/xml");

    HttpPost poster = new HttpPost("http://" + host + ":" + configPort + "/v1/rest-apis");
    poster.setEntity(content);

    HttpResponse response = client.execute(poster, context);
    //poster.releaseConnection();

    StatusLine status = response.getStatusLine();

    int statusCode = status.getStatusCode();
    String statusPhrase = status.getReasonPhrase();

    client.getConnectionManager().shutdown();

    if (statusCode >= 300) {
        throw new RuntimeException("Failed to create REST server: " + statusCode + " " + statusPhrase + "\n"
                + "Please check the server log for detail");
    }
}

From source file:com.cloudant.client.org.lightcouch.CouchDbClientAndroid.java

/**
 * @return {@link DefaultHttpClient} instance.
 *//*ww w  .  j  a v a 2s.  c o  m*/
@Override
HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
        final SchemeRegistry schemeRegistry = createRegistry(props);
        // Http params
        final HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, props.getConnectionTimeout());
        final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager(params, schemeRegistry);
        httpclient = new DefaultHttpClient(ccm, params);
        if (props.getProxyHost() != null) {
            HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        // basic authentication
        if (props.getUsername() != null && props.getPassword() != null) {
            httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()),
                    new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
            props.clearPassword();
        }
        registerInterceptors(httpclient);
    } catch (Exception e) {
        throw new IllegalStateException("Error Creating HTTP client. ", e);
    }
    return httpclient;
}