Example usage for org.apache.http.protocol BasicHttpContext setAttribute

List of usage examples for org.apache.http.protocol BasicHttpContext setAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol BasicHttpContext setAttribute.

Prototype

public void setAttribute(String str, Object obj) 

Source Link

Usage

From source file:de.escidoc.core.test.common.fedora.TripleStoreTestBase.java

/**
 * Request SPO query to MPT triple store.
 *
 * @param spoQuery     The SPO query./*from  www .  j av  a2  s  .  c o  m*/
 * @param outputFormat The triple store output format (N-Triples/RDF/XML/Turtle/..)
 * @return query result
 * @throws Exception If anything fails.
 */
public String requestMPT(final String spoQuery, final String outputFormat) throws Exception {
    HttpPost post = new HttpPost(getFedoraUrl() + "/risearch");
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("format", outputFormat));
    formparams.add(new BasicNameValuePair("query", spoQuery));
    formparams.add(new BasicNameValuePair("type", TYPE_MPT));
    formparams.add(new BasicNameValuePair("lang", LANG_MPT));
    // The flush parameter tells the resource index to ensure
    // that any recently-added/modified/deleted triples are
    // flushed to the triplestore before executing the query.
    formparams.add(new BasicNameValuePair("flush", FLUSH));
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, HTTP.UTF_8);
    post.setEntity(entity);

    int resultCode = 0;
    try {
        DefaultHttpClient httpClient = getHttpClient();
        BasicHttpContext localcontext = new BasicHttpContext();
        BasicScheme basicAuth = new BasicScheme();
        localcontext.setAttribute("preemptive-auth", basicAuth);
        httpClient.addRequestInterceptor(new PreemptiveAuthInterceptor(), 0);
        HttpResponse httpRes = httpClient.execute(post, localcontext);
        if (httpRes.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) {
            throw new Exception("Bad request. Http response : " + resultCode);
        }

        String result = EntityUtils.toString(httpRes.getEntity(), HTTP.UTF_8);
        if (result == null) {
            return null;
        }
        if (result.startsWith("<html")) {
            Pattern p = Pattern.compile(QUERY_ERROR);
            Matcher m = p.matcher(result);

            Pattern p1 = Pattern.compile(PARSE_ERROR);
            Matcher m1 = p1.matcher(result);

            Pattern p2 = Pattern.compile(FORMAT_ERROR);
            Matcher m2 = p2.matcher(result);
            if (m.find()) {
                result = Constants.CDATA_START + result + Constants.CDATA_END;
                if (m1.find()) {
                    throw new Exception(result);
                } else if (m2.find()) {
                    throw new Exception(result);
                }
            } else {
                result = Constants.CDATA_START + result + Constants.CDATA_END;
                throw new Exception("Request to MPT failed." + result);
            }
        }

        return result;
    } catch (final Exception e) {
        throw new Exception(e.toString(), e);
    }
}

From source file:org.sonatype.nexus.plugins.rrb.MavenRepositoryReader.java

private StringBuilder getContent() {
    StringBuilder buff = new StringBuilder();

    String sep = remoteUrl.contains("?") ? "&" : "?";
    String url = remoteUrl + sep + "delimiter=/";
    url = maybeAppendQueryString(url);/* ww w. ja  v a2  s.c o m*/

    HttpGet method = new HttpGet(url);
    try {
        logger.debug("Requesting: {}", method);

        final BasicHttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(Hc4Provider.HTTP_CTX_KEY_REPOSITORY, proxyRepository);

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

        int statusCode = response.getStatusLine().getStatusCode();
        logger.debug("Status code: {}", statusCode);

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line;
        while ((line = reader.readLine()) != null) {
            buff.append(line).append("\n");
        }

        // HACK: Deal with S3 edge-case
        // here is the deal, For reasons I do not understand, S3 comes back with an empty response (and a 200),
        // stripping off the last '/' returns the error we are looking for (so we can do a query)
        Header serverHeader = response.getFirstHeader(HttpHeaders.SERVER);
        if (buff.length() == 0 && serverHeader != null && serverHeader.getValue().equalsIgnoreCase("AmazonS3")
                && remoteUrl.endsWith("/")) {
            remoteUrl = remoteUrl.substring(0, remoteUrl.length() - 1);
            return getContent();
        }

        return buff;
    } catch (Exception e) {
        logger.warn("Failed to get directory listing content", e);
    }

    return buff;
}

