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:org.lightcouch.CouchDbClientBase.java

/**
 * @return {@link DefaultHttpClient} instance.
 *//*from w w  w . j  a v  a2s . co  m*/
private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
        SchemeSocketFactory ssf = null;
        if (props.getProtocol().equals("https")) {
            TrustManager trustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            SSLSocket socket = (SSLSocket) ssf.createSocket(null);
            socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
        } else {
            ssf = PlainSocketFactory.getSocketFactory();
        }
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
        httpclient = new DefaultHttpClient(ccm);
        host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
        context = new BasicHttpContext();
        // Http params
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                props.getConnectionTimeout());
        int maxConnections = props.getMaxConnections();
        if (maxConnections != 0) {
            ccm.setMaxTotal(maxConnections);
            ccm.setDefaultMaxPerRoute(maxConnections);
        }
        if (props.getProxyHost() != null) {
            HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        // basic authentication
        if (props.getUsername() != null && props.getPassword() != null) {
            httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()),
                    new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
            props.clearPassword();
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(host, basicAuth);
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }
        // request interceptor
        httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context) throws IOException {
                if (log.isInfoEnabled())
                    log.info(">> " + request.getRequestLine());
            }
        });
        // response interceptor
        httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context) throws IOException {
                validate(response);
                if (log.isInfoEnabled())
                    log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
        });
    } catch (Exception e) {
        log.error("Error Creating HTTP client. " + e.getMessage());
        throw new IllegalStateException(e);
    }
    return httpclient;
}

From source file:org.apache.abdera2.common.protocol.Session.java

public void usePreemptiveAuthentication(String target, String realm) throws URISyntaxException {
    AuthCache cache = (AuthCache) localContext.getAttribute(ClientContext.AUTH_CACHE);
    if (cache == null) {
        String host = AuthScope.ANY_HOST;
        int port = AuthScope.ANY_PORT;
        if (target != null) {
            URI uri = new URI(target);
            host = uri.getHost();//from   w ww .  j  ava 2s  .com
            port = uri.getPort();
        }
        BasicScheme basicAuth = new BasicScheme();
        HttpHost targetHost = new HttpHost(host, port, basicAuth.getSchemeName());
        cache = new BasicAuthCache();
        cache.put(targetHost, basicAuth);
        localContext.setAttribute(ClientContext.AUTH_CACHE, cache);
    }
}

From source file:com.cheddargetter.client.service.CheddarGetterPaymentService.java

private BasicHttpContext createHttpContext() {
    AuthCache authCache = new BasicAuthCache();
    authCache.put(host, new BasicScheme());
    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTH_CACHE, authCache);
    return context;
}

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

/**
 * Execute an auth query using POST//from www .j  a va2  s.  c  o m
 * @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
 */
private JSONObject executeQueryAuthPost(String query, SparqlResultTypes resultType) throws Exception {

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

    DefaultHttpClient httpclient = new DefaultHttpClient();

    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);

    // add new stuff
    HttpPost httppost = new HttpPost(getPostURL());
    String resultsFormat = this.getContentType(resultType);
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    // add params
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("query", query));
    params.add(new BasicNameValuePair("format", resultsFormat));
    params.add(new BasicNameValuePair("default-graph-uri", this.dataset));

    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // finish new stuff

    HttpResponse response_http = httpclient.execute(targetHost, httppost, 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
    }

    JSONObject resp;
    try {
        resp = (JSONObject) JSONValue.parse(responseTxt);
    } catch (Exception e) {
        entity.getContent().close();
        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")) {
            entity.getContent().close();
            throw new Exception(responseTxt);
        }
        entity.getContent().close();
        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(resp, resultType);
        entity.getContent().close();

        return procResp;
    }
}

From source file:org.sinekartads.integration.cms.SignCMSonAlfresco.java

public static <SkdsResponse extends BaseResponse> SkdsResponse postJsonRequest(BaseRequest request,
        Class<SkdsResponse> responseClass) throws IllegalStateException, IOException {

    SkdsResponse response = null;/*from   www .  j  a va2  s . c om*/
    InputStream respIs = null;
    DefaultHttpClient httpclient = null;
    try {
        HttpHost targetHost = new HttpHost(HOST_NAME, PORT, "http");

        httpclient = new DefaultHttpClient();

        httpclient.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(USER, PWD));

        AuthCache authCache = new BasicAuthCache();

        BasicScheme basicAuth = new BasicScheme();
        authCache.put(targetHost, basicAuth);

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

        HttpPost httppost = new HttpPost("/alfresco/service" + request.getJSONUrl() + ".json?requestType=json");

        String req = request.toJSON();
        ByteArrayEntity body = new ByteArrayEntity(req.getBytes());
        httppost.setEntity(body);
        HttpResponse resp = httpclient.execute(targetHost, httppost, localcontext);
        HttpEntity entityResp = resp.getEntity();
        respIs = entityResp.getContent();

        response = TemplateUtils.Encoding.deserializeJSON(responseClass, respIs);

        EntityUtils.consume(entityResp);
        //      } catch(Exception e) {
        //         String message = e.getMessage();
        //         if ( StringUtils.isBlank(message) ) {
        //            message = e.toString();
        //         }
        //         tracer.error(message, e);
        //         throw new RuntimeException(message, e);
    } finally {
        if (httpclient != null) {
            httpclient.getConnectionManager().shutdown();
        }
        IOUtils.closeQuietly(respIs);
    }
    return response;
}

