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:org.ryancutter.barcajolt.BarcaJolt.java

/**
 * Execute GET and collect response/* w ww  .ja v a  2  s  . c  om*/
 * 
 * @param getURL Requested GET operation. Will be appended to HOST.
 * 
 * @return JSONObject Results of GET operation. Will return null for HTTP status codes other
 * than 200.
 */
private JSONObject get(String getURL, boolean arrayResult) {
    // set up DefaultHttpClient and other objects
    StringBuilder builder = new StringBuilder();
    DefaultHttpClient client = new DefaultHttpClient();

    HttpHost host = new HttpHost(mHost, mPort, mProtocol);
    HttpGet get = new HttpGet(getURL);

    client.getCredentialsProvider().setCredentials(new AuthScope(host.getHostName(), host.getPort()),
            new UsernamePasswordCredentials(mUsername, mPassword));

    JSONObject jObject = null;
    try {
        // execute GET and collect results if valid response
        HttpResponse response = client.execute(host, get);

        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();
        if (statusCode == 200) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line);
            }

            try {
                // check if this is the result of BarcaJolt.getDBs(). since Cloudant returns a JSONArray 
                // rather than JSONObject for /_all_dbs requests, this class temporarily wraps the array
                // like {"dbs":["database1", "database2"]}. unwrapped in BarcaJolt.getDBs()
                if (arrayResult) {
                    builder.insert(0, "{'dbs' : ");
                    builder.append("}");
                }

                jObject = new JSONObject(builder.toString());
            } catch (JSONException e) {
                Log.e(TAG, "JSONException converting StringBuilder to JSONObject", e);
            }
        } else {
            // we only want to process 200's
            // TODO process non-200's in a more clever way
            Log.e(TAG, "Bad HttoResponse status: " + new Integer(statusCode).toString());
            return null;
        }
    } catch (ClientProtocolException e) {
        Log.e(TAG, "ClientProtocolException", e);
    } catch (IOException e) {
        Log.e(TAG, "DefaultHttpClient IOException", e);
    }

    // let go of resources
    client.getConnectionManager().shutdown();

    return jObject;
}

From source file:uk.org.openeyes.oink.itest.adapters.ITProxyAdapter.java

@Test
public void testCreatePatient() throws Exception {

    Thread.sleep(10000);/*from  ww w .  j a  v a2s. c o m*/

    OINKRequestMessage req = new OINKRequestMessage();
    req.setResourcePath("/Patient");
    req.setMethod(HttpMethod.POST);

    InputStream is = ITProxyAdapter.class.getResourceAsStream("/example-messages/fhir/patient2.json");
    Parser parser = new JsonParser();
    Patient p = (Patient) parser.parse(is);

    FhirBody body = new FhirBody(p);
    req.setBody(body);

    RabbitClient client = new RabbitClient(props.getProperty("rabbit.host"),
            Integer.parseInt(props.getProperty("rabbit.port")), props.getProperty("rabbit.vhost"),
            props.getProperty("rabbit.username"), props.getProperty("rabbit.password"));

    OINKResponseMessage resp = client.sendAndRecieve(req, props.getProperty("rabbit.routingKey"),
            props.getProperty("rabbit.defaultExchange"));

    assertEquals(201, resp.getStatus());

    String locationHeader = resp.getLocationHeader();
    assertNotNull(locationHeader);
    assertFalse(locationHeader.isEmpty());
    log.info("Posted to " + locationHeader);

    // Check exists on server
    // See if Patient exists
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("admin", "admin"));

    HttpGet httpGet = new HttpGet(locationHeader);
    httpGet.setHeader("Accept", "application/fhir+json");
    HttpResponse response1 = httpClient.execute(httpGet);
    assertEquals(200, response1.getStatusLine().getStatusCode());
}

From source file:nl.esciencecenter.octopus.webservice.JobLauncherServiceTest.java

@Test
public void testMacifyHttpClient() throws URISyntaxException {
    // FIXME Waiting for https://github.com/NLeSC/octopus/issues/38 to be resolved
    JobLauncherConfiguration config = sampleConfiguration();
    DefaultHttpClient httpClient = new DefaultHttpClient();

    JobLauncherService.macifyHttpClient(httpClient, config.getMacs());

    assertTrue("MAC Registered auth scheme", httpClient.getAuthSchemes().getSchemeNames().contains("mac"));

    MacCredential expected_creds = config.getMacs().get(0);
    AuthScope authscope = expected_creds.getAuthScope();
    Credentials creds = httpClient.getCredentialsProvider().getCredentials(authscope);
    assertEquals(expected_creds, creds);

    List<String> authSchemes = Collections.unmodifiableList(Arrays.asList(new String[] { MacScheme.SCHEME_NAME,
            AuthPolicy.SPNEGO, AuthPolicy.KERBEROS, AuthPolicy.NTLM, AuthPolicy.DIGEST, AuthPolicy.BASIC }));
    assertEquals(authSchemes, httpClient.getParams().getParameter(AuthPNames.TARGET_AUTH_PREF));
}

