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) 

Source Link

Document

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

Usage

From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.HttpPreemptiveAuthInterceptor.java

@Override
public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    // If not auth scheme has been initialized yet
    if (authState.getAuthScheme() != null) {
        return;/*from  w  w  w  . j  av a  2  s.co  m*/
    }

    // fetch credentials
    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());

    // Obtain credentials matching the target host
    Credentials creds = credsProvider.getCredentials(authScope);

    if (creds == null) {
        log.warn("no credentials provided for " + authScope);
        return;
    }

    authState.setAuthScheme(authScheme);
    authState.setCredentials(creds);
}

From source file:org.commonjava.redhat.maven.rv.util.InputUtils.java

public static File getFile(final String location, final File downloadsDir, final boolean deleteExisting)
        throws ValidationException {
    if (client == null) {
        final DefaultHttpClient hc = new DefaultHttpClient();
        hc.setRedirectStrategy(new DefaultRedirectStrategy());

        final String proxyHost = System.getProperty("http.proxyHost");
        final int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "-1"));

        if (proxyHost != null && proxyPort > 0) {
            final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
            hc.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
        }//from  w w  w. j  a  va  2s. co  m

        client = hc;
    }

    File result = null;

    if (location.startsWith("http")) {
        LOGGER.info("Downloading: '" + location + "'...");

        try {
            final URL url = new URL(location);
            final String userpass = url.getUserInfo();
            if (!isEmpty(userpass)) {
                final AuthScope scope = new AuthScope(url.getHost(), url.getPort());
                final Credentials creds = new UsernamePasswordCredentials(userpass);

                client.getCredentialsProvider().setCredentials(scope, creds);
            }
        } catch (final MalformedURLException e) {
            LOGGER.error("Malformed URL: '" + location + "'", e);
            throw new ValidationException("Failed to download: %s. Reason: %s", e, location, e.getMessage());
        }

        final File downloaded = new File(downloadsDir, new File(location).getName());
        if (deleteExisting && downloaded.exists()) {
            downloaded.delete();
        }

        if (!downloaded.exists()) {
            HttpGet get = new HttpGet(location);
            OutputStream out = null;
            try {
                HttpResponse response = client.execute(get);
                // Work around for scenario where we are loading from a server
                // that does a refresh e.g. gitweb
                if (response.containsHeader("Cache-control")) {
                    LOGGER.info("Waiting for server to generate cache...");
                    try {
                        Thread.sleep(5000);
                    } catch (final InterruptedException e) {
                    }
                    get.abort();
                    get = new HttpGet(location);
                    response = client.execute(get);
                }
                final int code = response.getStatusLine().getStatusCode();
                if (code == 200) {
                    final InputStream in = response.getEntity().getContent();
                    out = new FileOutputStream(downloaded);

                    copy(in, out);
                } else {
                    LOGGER.info(String.format("Received status: '%s' while downloading: %s",
                            response.getStatusLine(), location));

                    throw new ValidationException("Received status: '%s' while downloading: %s",
                            response.getStatusLine(), location);
                }
            } catch (final ClientProtocolException e) {
                throw new ValidationException("Failed to download: '%s'. Error: %s", e, location,
                        e.getMessage());
            } catch (final IOException e) {
                throw new ValidationException("Failed to download: '%s'. Error: %s", e, location,
                        e.getMessage());
            } finally {
                closeQuietly(out);
                get.abort();
            }
        }

        result = downloaded;
    } else {
        LOGGER.info("Using local file: '" + location + "'...");

        result = new File(location);
    }

    return result;
}

From source file:com.jwm123.loggly.reporter.Client.java