From source file:com.mikecorrigan.bohrium.pubsub.Transaction.java

private int read(HttpRequestBase request) {
    Log.v(TAG, "read");

    CookieStore mCookieStore = new BasicCookieStore();
    mCookieStore.addCookie(mAuthCookie);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicHttpContext mHttpContext = new BasicHttpContext();
    mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);

    try {/*from www  .j a va  2 s . c  o m*/
        final HttpParams getParams = new BasicHttpParams();
        HttpClientParams.setRedirecting(getParams, false);
        request.setParams(getParams);

        request.setHeader("Accept", getMimeType());

        HttpResponse response = httpClient.execute(request, mHttpContext);
        Log.d(TAG, "status=" + response.getStatusLine());

        // Read response body.
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            InputStream is = responseEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            is.close();

            mStatusCode = response.getStatusLine().getStatusCode();
            mStatusReason = response.getStatusLine().getReasonPhrase();
            if (mStatusCode == 200) {
                mResponseBody = decode(sb.toString());
                Log.v(TAG, "mResponseBody=" + sb.toString());
            }
            return mStatusCode;
        }
    } catch (IOException e) {
        Log.e(TAG, "exception=" + e);
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    }

    return mStatusCode;
}

From source file:com.cloudbees.tomcat.valves.PrivateAppValveIntegratedTest.java

@Test
public void pre_emptive_basic_authentication_scenario() throws IOException {
    System.out.println("pre_emptive_basic_authentication_scenario");

    privateAppValve.setAuthenticationEntryPoint(PrivateAppValve.AuthenticationEntryPoint.BASIC_AUTH);

    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials(accessKey, secretKey));

    // 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);//from w  ww.j a  va2s. c  om

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/");

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpClient.execute(httpHost, httpget, localcontext);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("x-response"), is(true));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }

}

From source file:com.mikecorrigan.bohrium.pubsub.Transaction.java

private int readWrite(HttpEntityEnclosingRequestBase request) {
    Log.v(TAG, "readWrite");

    CookieStore mCookieStore = new BasicCookieStore();
    mCookieStore.addCookie(mAuthCookie);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    BasicHttpContext mHttpContext = new BasicHttpContext();
    mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore);

    // Encode request body.
    StringEntity requestEntity;//from  w  w  w .  j  av  a 2  s  .c om
    try {
        requestEntity = new StringEntity(encode(mRequestBody));
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "HTTP encoding failed=" + e);
        return mStatusCode;
    }

    try {
        final HttpParams getParams = new BasicHttpParams();
        HttpClientParams.setRedirecting(getParams, false);
        request.setParams(getParams);

        request.setHeader("Content-Type", getMimeType());
        request.setEntity(requestEntity);

        HttpResponse response = httpClient.execute(request, mHttpContext);
        Log.d(TAG, "status=" + response.getStatusLine());

        // Read response body.
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            InputStream is = responseEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            is.close();

            mStatusCode = response.getStatusLine().getStatusCode();
            mStatusReason = response.getStatusLine().getReasonPhrase();
            if (mStatusCode == 200) {
                mResponseBody = decode(sb.toString());
                Log.v(TAG, "mResponseBody=" + sb.toString());
            }
            return mStatusCode;
        }
    } catch (IOException e) {
        Log.e(TAG, "exception=" + e);
        Log.e(TAG, Log.getStackTraceString(e));
    } finally {
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    }

    return mStatusCode;
}

From source file:com.cloudbees.servlet.filters.PrivateAppFilterIntegratedTest.java

@Test
public void pre_emptive_basic_authentication_scenario() throws IOException {
    System.out.println("pre_emptive_basic_authentication_scenario");

    privateAppFilter.setAuthenticationEntryPoint(PrivateAppFilter.AuthenticationEntryPoint.BASIC_AUTH);

    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials(accessKey, secretKey));

    // 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);//from w w w. j  a v a2s .  c  om

    // Add AuthCache to the execution context
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet("/");

    for (int i = 0; i < 3; i++) {
        HttpResponse response = httpClient.execute(httpHost, httpget, localcontext);
        assertThat(response.getStatusLine().getStatusCode(), equalTo(HttpServletResponse.SC_OK));
        assertThat(response.containsHeader("x-response"), is(true));

        dumpHttpResponse(response);

        EntityUtils.consumeQuietly(response.getEntity());
    }

}

