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.opencastproject.remotetest.server.DigestAuthenticationTest.java

@Test
public void testBadDigestAuthenticatedGet() throws Exception {
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("matterhorn_system_account",
            "wrong_password");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
    HttpGet get = new HttpGet(BASE_URL + "/welcome.html");
    get.addHeader("X-Requested-Auth", "Digest");
    try {//  w  ww . j  a va  2s . c  om
        HttpResponse response = httpclient.execute(get);
        Assert.assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatusLine().getStatusCode());
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.networkmanagerapp.SettingBackgroundUploader.java

/**
 * Performs the file upload in the background
 * @throws FileNotFoundException, IOException, both caught internally. 
 * @param arg0 The intent to run in the background.
 *//*  ww  w  .  j  a va2 s.  c  om*/
@Override
protected void onHandleIntent(Intent arg0) {
    configFilePath = arg0.getStringExtra("CONFIG_FILE_PATH");
    key = arg0.getStringExtra("KEY");
    value = arg0.getStringExtra("VALUE");
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();
    try {
        fos = NetworkManagerMainActivity.getInstance().openFileOutput(this.configFilePath,
                Context.MODE_PRIVATE);
        String nameLine = "Name" + " = " + "\"" + this.key + "\"\n";
        String valueLine = "Value" + " = " + "\"" + this.value + "\"";
        fos.write(nameLine.getBytes());
        fos.write(valueLine.getBytes());
        fos.close();

        String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference",
                "");
        File f = new File(NetworkManagerMainActivity.getInstance().getFilesDir() + "/" + this.configFilePath);
        HttpHost targetHost = new HttpHost(
                PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference", "192.168.1.1"),
                1080, "http");
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("root", password));
        HttpPost httpPost = new HttpPost("http://"
                + PreferenceManager.getDefaultSharedPreferences(NetworkManagerMainActivity.getInstance())
                        .getString("ip_preference", "192.168.1.1")
                + ":1080/cgi-bin/upload.php");
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", new FileBody(f));
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);
        Log.d("upload", response.getStatusLine().toString());
    } catch (FileNotFoundException e) {
        Log.e("NETWORK_MANAGER_XU_FNFE", e.getLocalizedMessage());
    } catch (IOException e) {
        Log.e("NETWORK_MANAGER_XU_IOE", e.getLocalizedMessage());
    } finally {
        mNM.cancel(R.string.upload_service_started);
        stopSelf();
    }
}

From source file:org.opensuse.android.HttpCoreRestClient.java

private HttpClient connect() {
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(host, 80),
            new UsernamePasswordCredentials(username, password));
    return client;
}

From source file:org.sonar.plugins.buildstability.ci.api.AbstractServer.java

public void doLogin(DefaultHttpClient client) throws IOException {
    if (StringUtils.isNotBlank(getUsername()) && StringUtils.isNotBlank(getPassword())) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(getUsername(), getPassword()));
    }/*from w  w  w.  j a va2  s. com*/
}

From source file:com.mycompany.projecta.Test.java

public void Auth() throws Exception {

    // Credentials
    String username = "fernandoadp";
    String password = "ADP.2017";

    // Jenkins url
    String jenkinsUrl = "http://localhost:8080";

    // Build name
    String jobName = "ServiceA";

    // Build token
    String buildToken = "build";

    // Create your httpclient
    DefaultHttpClient client = new DefaultHttpClient();

    // Then provide the right credentials *******************
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new org.apache.http.auth.UsernamePasswordCredentials(username, password));
    //client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), (Credentials) new UsernamePasswordCredentials(username, password));

    // Generate BASIC scheme object and stick it to the execution context
    BasicScheme basicAuth = new BasicScheme();
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute("preemptive-auth", basicAuth);

    // Add as the first (because of the zero) request interceptor
    // It will first intercept the request and preemptively initialize the authentication scheme if there is not
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    // You get request that will start the build
    String getUrl = jenkinsUrl + "/job/" + jobName + "/build?token=" + buildToken;
    HttpGet get = new HttpGet(getUrl);

    try {//from w  ww .j  ava 2 s .c  om
        // Execute your request with the given context
        HttpResponse response = client.execute(get, context);
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:de.dan_nrw.web.WebClient.java

/**
 * Sends a http request and handles response using specified ResponseHandler
 * @param <T> Type of return/*from  w ww  .  j a v  a 2s. c om*/
 * @param uri URI to use
 * @param responseHandler Response handled used for handling response
 * @return
 * @throws IOException if response handling fails
 * @throws ProtocolException if request returns an error
 */
public <T> T sendRequest(URI uri, ResponseHandler<T> responseHandler) throws IOException, ProtocolException {
    HttpGet request = new HttpGet(uri);
    request.addHeader("User-agent", this.userAgent.getHeaderValue());

    DefaultHttpClient client = new DefaultHttpClient();

    if (this.credentials != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, this.credentials);
    }

    return client.execute(request, responseHandler);
}

From source file:bad.robot.http.apache.ApacheHttpClientBuilder.java

private void setupAuthentication(DefaultHttpClient client) {
    CredentialsProvider credentialsProvider = client.getCredentialsProvider();
    for (AuthenticatedHost authentication : authentications)
        credentialsProvider.setCredentials(authentication.scope, authentication.credentials);
}

From source file:org.opendaylight.defense4all.framework.cli.ControlappsConnector.java

public ControlappsConnector(String username, String password, String restSubPath) throws Exception {

    this.username = username;
    this.password = password;
    restPrefix = "http://" + RESTSERVICE_HOSTNAME + ":" + RESTSERVICE_PORT + restSubPath;

    try {/*from   w w  w .j  a va 2  s  . c om*/
        objMapper = new ObjectMapper();
        objMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); // Ignore unknown fields

        // set authentication for rest template
        AuthScope authScope = new AuthScope(RESTSERVICE_HOSTNAME, RESTSERVICE_PORT, AuthScope.ANY_REALM);
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(authScope, credentials);

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
        restTemplate = new RestTemplate(factory);
        if (restTemplate == null)
            throw new Exception("");
    } catch (Throwable e) {
        throw new Exception("Failed to initialize connection with controlapps. Is it up?");
    }
}

From source file:org.sonar.updatecenter.server.HttpDownloader.java

File downloadFile(URI fileURI, File toFile, String login, String password) {
    LOG.info("Download " + fileURI + " in " + toFile);
    DefaultHttpClient client = new DefaultHttpClient();
    try {//ww  w .  ja  v  a 2  s  . c  o m
        if (StringUtils.isNotBlank(login)) {
            client.getCredentialsProvider().setCredentials(new AuthScope(fileURI.getHost(), fileURI.getPort()),
                    new UsernamePasswordCredentials(login, password));
        }
        HttpGet httpget = new HttpGet(fileURI);
        byte[] data = client.execute(httpget, new ByteResponseHandler());
        if (data != null) {
            FileUtils.writeByteArrayToFile(toFile, data);
        }

    } catch (Exception e) {
        LOG.error("Fail to download " + fileURI + " to " + toFile, e);
        FileUtils.deleteQuietly(toFile);

    } finally {
        client.getConnectionManager().shutdown();
    }
    return toFile;
}

From source file:org.fusesource.fabric.itests.paxexam.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);/*from   w w  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.waitForContainerStatus(containers, PROVISION_TIMEOUT);
}