From source file:monakhv.samlib.http.HttpClientController.java

/**
 * Very row method to make http connection and begin download data Call only
 * by _getURL/*from  www.j av  a2  s  .co  m*/
 *
 * @param url URL to download
 * @param reader File to download to can be null
 * @return Download data if "f" is null
 * @throws IOException connection problem
 * @throws SamLibIsBusyException host return 503 status
 * @throws SamlibParseException host return status other then 200 and 503
 */
private String __getURL(URL url, PageReader reader)
        throws IOException, SamLibIsBusyException, SamlibParseException {

    HttpGet method = new HttpGet(url.toString());

    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, READ_TIMEOUT);

    DefaultHttpClient httpclient = new DefaultHttpClient(httpParams);

    if (pwd != null && scope != null) {
        httpclient.getCredentialsProvider().setCredentials(scope, pwd);
    }

    if (proxy != null) {
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    method.setHeader("User-Agent", USER_AGENT);
    method.setHeader("Accept-Charset", ENCODING);
    HttpResponse response;
    try {
        response = httpclient.execute(method);
        Log.d(DEBUG_TAG, "Status Response: " + response.getStatusLine().toString());
    } catch (NullPointerException ex) {
        Log.e(DEBUG_TAG, "Connection Error", ex);
        throw new IOException("Connection error: " + url.toString());
    }
    int status = response.getStatusLine().getStatusCode();

    if (status == 503) {
        httpclient.getConnectionManager().shutdown();
        throw new SamLibIsBusyException("Need to retryException ");
    }
    if (status != 200) {
        httpclient.getConnectionManager().shutdown();
        throw new SamlibParseException("Status code: " + status);
    }

    String result = reader.doReadPage(response.getEntity().getContent());
    httpclient.getConnectionManager().shutdown();
    return result;

}

From source file:nl.esciencecenter.osmium.JobLauncherServiceTest.java

@Test
public void testMacifyHttpClient() throws URISyntaxException {
    // FIXME Waiting for https://github.com/NLeSC/xenon/issues/38 to be resolved
    JobLauncherConfiguration config = sampleConfiguration();
    DefaultHttpClient httpClient = new DefaultHttpClient();

    JobLauncherService.macifyHttpClient(httpClient, config.getMacs());

    assertTrue("MAC Registered auth scheme", httpClient.getAuthSchemes().getSchemeNames().contains("mac"));

    MacCredential expected_creds = config.getMacs().get(0);
    AuthScope authscope = expected_creds.getAuthScope();
    Credentials creds = httpClient.getCredentialsProvider().getCredentials(authscope);
    assertEquals(expected_creds, creds);

    List<String> authSchemes = Collections.unmodifiableList(Arrays.asList(new String[] { MacScheme.SCHEME_NAME,
            AuthPolicy.SPNEGO, AuthPolicy.KERBEROS, AuthPolicy.NTLM, AuthPolicy.DIGEST, AuthPolicy.BASIC }));
    assertEquals(authSchemes, httpClient.getParams().getParameter(AuthPNames.TARGET_AUTH_PREF));
}

From source file:org.sonatype.nexus.testsuite.security.nexus4383.Nexus4383LogoutResourceIT.java

/**
 * 1.) Make a get request to set a cookie </BR>
 * 2.) verify cookie works (do not send basic auth) </BR>
 * 3.) do logout  </BR>//from w ww  .ja  va  2 s.  c  o m
 * 4.) repeat step 2 and expect failure.
 */
