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.tntinteractive.portalsammler.engine.FileDownloader.java

/**
 * Ldt die Datei runter, die im bergebenen Attribut steht und liefert ihren Inhalt.
 *///from  w  w  w .  j a v  a 2 s  . co m
private byte[] downloader(final WebElement element, final String attribute)
        throws IOException, URISyntaxException {
    final String fileToDownloadLocation = element.getAttribute(attribute);
    if (fileToDownloadLocation.trim().equals("")) {
        throw new NullPointerException("The element you have specified does not link to anything!");
    }

    final URL fileToDownload = new URL(fileToDownloadLocation);

    final HttpClient client = HttpClientBuilder.create().build();
    final BasicHttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(HttpClientContext.COOKIE_STORE,
            this.mimicCookieState(this.driver.manage().getCookies()));

    final HttpGet httpget = new HttpGet(fileToDownload.toURI());
    httpget.setConfig(RequestConfig.custom().setRedirectsEnabled(true).build());

    final HttpResponse response = client.execute(httpget, localContext);
    this.httpStatusOfLastDownloadAttempt = response.getStatusLine().getStatusCode();
    try {
        return IOUtils.toByteArray(response.getEntity().getContent());
    } finally {
        response.getEntity().getContent().close();
    }

}

From source file:org.artificer.test.AbstractIntegrationTest.java

protected ClientRequest clientRequest(String endpoint) {
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(USERNAME, PASSWORD);
    client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY), credentials);
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    HttpHost targetHost = new HttpHost(HOST, PORT);
    authCache.put(targetHost, basicAuth);
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(client, localContext);

    ClientRequest clientRequest = new ClientRequest(BASE_URL + endpoint, executor);
    return clientRequest;
}

From source file:edu.cornell.mannlib.vitro.webapp.rdfservice.impl.virtuoso.RDFServiceVirtuoso.java

/**
 * We need an HttpContext that will provide username and password in
 * response to a basic authentication challenge.
 */// www  .  j a  v  a  2 s  . co  m
private HttpContext createHttpContext() {
    CredentialsProvider provider = new BasicCredentialsProvider();
    provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    BasicHttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.CREDS_PROVIDER, provider);
    return context;
}

From source file:org.alfresco.po.share.util.FileDownloader.java

/**
 * Main method that performs the download operation
 * using HttpClient with WebDriver's cookies.
 * /*from   ww  w .j  a  va  2s .c o m*/
 * @param path url path to file
 * @throws Exception if error
 */
public void download(final String path, File file) throws Exception {
    URL fileToDownload;
    // Cookie setup
    RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    HttpClient client = HttpClientBuilder.create().setRedirectStrategy(redirectStrategy).build();
    HttpEntity entity = null;
    try {
        String myUrl = URLDecoder.decode(path, "UTF-8");
        String fileUrl = myUrl.replace("\\/", "/").replace(" ", "%20");

        fileToDownload = new URL(fileUrl);
        BasicHttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(HttpClientContext.COOKIE_STORE, getCookies());
        // Prepare an http get call
        HttpGet httpget = new HttpGet(fileToDownload.toURI());
        if (logger.isDebugEnabled()) {
            logger.debug("Sending GET request for: " + httpget.getURI());
        }
        // Get the response from http get call
        HttpResponse response = client.execute(httpget, localContext);
        int httpStatusCode = response.getStatusLine().getStatusCode();
        if (logger.isDebugEnabled()) {
            logger.debug("HTTP GET request status: " + httpStatusCode);
        }
        // Extract content and stream to file
        entity = response.getEntity();
        InputStream input = entity.getContent();
        if (input != null) {
            FileUtils.copyInputStreamToFile(input, file);
        }
    } catch (MalformedURLException murle) {
        throw new Exception("Unable to reach document", murle);
    } catch (IllegalStateException ise) {
        throw new Exception("State problem", ise);
    } catch (IOException ioe) {
        throw new Exception("Unable to read write file", ioe);
    } catch (URISyntaxException urise) {
        throw new Exception("A uri syntax problem", urise);
    }
}

From source file:org.sonatype.nexus.proxy.maven.routing.internal.AbstractHttpRemoteStrategy.java

/**
 * Returns {@code true} if remote server (proxies by {@link MavenProxyRepository}) is recognized as server that MUST
 * NOT be trusted for any automatic routing feature.
 * /*  w  w w . j  a  v  a 2 s  . co m*/
 * @throws StrategyFailedException if server is recognized as blacklisted.
 */
