Example usage for org.apache.http.client.protocol HttpClientContext getRedirectLocations

List of usage examples for org.apache.http.client.protocol HttpClientContext getRedirectLocations

Introduction

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

Prototype

@SuppressWarnings("unchecked")
    public List<URI> getRedirectLocations() 

Source Link

Usage

From source file:org.openmrs.module.webservices.rest.ITBase.java

@BeforeClass
public static void waitForServerToStart() {
    synchronized (serverStartupLock) {
        if (!serverStarted) {
            final long time = System.currentTimeMillis();
            final int timeout = 300000;
            final int retryAfter = 10000;

            final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(retryAfter)
                    .setConnectTimeout(retryAfter).build();

            final String startupUri = TEST_URL.getScheme() + "://" + TEST_URL.getHost() + ":"
                    + TEST_URL.getPort() + TEST_URL.getPath();
            System.out.println(//from  w w  w. j a  v  a 2  s  .c  o m
                    "Waiting for server at " + startupUri + " for " + timeout / 1000 + " more seconds...");

            while (System.currentTimeMillis() - time < timeout) {
                try {
                    final HttpClient client = HttpClientBuilder.create().disableAutomaticRetries().build();
                    final HttpGet sessionGet = new HttpGet(startupUri);
                    sessionGet.setConfig(requestConfig);
                    final HttpClientContext context = HttpClientContext.create();
                    final HttpResponse response = client.execute(sessionGet, context);

                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 400) {
                        throw new RuntimeException(status + " " + response.getStatusLine().getReasonPhrase());
                    }

                    URI finalUri = sessionGet.getURI();
                    List<URI> redirectLocations = context.getRedirectLocations();
                    if (redirectLocations != null) {
                        finalUri = redirectLocations.get(redirectLocations.size() - 1);
                    }

                    String finalUriString = finalUri.toString();
                    if (!finalUriString.contains("initialsetup")) {
                        serverStarted = true;
                        return;
                    }
                } catch (IOException e) {
                    System.out.println(e.toString());
                }

                try {
                    System.out.println("Waiting for " + (timeout - (System.currentTimeMillis() - time)) / 1000
                            + " more seconds...");
                    Thread.sleep(retryAfter);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            throw new RuntimeException("Server startup took longer than 5 minutes!");
        }
    }
}

From source file:com.yaauie.unfurl.UrlExpander.java

public URI expand(URI uri) throws IOException {
    final HttpHead request = new HttpHead(uri);
    final HttpClientContext context = new HttpClientContext();

    httpClient.execute(request, context);

    final List<URI> redirectLocations = context.getRedirectLocations();
    if (redirectLocations == null || redirectLocations.isEmpty()) {
        return uri;
    } else {/*from w  ww  . j a v a 2s .com*/
        return redirectLocations.get(redirectLocations.size() - 1);
    }
}

From source file:org.callimachusproject.client.HttpUriClient.java

private URI getSystemId(HttpClientContext ctx) {
    HttpUriRequest request = (HttpUriRequest) ctx.getRequest();
    try {//from  w ww . j  a  v a2s .co m
        URI original = request.getURI();
        HttpHost target = ctx.getTargetHost();
        List<URI> list = ctx.getRedirectLocations();
        URI absolute = URIUtils.resolve(original, target, list);
        return new URI(TermFactory.newInstance(absolute.toASCIIString()).getSystemId());
    } catch (URISyntaxException e) {
        return request.getURI();
    }
}

From source file:org.callimachusproject.client.HttpClientRedirectTest.java

/**
 * The interpreted (absolute) URI that was used to generate the last
 * request./*  w  w w. j a  va 2s .  c  o m*/
 */
private URI getHttpLocation(HttpUriRequest originalRequest, HttpClientContext ctx) {
    try {
        URI original = originalRequest.getURI();
        HttpHost target = ctx.getTargetHost();
        List<URI> redirects = ctx.getRedirectLocations();
        URI absolute = URIUtils.resolve(original, target, redirects);
        return new URI(TermFactory.newInstance(absolute.toASCIIString()).getSystemId());
    } catch (URISyntaxException e) {
        return null;
    }
}

From source file:io.crate.integrationtests.BlobHttpIntegrationTest.java

public List<String> getRedirectLocations(CloseableHttpClient client, String uri, InetSocketAddress address)
        throws IOException {
    CloseableHttpResponse response = null;
    try {/*  ww w. j  a va 2  s.c o m*/
        HttpClientContext context = HttpClientContext.create();
        HttpHead httpHead = new HttpHead(String.format(Locale.ENGLISH, "http://%s:%s/_blobs/%s",
                address.getHostName(), address.getPort(), uri));
        response = client.execute(httpHead, context);

        List<URI> redirectLocations = context.getRedirectLocations();
        if (redirectLocations == null) {
            // client might not follow redirects automatically
            if (response.containsHeader("location")) {
                List<String> redirects = new ArrayList<>(1);
                for (Header location : response.getHeaders("location")) {
                    redirects.add(location.getValue());
                }
                return redirects;
            }
            return Collections.emptyList();
        }

        List<String> redirects = new ArrayList<>(1);
        for (URI redirectLocation : redirectLocations) {
            redirects.add(redirectLocation.toString());
        }
        return redirects;
    } finally {
        if (response != null) {
            IOUtils.closeWhileHandlingException(response);
        }
    }
}

From source file:io.crate.rest.AdminUIHttpIntegrationTest.java

List<URI> getAllRedirectLocations(String uri, Header[] headers) throws IOException {
    CloseableHttpResponse response = null;
    try {//from  ww w . j  av  a  2  s  .c o m
        HttpClientContext context = HttpClientContext.create();
        HttpGet httpGet = new HttpGet(String.format(Locale.ENGLISH, "http://%s:%s/%s", address.getHostName(),
                address.getPort(), uri));
        if (headers != null) {
            httpGet.setHeaders(headers);
        }
        response = httpClient.execute(httpGet, context);

        // get all redirection locations
        return context.getRedirectLocations();
    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:sachin.spider.SpiderConfig.java

private String handleRedirect(String url) {
    try {/* www. j  ava  2 s  .  co m*/
        HttpGet httpget = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setRedirectsEnabled(true)
                .setCircularRedirectsAllowed(true).setRelativeRedirectsAllowed(true)
                .setConnectionRequestTimeout(getConnectionRequestTimeout()).setSocketTimeout(getSocketTimeout())
                .setConnectTimeout(getConnectionTimeout()).build();
        httpget.setConfig(requestConfig);
        HttpClientBuilder builder = HttpClientBuilder.create();
        builder.setUserAgent(getUserAgentString());
        if (isAuthenticate()) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(getUsername(), getPassword()));
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
        CloseableHttpClient httpclient = builder.build();
        HttpClientContext context = HttpClientContext.create();
        CloseableHttpResponse response = httpclient.execute(httpget, context);
        HttpHost target = context.getTargetHost();
        List<URI> redirectLocations = context.getRedirectLocations();
        URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
        url = location.toString();
        EntityUtils.consumeQuietly(response.getEntity());
        HttpClientUtils.closeQuietly(response);
    } catch (IOException | URISyntaxException ex) {
        Logger.getLogger(SpiderConfig.class.getName()).log(Level.SEVERE, null, ex);
        System.err.println(url);
    }
    return url;
}

From source file:sachin.spider.WebSpider.java

private void handleRedirectedLink(WebURL curUrl) {
    String url = curUrl.getUrl();
    HttpGet httpget = new HttpGet(url);
    RequestConfig requestConfig = getRequestConfigWithRedirectEnabled();
    httpget.setConfig(requestConfig);// w w  w  . j a va2  s  .co m
    try {
        HttpClientContext context = HttpClientContext.create();
        long startingTime = System.currentTimeMillis();
        try (CloseableHttpResponse response = httpclient.execute(httpget, context)) {
            long endingTime = System.currentTimeMillis();
            HttpHost target = context.getTargetHost();
            List<URI> redirectLocations = context.getRedirectLocations();
            URI location = URIUtils.resolve(httpget.getURI(), target, redirectLocations);
            String redirectUrl = location.toString();
            curUrl.setRedirectTo(redirectUrl);
            curUrl.setResposneTime(((int) (endingTime - startingTime)) / 1000);
            redirectUrl = URLCanonicalizer.getCanonicalURL(redirectUrl);
            WebURL weburl = new WebURL(redirectUrl);
            weburl.addParent(curUrl);
            if (!config.links.contains(weburl)) {
                config.links.add(weburl);
            }
            try {
                if (redirectLocations != null) {
                    for (URI s : redirectLocations) {
                        String urls = URLCanonicalizer.getCanonicalURL(s.toString());
                        WebURL url1 = new WebURL(urls);
                        if (!config.links.contains(url1)) {
                            config.links.add(url1);
                        }
                    }
                }
            } catch (Exception ex) {
                Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
            }
            EntityUtils.consumeQuietly(response.getEntity());
            HttpClientUtils.closeQuietly(response);
        }
    } catch (IOException | URISyntaxException ex) {
        System.out.println(curUrl.getUrl());
        curUrl.setErrorMsg(ex.toString());
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        System.out.println(curUrl.getUrl());
        curUrl.setErrorMsg(ex.toString());
        Logger.getLogger(WebSpider.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        httpget.releaseConnection();
    }
}

From source file:io.cloudslang.content.httpclient.CSHttpClient.java

public Map<String, String> parseResponse(CloseableHttpResponse httpResponse, String responseCharacterSet,
        String destinationFile, URI uri, HttpClientContext httpClientContext, CookieStore cookieStore,
        SerializableSessionObject cookieStoreSessionObject) {
    Map<String, String> result = new HashMap<>();

    try {/*from www  . j  a v  a  2  s .c  o m*/
        httpResponseConsumer.setHttpResponse(httpResponse).setResponseCharacterSet(responseCharacterSet)
                .setDestinationFile(destinationFile).consume(result);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    finalLocationConsumer.setUri(uri).setRedirectLocations(httpClientContext.getRedirectLocations())
            .setTargetHost(httpClientContext.getTargetHost()).consume(result);

    headersConsumer.setHeaders(httpResponse.getAllHeaders()).consume(result);
    statusConsumer.setStatusLine(httpResponse.getStatusLine()).consume(result);

    if (cookieStore != null) {
        try {
            cookieStoreSessionObject.setValue(CookieStoreBuilder.serialize(cookieStore));
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    result.put(RETURN_CODE, SUCCESS);
    return result;
}