Example usage for org.apache.http.client.protocol ClientContext AUTH_CACHE

List of usage examples for org.apache.http.client.protocol ClientContext AUTH_CACHE

Introduction

In this page you can find the example usage for org.apache.http.client.protocol ClientContext AUTH_CACHE.

Prototype

String AUTH_CACHE

To view the source code for org.apache.http.client.protocol ClientContext AUTH_CACHE.

Click Source Link

Document

Attribute name of a org.apache.http.client.AuthCache object that represents the auth scheme cache.

Usage

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using GET (use should be rare - in cases where POST is not supported)
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception/*from  www .  ja  va 2  s  . c  o  m*/
 */
@SuppressWarnings("unused")
private JSONObject executeQueryAuthGet(String queryAndUrl, SparqlResultTypes resultType) throws Exception {

    if (resultType == null) {
        resultType = getDefaultResultType();
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    //ResponseHandler<String> responseHandler = new BasicResponseHandler();

    System.err.println("the server name was " + this.server);
    System.err.println("the port id was " + this.port);
    System.err.println("the user name was " + "SPARQL/" + this.userName);
    System.err.println("the password was " + this.password);

    System.err.println(queryAndUrl);

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet(queryAndUrl);
    String resultsFormat = this.getContentType(resultType);
    httpget.addHeader("Accept", resultsFormat);

    System.out.println("executing request" + httpget.getRequestLine());

    //        String responseTxt = httpclient.execute(httpget, responseHandler);
    HttpResponse response_http = httpclient.execute(targetHost, httpget, localcontext);
    HttpEntity entity = response_http.getEntity();
    String responseTxt = EntityUtils.toString(entity, "UTF-8");

    // some diagnostic output
    if (responseTxt == null) {
        System.err.println("the response text was null!");
    }

    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    if (responseTxt.length() < 100) {
        System.err.println("SparqlEndpointInterface received: " + responseTxt);
    } else {
        System.err.println("SparqlEndpointInterface received: " + responseTxt.substring(0, 99) + "... ("
                + responseTxt.length() + " chars)");
    }

    JSONObject resp;
    try {
        resp = (JSONObject) new JSONParser().parse(responseTxt);
    } catch (Exception e) {
        throw new Exception("Cannot parse query result into JSON: " + responseTxt);
    }

    if (resp == null) {
        System.err.println("the response could not be transformed into json");

        if (responseTxt.contains("Error")) {
            throw new Exception(responseTxt);
        }
        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(resp, resultType);

        return procResp;
    }
}

From source file:org.apache.hadoop.gateway.GatewayFuncTestDriver.java

public String oozieSubmitJob(String user, String password, String request, int status)
        throws IOException, URISyntaxException {
    getMock("OOZIE").expect().method("POST").pathInfo("/v1/jobs").respond().status(HttpStatus.SC_CREATED)
            .content(getResourceBytes("oozie-jobs-submit-response.json")).contentType("application/json");
    //System.out.println( "REQUEST LENGTH = " + request.length() );

    URL url = new URL(getUrl("OOZIE") + "/v1/jobs?action=start" + (isUseGateway() ? "" : "&user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(user, password));

    // 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
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpPost post = new HttpPost(url.toURI());
    //    post.getParams().setParameter( "action", "start" );
    StringEntity entity = new StringEntity(request, ContentType.create("application/xml", "UTF-8"));
    post.setEntity(entity);/*from w  w  w .ja  v a2 s  .  c om*/
    post.setHeader("X-XSRF-Header", "ksdjfhdsjkfhds");
    HttpResponse response = client.execute(targetHost, post, localContext);
    assertThat(response.getStatusLine().getStatusCode(), is(status));
    String json = EntityUtils.toString(response.getEntity());

    //    String json = given()
    //        .log().all()
    //        .auth().preemptive().basic( user, password )
    //        .queryParam( "action", "start" )
    //        .contentType( "application/xml;charset=UTF-8" )
    //        .content( request )
    //        .expect()
    //        .log().all()
    //        .statusCode( status )
    //        .when().post( getUrl( "OOZIE" ) + "/v1/jobs" + ( isUseGateway() ? "" : "?user.name=" + user ) ).asString();
    //System.out.println( "JSON=" + json );
    String id = from(json).getString("id");
    return id;
}

From source file:org.apache.hadoop.gateway.GatewayFuncTestDriver.java

public String oozieQueryJobStatus(String user, String password, String id, int status) throws Exception {
    getMock("OOZIE").expect().method("GET").pathInfo("/v1/job/" + id).respond().status(HttpStatus.SC_OK)
            .content(getResourceBytes("oozie-job-show-info.json")).contentType("application/json");

    //NOTE:  For some reason REST-assured doesn't like this and ends up failing with Content-Length issues.
    URL url = new URL(getUrl("OOZIE") + "/v1/job/" + id + (isUseGateway() ? "" : "?user.name=" + user));
    HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope(targetHost),
            new UsernamePasswordCredentials(user, password));

    // 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
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet request = new HttpGet(url.toURI());
    request.setHeader("X-XSRF-Header", "ksdhfjkhdsjkf");
    HttpResponse response = client.execute(targetHost, request, localContext);
    assertThat(response.getStatusLine().getStatusCode(), is(status));
    String json = EntityUtils.toString(response.getEntity());
    String jobStatus = from(json).getString("status");
    return jobStatus;
}

From source file:org.apache.http.client.protocol.ResponseAuthCache.java

public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
    Args.notNull(response, "HTTP request");
    Args.notNull(context, "HTTP context");
    AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);

    HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    final AuthState targetState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
    if (target != null && targetState != null) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("Target auth state: " + targetState.getState());
        }//  ww  w  .j a  v a 2 s.com
        if (isCachable(targetState)) {
            final SchemeRegistry schemeRegistry = (SchemeRegistry) context
                    .getAttribute(ClientContext.SCHEME_REGISTRY);
            if (target.getPort() < 0) {
                final Scheme scheme = schemeRegistry.getScheme(target);
                target = new HttpHost(target.getHostName(), scheme.resolvePort(target.getPort()),
                        target.getSchemeName());
            }
            if (authCache == null) {
                authCache = new BasicAuthCache();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            }
            switch (targetState.getState()) {
            case CHALLENGED:
                cache(authCache, target, targetState.getAuthScheme());
                break;
            case FAILURE:
                uncache(authCache, target, targetState.getAuthScheme());
            }
        }
    }

    final HttpHost proxy = (HttpHost) context.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
    final AuthState proxyState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
    if (proxy != null && proxyState != null) {
        if (this.log.isDebugEnabled()) {
            this.log.debug("Proxy auth state: " + proxyState.getState());
        }
        if (isCachable(proxyState)) {
            if (authCache == null) {
                authCache = new BasicAuthCache();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            }
            switch (proxyState.getState()) {
            case CHALLENGED:
                cache(authCache, proxy, proxyState.getAuthScheme());
                break;
            case FAILURE:
                uncache(authCache, proxy, proxyState.getAuthScheme());
            }
        }
    }
}