@Test
public void testLogout() throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "status";
    String logoutUrl = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "authentication/logout";

    Header userAgentHeader = new BasicHeader("User-Agent", "Something Stateful");

    // default useragent is: Jakarta Commons-HttpClient/3.1[\r][\n]
    DefaultHttpClient httpClient = new DefaultHttpClient();
    URI nexusBaseURI = new URI(url);
    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(),
            nexusBaseURI.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // HACK: Disable CSRFGuard support for now, its too problematic
    //String owaspQueryParams = null;
    HttpGet getMethod = new HttpGet(url);
    getMethod.addHeader(userAgentHeader);
    try {
        CloseableHttpResponse response = httpClient.execute(getMethod, localcontext);
        // HACK: Disable CSRFGuard support for now, its too problematic
        //Header owaspCsrfToken = response.getFirstHeader("OWASP_CSRFTOKEN");
        //assertThat(owaspCsrfToken, is(notNullValue()));
        //owaspQueryParams = "?" + owaspCsrfToken.getName() + "=" + owaspCsrfToken.getValue();
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    Assert.assertNotNull("Session Cookie not set", sessionCookie);

    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    // now with just the cookie
    httpClient.getCookieStore().addCookie(sessionCookie);
    // HACK: Disable CSRFGuard support for now, its too problematic
    //getMethod = new HttpGet(url + owaspQueryParams);
    getMethod = new HttpGet(url);
    try {
        Assert.assertEquals(httpClient.execute(getMethod).getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    // do logout
    // HACK: Disable CSRFGuard support for now, its too problematic
    //HttpGet logoutGetMethod = new HttpGet(logoutUrl + owaspQueryParams);
    HttpGet logoutGetMethod = new HttpGet(logoutUrl);
    try {
        final HttpResponse response = httpClient.execute(logoutGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
        Assert.assertEquals("OK", EntityUtils.toString(response.getEntity()));
    } finally {
        logoutGetMethod.reset();
    }

    // set cookie again
    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    httpClient.getCookieStore().addCookie(sessionCookie);
    HttpGet failedGetMethod = new HttpGet(url);
    try {
        final HttpResponse response = httpClient.execute(failedGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 401);
    } finally {
        failedGetMethod.reset();
    }
}

From source file:uk.org.openeyes.oink.itest.adapters.ITProxyAdapter.java

@Test
public void testPractitionerCreateUpdateAndDelete() throws Exception {

    // CREATE//from  w w w. j  av  a2s. c  o m
    OINKRequestMessage req = new OINKRequestMessage();
    req.setResourcePath("/Practitioner");
    req.setMethod(HttpMethod.POST);
    req.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp");
    InputStream is = ITProxyAdapter.class.getResourceAsStream("/example-messages/fhir/practitioner2.json");
    Parser parser = new JsonParser();
    Practitioner p = (Practitioner) parser.parse(is);
    FhirBody body = new FhirBody(p);
    req.setBody(body);

    RabbitClient client = new RabbitClient(props.getProperty("rabbit.host"),
            Integer.parseInt(props.getProperty("rabbit.port")), props.getProperty("rabbit.vhost"),
            props.getProperty("rabbit.username"), props.getProperty("rabbit.password"));

    OINKResponseMessage resp = client.sendAndRecieve(req, props.getProperty("rabbit.routingKey"),
            props.getProperty("rabbit.defaultExchange"));

    assertEquals(201, resp.getStatus());
    String locationHeader = resp.getLocationHeader();
    assertNotNull(locationHeader);
    assertFalse(locationHeader.isEmpty());
    log.info("Posted to " + locationHeader);

    // See if Patient exists
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("admin", "admin"));

    HttpGet httpGet = new HttpGet(locationHeader);
    httpGet.setHeader("Accept", "application/fhir+json");
    HttpResponse response1 = httpClient.execute(httpGet);
    assertEquals(200, response1.getStatusLine().getStatusCode());

    // UPDATE
    String id = getIdFromLocationHeader("Practitioner", locationHeader);
    OINKRequestMessage updateRequest = new OINKRequestMessage();
    updateRequest.setResourcePath("/Practitioner/" + id);
    updateRequest.setMethod(HttpMethod.PUT);
    updateRequest.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp");
    p.getTelecom().get(0).setValueSimple("0222 222 2222");
    updateRequest.setBody(new FhirBody(p));

    OINKResponseMessage updateResponse = client.sendAndRecieve(updateRequest,
            props.getProperty("rabbit.routingKey"), props.getProperty("rabbit.defaultExchange"));
    assertEquals(200, updateResponse.getStatus());

    // DELETE
    OINKRequestMessage deleteRequest = new OINKRequestMessage();
    deleteRequest.setResourcePath("/Practitioner/" + id);
    deleteRequest.setMethod(HttpMethod.DELETE);
    deleteRequest.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Practitioner/Gp");

    OINKResponseMessage deleteResponse = client.sendAndRecieve(deleteRequest,
            props.getProperty("rabbit.routingKey"), props.getProperty("rabbit.defaultExchange"));
    assertEquals(204, deleteResponse.getStatus());

}

From source file:uk.org.openeyes.oink.itest.adapters.ITProxyAdapter.java

@Test
public void testOrganizationCreateUpdateAndDelete() throws Exception {

    // CREATE/*w  w w  . ja v a2  s.  c  o  m*/
    // http://192.168.1.100:80/api/Organization?_profile=http://openeyes.org.uk/fhir/1.7.0/profile/Organization/Practice
    OINKRequestMessage req = new OINKRequestMessage();
    req.setResourcePath("/Organization");
    req.setMethod(HttpMethod.POST);
    req.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Organization/Practice");
    InputStream is = ITProxyAdapter.class.getResourceAsStream("/example-messages/fhir/organization.json");
    Parser parser = new JsonParser();
    Organization p = (Organization) parser.parse(is);
    FhirBody body = new FhirBody(p);
    req.setBody(body);

    RabbitClient client = new RabbitClient(props.getProperty("rabbit.host"),
            Integer.parseInt(props.getProperty("rabbit.port")), props.getProperty("rabbit.vhost"),
            props.getProperty("rabbit.username"), props.getProperty("rabbit.password"));

    OINKResponseMessage resp = client.sendAndRecieve(req, props.getProperty("rabbit.routingKey"),
            props.getProperty("rabbit.defaultExchange"));

    assertEquals(201, resp.getStatus());
    String locationHeader = resp.getLocationHeader();
    assertNotNull(locationHeader);
    assertFalse(locationHeader.isEmpty());
    log.info("Posted to " + locationHeader);

    // See if Patient exists
    DefaultHttpClient httpClient = new DefaultHttpClient();

    httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("admin", "admin"));

    HttpGet httpGet = new HttpGet(locationHeader);
    httpGet.setHeader("Accept", "application/fhir+json");
    HttpResponse response1 = httpClient.execute(httpGet);
    assertEquals(200, response1.getStatusLine().getStatusCode());

    // UPDATE
    String id = getIdFromLocationHeader("Organization", locationHeader);
    OINKRequestMessage updateRequest = new OINKRequestMessage();
    updateRequest.setResourcePath("/Organization/" + id);
    updateRequest.setMethod(HttpMethod.PUT);
    updateRequest.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Organization/Practice");
    p.getTelecom().get(0).setValueSimple("0222 222 2222");
    updateRequest.setBody(new FhirBody(p));

    OINKResponseMessage updateResponse = client.sendAndRecieve(updateRequest,
            props.getProperty("rabbit.routingKey"), props.getProperty("rabbit.defaultExchange"));
    assertEquals(200, updateResponse.getStatus());

    // DELETE
    OINKRequestMessage deleteRequest = new OINKRequestMessage();
    deleteRequest.setResourcePath("/Organization/" + id);
    deleteRequest.setMethod(HttpMethod.DELETE);
    deleteRequest.addProfile("http://openeyes.org.uk/fhir/1.7.0/profile/Organization/Practice");

    OINKResponseMessage deleteResponse = client.sendAndRecieve(deleteRequest,
            props.getProperty("rabbit.routingKey"), props.getProperty("rabbit.defaultExchange"));
    assertEquals(204, deleteResponse.getStatus());

}

From source file:org.commonjava.couch.io.CouchHttpClient.java

@PostConstruct
private void setupClient() {
    final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager();
    ccm.setMaxTotal(config.getMaxConnections());

    final DefaultHttpClient c = new DefaultHttpClient(ccm);

    if (config.getDatabaseUser() != null) {
        final AuthScope scope = new AuthScope(config.getDatabaseHost(), config.getDatabasePort());
        final UsernamePasswordCredentials cred = new UsernamePasswordCredentials(config.getDatabaseUser(),
                config.getDatabasePassword());

        c.getCredentialsProvider().setCredentials(scope, cred);
    }/*from w ww  . j  ava 2 s.  com*/

    client = c;
}

From source file:org.fcrepo.test.api.TestAdminAPI.java

private HttpClient getClient(boolean auth) {
    DefaultHttpClient client = new PreemptiveAuth();
    if (auth) {//from  w w  w . j a  v  a 2  s .  c  om
        client.getCredentialsProvider().setCredentials(new AuthScope(getHost(), Integer.valueOf(getPort())),
                new UsernamePasswordCredentials(getUsername(), getPassword()));
    }
    return client;
}