public List<Map<String, Object>> getReport() throws Exception {
    final Integer rows = 500;
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(config.getAccount() + ".loggly.com", 80),
            new UsernamePasswordCredentials(config.getUsername(), config.getPassword()));
    CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    String url = "http://" + config.getAccount() + ".loggly.com/api/search?rows=" + rows + "&q="
            + URLEncoder.encode(query, "UTF8");
    if (StringUtils.isNotBlank(from)) {
        url += "&from=" + URLEncoder.encode(from, "UTF8");
    }/*from  w w  w. j  av a 2 s. com*/
    if (StringUtils.isNotBlank(to)) {
        url += "&until=" + URLEncoder.encode(to, "UTF8");
    }
    HttpGet get = new HttpGet(url);
    CloseableHttpResponse resp = null;
    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    Integer offset = 0 - rows;
    Integer numFound = 0;
    try {
        do {
            offset += rows;
            try {
                get = new HttpGet(url + "&start=" + offset);

                resp = client.execute(get);
                if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    String response = EntityUtils.toString(resp.getEntity());
                    Map<String, Object> responseMap = new Gson().fromJson(response,
                            new TypeToken<Map<String, Object>>() {
                            }.getType());
                    if (responseMap.containsKey("numFound")) {
                        numFound = ((Number) responseMap.get("numFound")).intValue();
                    }
                    if (responseMap.containsKey("data")) {
                        Collection<?> dataCol = (Collection<?>) responseMap.get("data");
                        if (!dataCol.isEmpty()) {
                            for (Object dataItem : dataCol) {
                                if (dataItem instanceof Map) {
                                    results.add((Map<String, Object>) dataItem);
                                }
                            }
                        }
                    }
                } else {
                    System.out.println("status: " + resp.getStatusLine().getStatusCode() + " Response: ["
                            + EntityUtils.toString(resp.getEntity()) + "]");
                    break;
                }
            } finally {
                get.releaseConnection();
                IOUtils.closeQuietly(resp);
            }
        } while (numFound >= offset + rows);
    } finally {
        IOUtils.closeQuietly(client);
    }

    return results;
}

From source file:org.sonatype.nexus.apachehttpclient.PreemptiveAuthHttpRequestInterceptor.java

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    final HttpClientContext clientContext = HttpClientContext.adapt(context);
    final AuthState authState = clientContext.getTargetAuthState();
    if (authState.getAuthScheme() == null) {
        final CredentialsProvider credsProvider = clientContext.getCredentialsProvider();
        final HttpHost targetHost = clientContext.getTargetHost();
        final Credentials creds = credsProvider
                .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
        if (creds != null) {
            authState.update(new BasicScheme(), creds);
        }/* w w  w  .j  av  a  2  s.  c o  m*/
    }
}

From source file:org.uberfire.provisioning.wildfly.runtime.provider.extras.Wildfly10RemoteClient.java

public int deploy(String user, String password, String host, int port, String filePath) {

    // the digest auth backend
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(user, password));

    CloseableHttpClient httpclient = custom().setDefaultCredentialsProvider(credsProvider).build();

    HttpPost post = new HttpPost("http://" + host + ":" + port + "/management-upload");

    post.addHeader("X-Management-Client-Name", "HAL");

    // the file to be uploaded
    File file = new File(filePath);
    FileBody fileBody = new FileBody(file);

    // the DMR operation
    ModelNode operation = new ModelNode();
    operation.get("address").add("deployment", file.getName());
    operation.get("operation").set("add");
    operation.get("runtime-name").set(file.getName());
    operation.get("enabled").set(true);
    operation.get("content").add().get("input-stream-index").set(0); // point to the multipart index used

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {/*from   w  w w  .  ja v  a 2s . co  m*/
        operation.writeBase64(bout);
    } catch (IOException ex) {
        getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex);
    }

    // the multipart
    MultipartEntityBuilder builder = create();
    builder.setMode(BROWSER_COMPATIBLE);
    builder.addPart("uploadFormElement", fileBody);
    builder.addPart("operation",
            new ByteArrayBody(bout.toByteArray(), create("application/dmr-encoded"), "blob"));
    HttpEntity entity = builder.build();

    //entity.writeTo(System.out);
    post.setEntity(entity);

    try {
        HttpResponse response = httpclient.execute(post);

        out.println(">>> Deploying Response Entity: " + response.getEntity());
        out.println(">>> Deploying Response Satus: " + response.getStatusLine().getStatusCode());
        return response.getStatusLine().getStatusCode();
    } catch (IOException ex) {
        ex.printStackTrace();
        getLogger(Wildfly10RemoteClient.class.getName()).log(SEVERE, null, ex);
    }
    return -1;
}

