Example usage for org.apache.http.client AuthCache put

List of usage examples for org.apache.http.client AuthCache put

Introduction

In this page you can find the example usage for org.apache.http.client AuthCache put.

Prototype

void put(HttpHost host, AuthScheme authScheme);

Source Link

Usage

From source file:biocode.fims.ezid.EzidService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EzidService,
 * and so subsequent calls using this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 *
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 *
 * @throws EzidException if authentication fails for any reason
 *//*from   w ww.ja  v a2 s  .  c  om*/
public void login(String username, String password) throws EzidException {
    String msg;
    try {
        URI serviceUri = new URI(LOGIN_SERVICE);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.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);
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        //System.out.println("authCache: " + authCache.toString());

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(LOGIN_SERVICE);
        body = httpClient.execute(httpget, handler, localcontext);
        String message = new String(body);
        msg = parseIdentifierResponse(message);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        /*
                org.apache.http.client.CookieStore cookieStore = httpClient.getCookieStore();
        System.out.println("\n\nCookies : ");
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Cookie: " + cookies.get(i));
        } */

    } catch (URISyntaxException e) {
        //System.out.println("URI SyntaxError Exception in LOGIN");
        throw new EzidException("Bad syntax for uri: " + LOGIN_SERVICE, e);
    } catch (ClientProtocolException e) {
        //System.out.println("ClientProtocol Exception in LOGIN");
        throw new EzidException(e);
    } catch (IOException e) {
        //System.out.println("IO Exception in LOGIN");
        throw new EzidException(e);
    }
    //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString());
}

From source file:ezid.EZIDService.java

/**
 * Log into the EZID service using account credentials provided by EZID. The cookie
 * returned by EZID is cached in a local CookieStore for the duration of the EZIDService,
 * and so subsequent calls using this instance of the service will function as
 * fully authenticated. An exception is thrown if authentication fails.
 *
 * @param username to identify the user account from EZID
 * @param password the secret password for this account
 *
 * @throws EZIDException if authentication fails for any reason
 *///from w  ww  .java 2s  .  co m
public void login(String username, String password) throws EZIDException {
    this.username = username;
    this.password = password;
    String msg;
    try {
        URI serviceUri = new URI(LOGIN_SERVICE);
        HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.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);
        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        //System.out.println("authCache: " + authCache.toString());

        ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
            public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                } else {
                    return null;
                }
            }
        };
        byte[] body = null;

        HttpGet httpget = new HttpGet(LOGIN_SERVICE);
        body = httpclient.execute(httpget, handler, localcontext);
        String message = new String(body);
        msg = parseIdentifierResponse(message);

        // DEBUGGING ONLY, CAN COMMENT OUT WHEN FULLY WORKING....
        /*
                org.apache.http.client.CookieStore cookieStore = httpclient.getCookieStore();
        System.out.println("\n\nCookies : ");
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Cookie: " + cookies.get(i));
        } */

    } catch (URISyntaxException e) {
        //System.out.println("URI SyntaxError Exception in LOGIN");
        throw new EZIDException("Bad syntax for uri: " + LOGIN_SERVICE, e);
    } catch (ClientProtocolException e) {
        //System.out.println("ClientProtocol Exception in LOGIN");
        throw new EZIDException(e);
    } catch (IOException e) {
        //System.out.println("IO Exception in LOGIN");
        throw new EZIDException(e);
    }
    //System.out.println("Seems to be a successful LOGIN, msg= " + msg.toString());
}

From source file:edu.lternet.pasta.doi.EzidRegistrar.java

/**
 * Make the DOI obsolete by setting the EZID metadata field "_status" to
 * "unavailable".//w ww.j  a v  a  2s  .c om
 * 
 * @param doi The DOI to obsolete
 * @throws EzidException
 */