From source file:org.apache.http.impl.client.AuthenticationStrategyAdaptor.java

public void authSucceeded(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
    if (isCachable(authScheme)) {
        if (authCache == null) {
            authCache = new BasicAuthCache();
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }//from ww  w. j  av a2  s .com
        if (this.log.isDebugEnabled()) {
            this.log.debug("Caching '" + authScheme.getSchemeName() + "' auth scheme for " + authhost);
        }
        authCache.put(authhost, authScheme);
    }
}

From source file:org.apache.http.impl.client.AuthenticationStrategyAdaptor.java

public void authFailed(final HttpHost authhost, final AuthScheme authScheme, final HttpContext context) {
    final AuthCache authCache = (AuthCache) context.getAttribute(ClientContext.AUTH_CACHE);
    if (authCache == null) {
        return;//from ww w.j  a v a2s .c o m
    }
    if (this.log.isDebugEnabled()) {
        this.log.debug("Removing from cache '" + authScheme.getSchemeName() + "' auth scheme for " + authhost);
    }
    authCache.remove(authhost);
}

From source file:org.apache.tomcat.maven.common.deployer.TomcatManager.java

/**
 * Creates a Tomcat manager wrapper for the specified URL, username, password and URL encoding.
 *
 * @param url      the full URL of the Tomcat manager instance to use
 * @param username the username to use when authenticating with Tomcat manager
 * @param password the password to use when authenticating with Tomcat manager
 * @param charset  the URL encoding charset to use when communicating with Tomcat manager
 * @param verbose  if the build is in verbose mode (quiet mode otherwise)
 * @since 2.2/*from   w ww  . j a  v a  2 s .  c om*/
 */
public TomcatManager(URL url, String username, String password, String charset, boolean verbose) {
    this.url = url;
    this.username = username;
    this.password = password;
    this.charset = charset;
    this.verbose = verbose;

    PoolingClientConnectionManager poolingClientConnectionManager = new PoolingClientConnectionManager();
    poolingClientConnectionManager.setMaxTotal(5);
    this.httpClient = new DefaultHttpClient(poolingClientConnectionManager);
    if (StringUtils.isNotEmpty(username)) {
        Credentials creds = new UsernamePasswordCredentials(username, password);

        String host = url.getHost();
        int port = url.getPort() > -1 ? url.getPort() : AuthScope.ANY_PORT;

        httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port), creds);

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        authCache.put(targetHost, basicAuth);

        localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }
}

From source file:org.hyperic.hq.hqapi1.HQConnection.java

private <T> T runMethod(HttpRequestBase method, String uri, ResponseHandler<T> responseHandler)
        throws IOException {
    String protocol = _isSecure ? "https" : "http";
    ServiceError error;//from w  w w . j av  a  2  s. co m
    URL url = new URL(protocol, _host, _port, uri);

    try {
        method.setURI(url.toURI());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("The syntax of request url [" + uri + "] is invalid", e);
    }

    _log.debug("Setting URI: " + url.toString());

    DefaultHttpClient client = new DefaultHttpClient();

    if (_isSecure) {
        // To allow for self signed certificates
        configureSSL(client);
    }

    // Validate user & password inputs
    if (_user == null || _user.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("User name cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    if (_password == null || _password.length() == 0) {
        error = new ServiceError();
        error.setErrorCode("LoginFailure");
        error.setReasonText("Password cannot be null or empty");

        return responseHandler.getErrorResponse(error);
    }

    // Set Basic auth creds
    UsernamePasswordCredentials defaultcreds = new UsernamePasswordCredentials(_user, _password);

    client.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds);

    // Preemptive authentication
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost host = new HttpHost(_host, _port, protocol);

    authCache.put(host, basicAuth);

    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    method.getParams().setParameter(ClientPNames.HANDLE_AUTHENTICATION, true);

    // Disable re-tries
    client.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, true));

    HttpResponse response = client.execute(method, localContext);

    return responseHandler.handleResponse(response);
}