From source file:de.escidoc.core.http.PreemtiveAuthHttpRequestInterceptor.java

@Override
public void process(final HttpRequest httpRequest, final HttpContext httpContext)
        throws HttpException, IOException {
    final AuthState authState = (AuthState) httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
    final CredentialsProvider credsProvider = (CredentialsProvider) httpContext
            .getAttribute(ClientContext.CREDS_PROVIDER);
    final HttpHost targetHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    // If not auth scheme has been initialized yet
    if (authState.getAuthScheme() == null) {
        final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        final Credentials creds = credsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        if (creds != null) {
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }/*from   www . ja  v a  2 s . co m*/
    }
}

From source file:com.marklogic.client.test.util.TestServerBootstrapper.java

private void deleteRestServer() throws ClientProtocolException, IOException {

    DefaultHttpClient client = new DefaultHttpClient();

    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
            new UsernamePasswordCredentials(username, password));

    HttpDelete delete = new HttpDelete(
            "http://" + host + ":8002/v1/rest-apis/java-unittest?include=modules&include=content");

    client.execute(delete);//w w w  .j a v a2s.co  m
}

From source file:org.gbif.utils.PreemptiveAuthenticationInterceptor.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    LOG.debug(request.getRequestLine().toString());

    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    CredentialsProvider credsProvider = (CredentialsProvider) context
            .getAttribute(ClientContext.CREDS_PROVIDER);
    HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

    // If not auth scheme has been initialized yet
    if (authState.getAuthScheme() == null && credsProvider != null) {
        AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
        // Obtain credentials matching the target host
        Credentials creds = credsProvider.getCredentials(authScope);
        // If found, generate BasicScheme preemptively
        if (creds != null) {
            LOG.debug("Authentication used for scope " + authScope.getHost());
            authState.setAuthScheme(new BasicScheme());
            authState.setCredentials(creds);
        }/*from w w  w  . ja  va 2  s  . co  m*/
    }
}

From source file:io.cloudslang.content.httpclient.build.auth.CredentialsProviderBuilderTest.java

@Test
public void createKerberosCredentialsProvider() {
    CredentialsProvider credentialsProvider = getCredentialsProvider(AuthSchemes.KERBEROS);
    Credentials credentials = credentialsProvider.getCredentials(new AuthScope("host", 80));

    assertThat(credentials, instanceOf(Credentials.class));
}

From source file:org.datacleaner.monitor.cluster.HttpClusterManagerFactory.java

@Override
public ClusterManager getClusterManager(TenantIdentifier tenant) {
    final DefaultHttpClient httpClient = new DefaultHttpClient(new PoolingClientConnectionManager());
    if (username != null && password != null) {
        final CredentialsProvider credentialsProvider = httpClient.getCredentialsProvider();
        final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
        final List<String> authpref = new ArrayList<String>();
        authpref.add(AuthPolicy.BASIC);//from   w  w  w.j  a  va2 s . co m
        authpref.add(AuthPolicy.DIGEST);
        httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
        credentialsProvider.setCredentials(new AuthScope(null, -1), credentials);
    }

    // use the server list
    final List<String> finalEndpoints = new ArrayList<String>();
    for (String endpoint : slaveServerUrls) {
        if (!endpoint.endsWith("/")) {
            endpoint = endpoint + "/";
        }
        endpoint = endpoint + "repository/" + tenant.getId() + "/cluster_slave_endpoint";
        finalEndpoints.add(endpoint);
    }

    return new HttpClusterManager(httpClient, finalEndpoints);
}