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.isisaddons.app.kitchensink.webapp.ro.tck.IsisWebServerRule.java

private RestfulClient getClient(final String path) {
    if (client == null) {
        final URI restfulUri = resolveUri(path);

        final ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager();
        final DefaultHttpClient httpClient = new DefaultHttpClient(threadSafeClientConnManager);

        if (user != null) {
            httpClient.getCredentialsProvider().setCredentials(new AuthScope("localhost", port),
                    new UsernamePasswordCredentials(user, pass));
        }/*from  w w  w  .ja v a2s. c o m*/

        client = new RestfulClient(restfulUri, httpClient);
    }
    return client;
}

From source file:org.fusesource.fabric.itests.smoke.FabricMavenProxyTest.java

@Test
public void testUpload() throws Exception {
    String featureLocation = System.getProperty("feature.location");
    System.out.println("Testing with feature from:" + featureLocation);
    System.err.println(executeCommand("fabric:create -n"));
    Set<Container> containers = ContainerBuilder.create(2).withName("maven").withProfiles("fabric")
            .assertProvisioningResult().build();

    FabricService fabricService = getFabricService();
    CuratorFramework curator = getCurator();
    List<String> children = getChildren(curator, ZkPath.MAVEN_PROXY.getPath("upload"));
    List<String> uploadUrls = new ArrayList<String>();
    for (String child : children) {
        String uploadeUrl = getSubstitutedPath(curator, ZkPath.MAVEN_PROXY.getPath("upload") + "/" + child);
        uploadUrls.add(uploadeUrl);/* ww w.j a va 2s  . c  om*/
    }
    //Pick a random maven proxy from the list.
    Random random = new Random();
    int index = random.nextInt(uploadUrls.size());
    String targetUrl = uploadUrls.get(index);

    String uploadUrl = targetUrl + "itest/itest/1.0/itest-1.0-features.xml";
    System.out.println("Using URI: " + uploadUrl);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(uploadUrl);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("admin", "admin"));

    FileNIOEntity entity = new FileNIOEntity(new File(featureLocation), "text/xml");
    put.setEntity(entity);
    HttpResponse response = client.execute(put);
    System.err.println("Response:" + response.getStatusLine());
    Assert.assertTrue(
            response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 202);

    System.err.println(
            executeCommand("fabric:profile-edit --repositories mvn:itest/itest/1.0/xml/features default"));
    System.err.println(executeCommand("fabric:profile-edit --features example-cbr default"));
    Provision.containerStatus(containers, PROVISION_TIMEOUT);
}

From source file:com.moarub.kipptapi.KipptAPIToken.java

@Override
protected StringBuilder doInBackground(String... u) {
    String username = u[0];//from   ww  w.  jav  a 2 s . co m
    String password = u[1];
    DefaultHttpClient client = new DefaultHttpClient();
    Credentials creds = new UsernamePasswordCredentials(username, password);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            creds);

    try {
        HttpGet request = new HttpGet(reqTokenUrl);

        HttpResponse response = client.execute(request);
        return ShareMoreUtils.getResponseString(response);
    } catch (ClientProtocolException e) {
        Log.d("ApiTokenFailure", "Can't fetch API Token " + e.getMessage());
        return null;
    } catch (IOException e) {
        Log.d("ApiTokenFailure", "Can't fetch API Token " + e.getMessage());
        return null;
    }
}

From source file:de.unioninvestment.eai.portal.portlet.crud.domain.model.authentication.RealmTest.java

@Test
public void shouldApplySettingsToHttpClient() {
    when(cryptorFactoryMock.getCryptor("pgp")).thenReturn(cryptorMock);
    AuthenticationRealmConfig config = createRealmConfig();
    when(preferencesMock.getValue("userKey", null)).thenReturn("user1");
    when(preferencesMock.getValue("passKey", null)).thenReturn("pass1");
    when(cryptorMock.decrypt("pass1")).thenReturn("pass2");
    Realm realm = new Realm(config, cryptorFactoryMock);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    realm.applyBasicAuthentication(httpClient);

    Credentials credentials = httpClient.getCredentialsProvider().getCredentials(AuthScope.ANY);
    assertThat(credentials.getUserPrincipal().getName(), is("user1"));
    assertThat(credentials.getPassword(), is("pass2"));
}

From source file:org.exoplatform.addons.es.client.ElasticClient.java

private HttpClient getHttpClient() {
    // Check if Basic Authentication need to be used
    if (StringUtils.isNotBlank(getEsUsernameProperty())) {
        DefaultHttpClient httpClient = new DefaultHttpClient(getClientConnectionManager());
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(getEsUsernameProperty(), getEsPasswordProperty()));
        LOG.debug("Basic authentication for ES activated with username = {} and password = {}",
                getEsUsernameProperty(), getEsPasswordProperty());
        return httpClient;
    } else {/*from  w w w.  j ava  2  s  . c  o m*/
        LOG.debug("Basic authentication for ES not activated");
        return new DefaultHttpClient(getClientConnectionManager());
    }
}

From source file:io.fabric8.itests.basic.FabricMavenProxyTest.java