protected void checkIsBlacklistedRemoteServer(final MavenProxyRepository mavenProxyRepository)
        throws StrategyFailedException, IOException {
    // check URL first, we currently test HTTP and HTTPS only for blacklist, if not, just skip this
    // but do not report blacklist at all (nor attempt)
    final String remoteUrl;
    try {
        remoteUrl = getRemoteUrlOf(mavenProxyRepository);
    } catch (MalformedURLException e) {
        // non HTTP/HTTPS, just return
        return;
    }
    final HttpClient httpClient = createHttpClientFor(mavenProxyRepository);
    {
        // NEXUS-5849: Artifactory will happily serve Central prefixes, effectively shading all the other artifacts from
        // it's group
        final HttpGet get = new HttpGet(remoteUrl);
        final BasicHttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(HttpClientFactory.HTTP_CTX_KEY_REPOSITORY, mavenProxyRepository);
        final HttpResponse response = httpClient.execute(get, httpContext);

        try {
            if (response.containsHeader("X-Artifactory-Id")) {
                log.debug("Remote server of proxy {} recognized as ARTF by response header",
                        mavenProxyRepository);
                throw new StrategyFailedException("Server proxied by " + mavenProxyRepository
                        + " proxy repository is not supported by automatic routing discovery");
            }
            if (response.getStatusLine().getStatusCode() >= 200
                    && response.getStatusLine().getStatusCode() <= 499) {
                if (response.getEntity() != null) {
                    final Document document = Jsoup.parse(response.getEntity().getContent(), null, remoteUrl);
                    final Elements addressElements = document.getElementsByTag("address");
                    if (!addressElements.isEmpty()) {
                        final String addressText = addressElements.get(0).text();
                        if (addressText != null
                                && addressText.toLowerCase(Locale.ENGLISH).startsWith("artifactory")) {
                            log.debug("Remote server of proxy {} recognized as ARTF by address element in body",
                                    mavenProxyRepository);
                            throw new StrategyFailedException("Server proxied by " + mavenProxyRepository
                                    + " proxy repository is not supported by automatic routing discovery");
                        }
                    }
                }
            }
        } finally {
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

From source file:com.consol.citrus.http.client.BasicAuthClientHttpRequestFactory.java

/**
 * Construct the client factory bean with user credentials.
 *//* w  w w  .  ja  v  a2s .co m*/
public HttpComponentsClientHttpRequestFactory getObject() throws Exception {
    Assert.notNull(credentials, "User credentials not set properly!");

    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            // we have to use preemptive authentication
            // therefore add some basic auth cache to the local context
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();

            authCache.put(new HttpHost(authScope.getHost(), authScope.getPort(), "http"), basicAuth);
            authCache.put(new HttpHost(authScope.getHost(), authScope.getPort(), "https"), basicAuth);

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

            return localcontext;
        }
    };

    if (httpClient instanceof AbstractHttpClient) {
        ((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials);
    } else {
        log.warn("Unable to set username password credentials for basic authentication, "
                + "because nested HttpClient implementation does not support a credentials provider!");
    }

    return requestFactory;
}

From source file:com.citrix.g2w.webdriver.util.FileDownloader.java

public String downloader(String fileToDownloadLocation, String localDownloadPath)
        throws IOException, URISyntaxException {
    URL fileToDownload = new URL(fileToDownloadLocation);
    String fileNameURI = fileToDownload.getFile();
    String filePath = "";
    if (fileNameURI.contains("?")) {
        filePath = localDownloadPath/*  w  w w  .j a  va 2  s. c om*/
                + fileNameURI.substring(fileNameURI.substring(0, fileNameURI.indexOf("?")).lastIndexOf("/") + 1,
                        fileNameURI.indexOf("?"));
    } else {
        filePath = localDownloadPath + fileNameURI.substring(fileNameURI.lastIndexOf("/") + 1);
    }
    File downloadedFile = new File(filePath);
    if (downloadedFile.canWrite() == false) {
        downloadedFile.setWritable(true);
    }

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

    if (this.mimicWebDriverCookieState) {
        localContext.setAttribute(ClientContext.COOKIE_STORE,
                this.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);

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

    FileUtils.copyInputStreamToFile(response.getEntity().getContent(), downloadedFile);
    response.getEntity().getContent().close();

    String downloadedFileAbsolutePath = downloadedFile.getAbsolutePath();
    this.logger.log("File downloaded to '" + downloadedFileAbsolutePath + "'");

    return downloadedFileAbsolutePath;
}

From source file:magicware.scm.redmine.tools.RedmineClient.java

public void fillBasicAuth(String userName, String base64Pwd) {

    // Basic?//from www  .j a  va2s . c  o  m
    httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(userName,
                    StringUtils.isEmpty(base64Pwd) ? UUID.randomUUID().toString()
                            : new String(Base64.decodeBase64(base64Pwd))));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);
}

From source file:org.zenoss.metrics.reporter.HttpPoster.java

private final void postImpl(MetricBatch batch) throws IOException {
    int size = batch.getMetrics().size();
    MetricCollection metrics = new MetricCollection();
    metrics.setMetrics(batch.getMetrics());

    String json = asJson(metrics);

    // Add AuthCache to the execution context
    BasicHttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieJar);

    if (needsAuth && !authenticated) {
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        HttpHost targetHost = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
        authCache.put(targetHost, basicAuth);

        localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);
    }/*from  ww w .  j a  va 2  s .com*/

    post.setEntity(new StringEntity(json, APPLICATION_JSON));

    cookieJar.clearExpired(new Date());
    httpClient.execute(post, responseHandler, localContext);
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * CookieStore per AccountName to prevent mixing of the sessions.
 * /*from  w w w .j a  v  a 2  s.  c  o m*/
 * @param accountName
 *            accountName or null (default)
 * @return
 */
private static HttpContext createHttpContext(String accountName, String authtoken) {
    BasicHttpContext ctx = new BasicHttpContext();
    CookieStore store;
    synchronized (CL_LOCK) {
        store = COOKIES.get(accountName);
        if (store == null) {
            store = new BasicCookieStore();
            COOKIES.put(accountName, store);
        }
    }
    ctx.setAttribute(ClientContext.COOKIE_STORE, store);

    if (authtoken != null) {
        boolean add = true;
        for (Cookie cookie : store.getCookies()) {
            if (COOKIE_SESSION_NAME.equals(cookie.getName())) {
                if (authtoken.equals(cookie.getValue())) {
                    add = false;
                }
                break;
            }
        }
        if (add) {
            BasicClientCookie sessionCookie = new BasicClientCookie(COOKIE_SESSION_NAME, authtoken);
            sessionCookie.setSecure(true);
            store.addCookie(sessionCookie);
        }
    }

    return ctx;
}