From source file:com.controlj.experiment.bulktrend.trendclient.TrendClient.java

public void go() {
    DefaultHttpClient client = null;// w  w  w.j a  v a  2s .  co  m
    try {
        prepareForResponse();

        if (altInput == null) {
            client = new DefaultHttpClient();

            // Set up preemptive Basic Authentication
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
            client.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

            BasicHttpContext localcontext = new BasicHttpContext();
            BasicScheme basicAuth = new BasicScheme();
            localcontext.setAttribute("preemptive-auth", basicAuth);
            client.addRequestInterceptor(new PreemptiveAuthRequestInterceptor(), 0);

            if (zip) {
                client.addRequestInterceptor(new GZipRequestInterceptor());
                client.addResponseInterceptor(new GZipResponseInterceptor());
            }

            HttpPost post = new HttpPost(url);

            try {
                setPostData(post);
                HttpResponse response = client.execute(post, localcontext);
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    System.err.println(
                            "Error: Web Service response code of: " + response.getStatusLine().getStatusCode());
                    return;
                }
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    parser.parseResponse(ids.size(), entity.getContent());
                }

            } catch (IOException e) {
                System.err.println("IO Error reading response");
                e.printStackTrace();
            }
        } else { // Alternate input (typically from a file) for testing
            try {
                parser.parseResponse(ids.size(), altInput);
            } catch (IOException e) {
                System.err.println("IO Error reading response");
                e.printStackTrace();
            }
        }
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
    }
    /*
    try {
    parser.parseResponse(ids.size(), new FileInputStream(new File("response.dump")));
    } catch (IOException e) {
    e.printStackTrace(); 
    }
    */

}

From source file:gov.nrel.bacnet.consumer.DatabusSender.java

BasicHttpContext setupPreEmptiveBasicAuth(DefaultHttpClient httpclient) {
    HttpHost targetHost = new HttpHost(host, port, mode);
    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, key));

    // 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);
    return localcontext;
}

From source file:org.ovirt.engine.sdk.web.HttpProxy.java

/**
 * Generates peer hit context/*from w w  w .j a  v a  2 s  .  c  o m*/
 * 
 * @return {@link BasicHttpContext}
 */
private BasicHttpContext getContext() {
    BasicHttpContext context = new BasicHttpContext();
    if (this.persistentAuth && StringUtils.isNulOrEmpty(this.sessionid)) {
        context.setAttribute(ClientContext.COOKIE_STORE, this.pool.getCookieStore());
    }
    return context;
}

From source file:com.lazerycode.selenium.filedownloader.FileDownloader.java

/**
 * Perform the file/image download.//  w ww . j a va  2s .co  m
 *
 * @param element
 * @param attribute
 * @return
 * @throws IOException
 * @throws NullPointerException
 */
private String downloader(WebElement element, String attribute, String Filename)
        throws IOException, NullPointerException, URISyntaxException {
    String fileToDownloadLocation = element.getAttribute(attribute);
    if (fileToDownloadLocation.trim().equals(""))
        throw new NullPointerException("The element you have specified does not link to anything!");

    URL fileToDownload = new URL(fileToDownloadLocation);
    //changed by Raul
    File downloadedFile = new File(Filename);
    //+ " fileToDownload.getFile().replaceFirst("/|\\\\", "").replace("?", ""));

    if (downloadedFile.canWrite() == false)
        downloadedFile.setWritable(true);

    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();

    //LOG.info("Mimic WebDriver cookie state: " + this.mimicWebDriverCookieState);
    if (this.mimicWebDriverCookieState) {
        localContext.setAttribute(ClientContext.COOKIE_STORE,
                mimicCookieState(this.driver.manage().getCookies()));
    }

    HttpGet httpget = new HttpGet(fileToDownload.toURI());
    HttpParams httpRequestParameters = httpget.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, this.followRedirects);
    httpget.setParams(httpRequestParameters);

    // LOG.info("Sending GET request for: " + httpget.getURI());
    HttpResponse response = client.execute(httpget, localContext);
    this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
    //LOG.info("HTTP GET request status: " + this.httpStatusOfLastDownloadAttempt);
    //LOG.info("Downloading file: " + downloadedFile.getName());
    FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
    response.getEntity().getContent().close();

    String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
    // LOG.info("File downloaded to '" + downloadedFileAbsolutePath + "'");

    return downloadedFileAbsolutePath;
}