Example usage for org.apache.http.auth AuthScope AuthScope

List of usage examples for org.apache.http.auth AuthScope AuthScope

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope AuthScope.

Prototype

public AuthScope(final String host, final int port, final String realm) 

Source Link

Document

Creates a new credentials scope for the given host, port, realm, and any authentication scheme.

Usage

From source file:kuona.jenkins.analyser.JenkinsClient.java

/**
 * Create an authenticated Jenkins HTTP client
 *
 * @param uri      Location of the jenkins server (ex. http://localhost:8080)
 * @param username Username to use when connecting
 * @param password Password or auth token to use when connecting
 *//*ww w  .  j  a v a2 s  .  co m*/
public JenkinsClient(Project project, URI uri, String username, String password) {
    this(project, uri);
    if (isNotBlank(username)) {
        CredentialsProvider provider = client.getCredentialsProvider();
        AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm");
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(scope, credentials);

        localContext = new BasicHttpContext();
        localContext.setAttribute("preemptive-auth", new BasicScheme());
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
}

From source file:kuona.client.JenkinsHttpClient.java

/**
 * Create an authenticated Jenkins HTTP client
 *
 * @param uri      Location of the jenkins server (ex. http://localhost:8080)
 * @param username Username to use when connecting
 * @param password Password or auth token to use when connecting
 *///from ww w . j a v  a  2  s.c  om
public JenkinsHttpClient(Project project, URI uri, String username, String password) {
    this(project, uri);
    if (isNotBlank(username)) {
        CredentialsProvider provider = client.getCredentialsProvider();
        AuthScope scope = new AuthScope(uri.getHost(), uri.getPort(), "realm");
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        provider.setCredentials(scope, credentials);

        localContext = new BasicHttpContext();
        localContext.setAttribute("preemptive-auth", new BasicScheme());
        client.addRequestInterceptor(new PreemptiveAuth(), 0);
    }
}

From source file:org.opendaylight.defense4all.odl.controller.Connector.java

public void init() throws ExceptionControlApp {

    try {/* w  w w .  jav  a 2s .c o  m*/
        restPrefix = "http://" + odlOFC.ipAddrString + ":" + Integer.toString(odlOFC.port);

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

        //         HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
        //         restTemplate = new RestTemplate(factory);

        RestTemplateFactory.INSTANCE.setInsecureSsl(true);
        restTemplate = RestTemplateFactory.INSTANCE.createRestTemplate(authScope, credentials);

        if (restTemplate == null)
            throw new Exception("Failed to create restTemplate");
    } catch (Throwable e) {
        log.error("Failed to init connector to " + odlOFC.hostname, e);
        FMHolder.get().getHealthTracker().reportHealthIssue(HealthTracker.MINOR_HEALTH_ISSUE);
        throw new ExceptionControlApp("Failed to init connector to " + odlOFC.hostname, e);
    }
}

From source file:com.google.resting.rest.client.HttpContext.java

public HttpContext setAuthScope(String host, int port, String realm) {
    authScope = new AuthScope(host, port, realm);
    return this;
}

From source file:pydio.sdk.java.http.AjxpHttpClient.java

public void refreshCredentials(UsernamePasswordCredentials credentials) {
    this.getCredentialsProvider().setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);
}

From source file:org.opennms.opennms.pris.plugins.defaults.source.HttpRequisitionSource.java

@Override
public Object dump() throws Exception {
    Requisition requisition = null;//ww w  .  java  2  s  .  c o  m

    if (getUrl() != null) {
        HttpClientBuilder builder = HttpClientBuilder.create();

        // If username and password was found, inject the credentials
        if (getUserName() != null && getPassword() != null) {

            CredentialsProvider provider = new BasicCredentialsProvider();

            // Create the authentication scope
            AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

            // Create credential pair
            UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(getUserName(),
                    getPassword());

            // Inject the credentials
            provider.setCredentials(scope, credentials);

            // Set the default credentials provider
            builder.setDefaultCredentialsProvider(provider);
        }

        HttpClient client = builder.build();
        HttpGet request = new HttpGet(getUrl());
        HttpResponse response = client.execute(request);
        try {

            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));
            JAXBContext jaxbContext = JAXBContext.newInstance(Requisition.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            requisition = (Requisition) jaxbUnmarshaller.unmarshal(bufferedReader);

        } catch (JAXBException e) {
            LOGGER.error("The response did not contain a valid requisition as xml.", e);
        }
        LOGGER.debug("Got Requisition {}", requisition);
    } else {
        LOGGER.error("Parameter requisition.url is missing in requisition.properties");
    }
    if (requisition == null) {
        LOGGER.error("Requisition is null for unknown reasons");
        return null;
    }
    LOGGER.info("HttpRequisitionSource delivered for requisition '{}'", requisition.getNodes().size());
    return requisition;
}