public void obsoleteDoi(String doi) throws EzidException {

    HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    String url = this.getEzidUrl("/id/" + doi);

    StringBuffer metadata = new StringBuffer("");
    metadata.append("_status: unavailable | withdrawn by author\n");

    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("Content-type", "text/plain");
    HttpEntity stringEntity = null;
    Integer statusCode = null;
    String entityString = null;

    try {
        stringEntity = new StringEntity(metadata.toString());
        httpPost.setEntity(stringEntity);
        HttpResponse httpResponse = httpClient.execute(httpHost, httpPost, context);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        HttpEntity httpEntity = httpResponse.getEntity();
        entityString = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    logger.info("obsoleteDoi: " + entityString);

    if (statusCode != HttpStatus.SC_OK) {
        String gripe = "DOI obsoletion failed for: " + doi;
        throw new EzidException(gripe);
    }

}

From source file:edu.lternet.pasta.doi.EzidRegistrar.java

/**
 * Registers the resource DOI based on the DataCite metadata object.
 * //ww w.ja v  a 2 s. c o m
 * @throws EzidException
 */
public void registerDataCiteMetadata() throws EzidException {

    if (this.dataCiteMetadata == null) {
        String gripe = "registerDataCiteMetadata: DataCite metadata object is null.";
        throw new EzidException(gripe);
    }

    HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // Generate BASIC scheme object and add it to the local auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    String doi = this.dataCiteMetadata.getDigitalObjectIdentifier().getDoi();
    String url = this.getEzidUrl("/id/" + doi);
    StringBuffer metadata = new StringBuffer("");
    metadata.append("datacite: " + this.dataCiteMetadata.toDataCiteXml() + "\n");
    metadata.append("_target: " + this.dataCiteMetadata.getLocationUrl() + "\n");
    HttpPut httpPut = new HttpPut(url);
    httpPut.setHeader("Content-type", "text/plain");
    HttpEntity stringEntity = null;
    Integer statusCode = null;
    String entityString = null;

    try {
        stringEntity = new StringEntity(metadata.toString());
        httpPut.setEntity(stringEntity);
        HttpResponse httpResponse = httpClient.execute(httpHost, httpPut, context);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        HttpEntity httpEntity = httpResponse.getEntity();
        entityString = EntityUtils.toString(httpEntity);
    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    logger.info("registerDataCiteMetadata: " + this.dataCiteMetadata.getLocationUrl() + "\n" + entityString);

    // Test for DOI collision or DOI registration failure
    if ((statusCode == HttpStatus.SC_BAD_REQUEST) && (entityString != null)
            && (entityString.contains("identifier already exists"))) {
        String gripe = "identifier already exists";
        throw new EzidException(gripe);
    } else if (statusCode != HttpStatus.SC_CREATED) {
        logger.error(this.dataCiteMetadata.toDataCiteXml());
        String gripe = "DOI registration failed for: " + doi;
        throw new EzidException(gripe);
    }

}

From source file:org.fao.geonet.utils.AbstractHttpRequest.java

protected ClientHttpResponse doExecute(final HttpRequestBase httpMethod) throws IOException {
    return requestFactory.execute(httpMethod, new Function<HttpClientBuilder, Void>() {
        @Nullable//w ww . j a  v a2  s  .com
        @Override
        public Void apply(@Nonnull HttpClientBuilder input) {
            final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            if (credentials != null) {
                final URI uri = httpMethod.getURI();
                HttpHost hh = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
                credentialsProvider.setCredentials(new AuthScope(hh), credentials);

                // Preemptive authentication
                if (isPreemptiveBasicAuth()) {
                    // Create AuthCache instance
                    AuthCache authCache = new BasicAuthCache();
                    // Generate BASIC scheme object and add it to the local auth cache
                    BasicScheme basicAuth = new BasicScheme();
                    authCache.put(hh, basicAuth);

                    // Add AuthCache to the execution context
                    httpClientContext = HttpClientContext.create();
                    httpClientContext.setCredentialsProvider(credentialsProvider);
                    httpClientContext.setAuthCache(authCache);
                } else {
                    input.setDefaultCredentialsProvider(credentialsProvider);
                }
            } else {
                input.setDefaultCredentialsProvider(credentialsProvider);
            }

            if (useProxy) {
                final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                input.setProxy(proxy);
                if (proxyCredentials != null) {
                    credentialsProvider.setCredentials(new AuthScope(proxy), proxyCredentials);
                }
            }
            input.setRedirectStrategy(new LaxRedirectStrategy());
            return null;
        }
    }, this);
}

From source file:edu.lternet.pasta.doi.EzidRegistrar.java

/**
 * Login to the EZID web service API system and return a valid session
 * identifier.//from  w ww  .jav a 2s . c  o m
 * 
 * @return The EZID session id
 * @throws EzidException
 */
public void login() throws EzidException {

    String sessionId = null;

    /*
     * The following set of code sets up Preemptive Authentication for the HTTP
     * CLIENT and is done so at the warning stated within the Apache
     * Http-Components Client tutorial here:
     * http://hc.apache.org/httpcomponents-
     * client-ga/tutorial/html/authentication.html#d5e1031
     */

    HttpHost httpHost = new HttpHost(this.host, Integer.valueOf(this.port), this.protocol);
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    AuthScope authScope = new AuthScope(httpHost.getHostName(), httpHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.ezidUser, this.ezidPassword);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(authScope, credentials);

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    // Generate BASIC scheme object and add it to the auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(httpHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    HttpGet httpGet = new HttpGet(this.getEzidUrl("/login"));

    HttpResponse response = null;
    Header[] headers = null;
    Integer statusCode = null;

    try {

        response = httpClient.execute(httpHost, httpGet, context);
        headers = response.getAllHeaders();
        statusCode = (Integer) response.getStatusLine().getStatusCode();
        logger.info("STATUS: " + statusCode.toString());

    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        logger.error(e);
        e.printStackTrace();
    } catch (IOException e) {
        logger.error(e);
        e.printStackTrace();
    } finally {
        closeHttpClient(httpClient);
    }

    if (statusCode == HttpStatus.SC_OK) {

        String headerName = null;
        String headerValue = null;

        // Loop through all headers looking for the "Set-Cookie" header.
        for (int i = 0; i < headers.length; i++) {
            headerName = headers[i].getName();

            if (headerName.equals("Set-Cookie")) {
                headerValue = headers[i].getValue();
                sessionId = this.getSessionId(headerValue);
                logger.info("Session: " + sessionId);
            }

        }

    } else {
        String gripe = "login: failed EZID login.";
        throw new EzidException(gripe);
    }

    this.sessionId = sessionId;

}

From source file:be.cytomine.client.HttpClient.java

public void connect(String url, String username, String password) throws IOException {
    isAuthByPrivateKey = false;/*from  w  w  w  .  ja  v  a 2  s.  c om*/
    log.info("Connection to " + url + " with login=" + username + " and pass=" + password);
    URL = new URL(url);
    targetHost = new HttpHost(URL.getHost(), URL.getPort());
    client = new DefaultHttpClient();
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    // Set credentials
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);
}

From source file:org.fcrepo.integration.http.api.AbstractResourceIT.java

/**
 * Execute an HTTP request with preemptive basic authentication.
 *
 * @param request the request to execute
 * @param username usename to use/*ww w.j ava2s  .com*/
 * @param password password to use
 * @return the open responses
 * @throws IOException in case of IOException
 */
@SuppressWarnings("resource")
protected CloseableHttpResponse executeWithBasicAuth(final HttpUriRequest request, final String username,
        final String password) throws IOException {
    final HttpHost target = new HttpHost(HOSTNAME, SERVER_PORT, PROTOCOL);
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(username, password));
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    final AuthCache authCache = new BasicAuthCache();
    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(target, basicAuth);

    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    return httpclient.execute(request, localContext);
}

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