@Test
public void testUpload() throws Exception {
    String featureLocation = System.getProperty("feature.location");
    System.out.println("Testing with feature from:" + featureLocation);
    System.err.println(executeCommand("fabric:create -n"));
    Set<Container> containers = ContainerBuilder.create(2).withName("maven").withProfiles("fabric")
            .assertProvisioningResult().build();
    try {/* w ww .j  a  va  2 s.  co m*/
        List<String> uploadUrls = new ArrayList<String>();
        ServiceProxy<CuratorFramework> curatorProxy = ServiceProxy.createServiceProxy(bundleContext,
                CuratorFramework.class);
        try {
            CuratorFramework curator = curatorProxy.getService();
            List<String> children = ZooKeeperUtils.getChildren(curator, ZkPath.MAVEN_PROXY.getPath("upload"));
            for (String child : children) {
                String uploadeUrl = ZooKeeperUtils.getSubstitutedPath(curator,
                        ZkPath.MAVEN_PROXY.getPath("upload") + "/" + child);
                uploadUrls.add(uploadeUrl);
            }
        } finally {
            curatorProxy.close();
        }
        //Pick a random maven proxy from the list.
        Random random = new Random();
        int index = random.nextInt(uploadUrls.size());
        String targetUrl = uploadUrls.get(index);

        String uploadUrl = targetUrl + "itest/itest/1.0/itest-1.0-features.xml";
        System.out.println("Using URI: " + uploadUrl);
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPut put = new HttpPut(uploadUrl);
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials("admin", "admin"));

        FileNIOEntity entity = new FileNIOEntity(new File(featureLocation), "text/xml");
        put.setEntity(entity);
        HttpResponse response = client.execute(put);
        System.err.println("Response:" + response.getStatusLine());
        Assert.assertTrue(response.getStatusLine().getStatusCode() == 200
                || response.getStatusLine().getStatusCode() == 202);

        System.err.println(
                executeCommand("fabric:profile-edit --repositories mvn:itest/itest/1.0/xml/features default"));
        System.err.println(executeCommand("fabric:profile-edit --features example-cbr default"));
        Provision.containerStatus(containers, PROVISION_TIMEOUT);
    } finally {
        ContainerBuilder.destroy(containers);
    }
}

From source file:org.deegree.protocol.ows.http.OwsHttpClientImpl.java

private void setCredentials(URL url, DefaultHttpClient client) {
    if (user != null) {
        client.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, pass));
    }/*from ww  w. j  av a 2s  .  c o m*/
}

From source file:org.picketlink.test.trust.tests.JBWSTokenIssuingLoginModuleUnitTestCase.java

private void assertApp(String appUri, String userName, String password, String httpHeader,
        String httpHeaderValue) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*w  w w. ja v a  2  s.  c o m*/
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(getServerAddress(), 8080), // localhost
                new UsernamePasswordCredentials(userName, password));

        HttpGet httpget = new HttpGet(getTargetURL(appUri)); // http://localhost:8080/test-app-1/test
        if (httpHeader != null)
            httpget.addHeader(httpHeader, httpHeaderValue);

        log.debug("executing request" + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);
        assertEquals("Http response has to finish with 'HTTP/1.1 200 OK'", 200,
                response.getStatusLine().getStatusCode());

        HttpEntity entity = response.getEntity();
        log.debug("Status line: " + response.getStatusLine());

        ByteArrayOutputStream baos = new ByteArrayOutputStream((int) entity.getContentLength());
        entity.writeTo(baos);
        String content = baos.toString();
        baos.close();

        if (log.isTraceEnabled()) {
            log.trace(content);
        }

        Pattern p = Pattern.compile("[.|\\s]*Credential\\[\\d\\]\\=SamlCredential\\[.*\\]", Pattern.DOTALL);
        Matcher m = p.matcher(content);
        boolean samlCredPresentOnSubject = m.find();
        assertTrue("SamlCredential on subject is missing for (" + appUri + ")", samlCredPresentOnSubject);

        EntityUtils.consume(entity);

    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.sonymobile.tools.gerrit.gerritevents.workers.rest.AbstractRestCommandJob.java

@Override
public void run() {
    ReviewInput reviewInput = createReview();

    String reviewEndpoint = resolveEndpointURL();

    HttpPost httpPost = createHttpPostEntity(reviewInput, reviewEndpoint);

    if (httpPost == null) {
        return;//w  w w  .ja  v  a2  s .c  om
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), config.getHttpCredentials());
    if (config.getGerritProxy() != null && !config.getGerritProxy().isEmpty()) {
        try {
            URL url = new URL(config.getGerritProxy());
            HttpHost proxy = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (MalformedURLException e) {
            logger.error("Could not parse proxy URL, attempting without proxy.", e);
            if (altLogger != null) {
                altLogger.print("ERROR Could not parse proxy URL, attempting without proxy. " + e.getMessage());
            }
        }
    }
    try {
        HttpResponse httpResponse = httpclient.execute(httpPost);
        String response = IOUtils.toString(httpResponse.getEntity().getContent(), "UTF-8");

        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            logger.error("Gerrit response: {}", httpResponse.getStatusLine().getReasonPhrase());
            if (altLogger != null) {
                altLogger.print("ERROR Gerrit response: " + httpResponse.getStatusLine().getReasonPhrase());
            }
        }
    } catch (Exception e) {
        logger.error("Failed to submit result to Gerrit", e);
        if (altLogger != null) {
            altLogger.print("ERROR Failed to submit result to Gerrit" + e.toString());
        }
    }
}