From source file:org.janusgraph.diskstorage.es.rest.util.BasicAuthHttpClientConfigCallbackTest.java

@Test
public void testSetDefaultCredentialsProviderNoRealm() throws Exception {

    final CredentialsProvider cp = basicAuthTestBase("");

    // expected: will match any host and any realm
    final Credentials credentialsForRealm1 = cp
            .getCredentials(new AuthScope("dummyhost1", 1234, "dummyrealm1"));
    assertEquals(HTTP_USER, credentialsForRealm1.getUserPrincipal().getName());
    assertEquals(HTTP_PASSWORD, credentialsForRealm1.getPassword());
}

From source file:org.cvasilak.jboss.mobile.admin.net.TalkToJBossServerTask.java

public TalkToJBossServerTask(Context context, Server server, Callback callback) {
    this.context = context;
    this.client = CustomHTTPClient.getHttpClient();
    this.server = server;
    this.callback = callback;

    this.gjson = ((JBossAdminApplication) context.getApplicationContext()).getJSONParser();
    this.parser = new JsonParser();

    // enable digest authentication
    if (server.getUsername() != null && !server.getUsername().equals("")) {
        Credentials credentials = new UsernamePasswordCredentials(server.getUsername(), server.getPassword());

        client.getCredentialsProvider().setCredentials(
                new AuthScope(server.getHostname(), server.getPort(), AuthScope.ANY_REALM), credentials);
    }/* w ww.java  2s.c o m*/
}

From source file:no.back.springextensions.DBFactory.java

/**
 * Create a new {@link Database} connection
 * //from   w  ww.j  av  a 2  s  .com
 * @return initialized database
 * @throws IllegalStateException
 *             if not all required properties are set before attempting to
 *             initialize.
 */
Database initialize() {
    if (hostname == null)
        throw new IllegalStateException(
                "You must specify " + hostname + " before initializing a database connection");
    if (database == null)
        throw new IllegalStateException(
                "You must specify a " + database + " name before initializing a database connection");
    if (!(port >= 0 && port <= 65536))
        throw new IllegalStateException(
                "You must specify a " + port + " within 0-65536 before initializing a database connection");

    Server server = new ServerImpl(hostname, port);
    if (username != null && password != null) {
        Credentials credentials = new UsernamePasswordCredentials(username, password);
        AuthScope authScope = new AuthScope(hostname, port, null);
        server.setCredentials(authScope, credentials);
    }

    return new Database(server, database);
}

From source file:read.taz.TazDownloader.java

private void downloadFile() throws ClientProtocolException, IOException {
    if (tazFile.file.exists()) {
        Log.w(getClass().getSimpleName(), "File " + tazFile + " exists.");
        return;/*from ww  w  .j a  va2 s.  c  om*/
    }
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    HttpConnectionParams.setSoTimeout(httpParams, 15000);

    DefaultHttpClient client = new DefaultHttpClient(httpParams);

    Credentials defaultcreds = new UsernamePasswordCredentials(uname, passwd);

    client.getCredentialsProvider()
            .setCredentials(new AuthScope(/* FIXME DRY */"dl.taz.de", 80, AuthScope.ANY_REALM), defaultcreds);

    URI uri = tazFile.getDownloadURI();
    Log.d(getClass().getSimpleName(), "Downloading taz from " + uri);
    HttpGet get = new HttpGet(uri);
    HttpResponse response = client.execute(get);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("Download failed with HTTP Error" + response.getStatusLine().getStatusCode());
    }

    String contentType = response.getEntity().getContentType().getValue();
    if (contentType.startsWith("text/html")) {
        Log.d(getClass().getSimpleName(),
                "Content type: " + contentType + " encountered. Assuming a non exisiting file");

        ByteArrayOutputStream htmlOut = new ByteArrayOutputStream();
        response.getEntity().writeTo(htmlOut);
        String resp = new String(htmlOut.toByteArray());
        Log.d(getClass().getSimpleName(), "Response: " + resp);
        throw new FileNotFoundException("No taz found for date " + tazFile.date.getTime());
    } else {
        FileOutputStream tazOut = new FileOutputStream(tazFile.file);
        try {
            response.getEntity().writeTo(tazOut);
        } finally {
            tazOut.close();
        }
    }

    // InputStream docStream = response.getEntity().getContent();
    // FileOutputStream out = null;
    // try {
    // out = tazOut;
    // byte[] buf = new byte[4096];
    // for (int read = docStream.read(buf); read != -1; read = docStream
    // .read(buf)) {
    // out.write(buf, 0, read);
    // }
    // } finally {
    // docStream.close();
    // if (out != null) {
    // out.close();
    // }
    // }

}