public byte[] getDownloadContentBytes(String downloadURL) {
    // Create AuthCache instance
    InputStream inputStream = null;
    byte[] bytes = null;
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();

    authCache.put(host, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    String executionUrl = downloadURL;
    final HttpRequestBase method = new HttpGet(executionUrl);

    try {/*from   ww  w. j a  va  2 s  . c o m*/
        HttpResponse response = httpClient.execute(method, localContext);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            long len = entity.getContentLength();
            inputStream = entity.getContent();
            bytes = IOUtils.toByteArray(inputStream);
        }
    } catch (Exception e) {
        if (Logging.connectors != null)
            Logging.connectors.error("Error while getting inputstream", e);
    } finally {
        if (inputStream != null) {
            IOUtils.closeQuietly(inputStream);
        }
    }

    return bytes;
}

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

/**
 * Get rest response and fill the query results
 * /*  w ww.  j  a  v a2  s . c  om*/
 * @param rightside
 * @param response
 * @throws IOException
 * @throws ResponseException
 */
public void getRest(String rightside, ConfluenceJSONResponse response) throws IOException, ResponseException {

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();

    authCache.put(host, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    String executionUrl = host.toURI() + path + (path.endsWith("/") ? "" : "/") + rightside;
    if (Logging.connectors != null)
        Logging.connectors.info("Execution url is :" + executionUrl);
    final HttpRequestBase method = new HttpGet(executionUrl);
    method.addHeader("Accept", "application/json");

    try {
        HttpResponse httpResponse = httpClient.execute(method, localContext);

        int resultCode = httpResponse.getStatusLine().getStatusCode();
        if (resultCode == 200) {
            // Logging.connectors.info("Successfully retrived response");
            Object jo = convertToJSON(httpResponse);
            response.acceptJSONObject(jo);
        } else if (resultCode == 401) {
            throw new IOException("There is Authentication failure, this may be due to capcha : "
                    + convertToString(httpResponse));
        } else {
            throw new IOException(
                    "Unexpected result code " + resultCode + ": " + convertToString(httpResponse));
        }

    } finally {
        method.abort();
    }
}