From source file:com.liferay.petra.json.web.service.client.BaseJSONWebServiceClientImpl.java

protected String execute(HttpRequestBase httpRequestBase)
        throws JSONWebServiceInvocationException, JSONWebServiceTransportException {

    signRequest(httpRequestBase);/*from w w w  .j av a 2 s  . com*/

    HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol);

    try {
        if (_closeableHttpAsyncClient == null) {
            afterPropertiesSet();
        }

        Future<HttpResponse> future = null;

        if (!isNull(_login) && !isNull(_password)) {
            HttpClientContext httpClientContext = HttpClientContext.create();

            AuthCache authCache = new BasicAuthCache();

            AuthScheme authScheme = null;

            if (!isNull(_proxyHostName)) {
                authScheme = new BasicScheme(ChallengeState.PROXY);
            } else {
                authScheme = new BasicScheme(ChallengeState.TARGET);
            }

            authCache.put(httpHost, authScheme);

            httpClientContext.setAttribute(ClientContext.AUTH_CACHE, authCache);

            future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, httpClientContext, null);
        } else {
            future = _closeableHttpAsyncClient.execute(httpHost, httpRequestBase, null);
        }

        HttpResponse httpResponse = future.get();

        StatusLine statusLine = httpResponse.getStatusLine();

        int statusCode = statusLine.getStatusCode();

        if (_logger.isTraceEnabled()) {
            _logger.trace("Server returned status " + statusCode);
        }

        HttpEntity httpEntity = httpResponse.getEntity();

        if ((statusCode == HttpServletResponse.SC_NO_CONTENT)
                || (((httpEntity == null) || (httpEntity.getContentLength() == 0))
                        && _isStatus2XX(statusCode))) {

            return null;
        }

        String content = EntityUtils.toString(httpEntity, _CHARSET);

        if ((httpEntity.getContentType() != null) && _isApplicationJSONContentType(httpEntity)) {

            content = updateJSON(content);
        }

        if (_isStatus2XX(statusCode)) {
            return content;
        } else if ((statusCode == HttpServletResponse.SC_BAD_REQUEST)
                || (statusCode == HttpServletResponse.SC_FORBIDDEN)
                || (statusCode == HttpServletResponse.SC_METHOD_NOT_ALLOWED)
                || (statusCode == HttpServletResponse.SC_NOT_ACCEPTABLE)
                || (statusCode == HttpServletResponse.SC_NOT_FOUND)) {

            throw new JSONWebServiceInvocationException(content, statusCode);
        } else if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
            throw new JSONWebServiceTransportException.AuthenticationFailure(
                    "Not authorized to access JSON web service");
        }

        throw new JSONWebServiceTransportException.CommunicationFailure("Server returned status " + statusCode,
                statusCode);
    } catch (ExecutionException ee) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ee);
    } catch (InterruptedException ie) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ie);
    } catch (IOException ioe) {
        throw new JSONWebServiceTransportException.CommunicationFailure("Unable to transmit request", ioe);
    } finally {
        httpRequestBase.releaseConnection();
    }
}

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

/**
 * Execute an auth query using POST/*from   w w  w .  ja v  a 2s  .co  m*/
 * @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
 */

public JSONObject executeAuthUploadOwl(byte[] owl) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    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);

    // add new stuff
    HttpPost httppost = new HttpPost(getUploadURL());
    String resultsFormat = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.addTextBody("graph-uri", this.dataset);
    builder.addBinaryBody("res-file", owl);
    HttpEntity entity = builder.build();
    httppost.setEntity(entity);

    /*  THIS IS THE MULTIPART FORMAT WE NEED TO SEND.
            
    Content-Type: multipart/form-data; boundary=---------------------------32932166721282
    Content-Length: 234
            
    -----------------------------32932166721282
    Content-Disposition: form-data; name="graph-uri"
            
    http://www.kdl.ge.com/changeme
    -----------------------------32932166721282
    Content-Disposition: form-data; name="res-file"; filename="employee.owl"
    Content-Type: application/octet-stream
            
    <rdf:RDF
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:owl="http://www.w3.org/2002/07/owl#"
        xmlns="http://kdl.ge.com/pd/employee#"
        xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
      .
      .
      .
    </rdf:RDF>
            
    -----------------------------32932166721282--
            
     */

    executeTestQuery();

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity resp_entity = response_http.getEntity();
    // get response with HTML tags removed
    String responseTxt = EntityUtils.toString(resp_entity, "UTF-8").replaceAll("\\<.*?>", " ");

    SimpleResultSet ret = new SimpleResultSet();

    if (responseTxt.trim().isEmpty()) {
        // success or bad login :-(
        ret.setSuccess(true);
    } else {
        ret.setSuccess(false);
        ret.addRationaleMessage(responseTxt);
    }
    resp_entity.getContent().close();
    return ret.toJson();
}