Example usage for org.apache.http.client.methods HttpHead HttpHead

List of usage examples for org.apache.http.client.methods HttpHead HttpHead

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpHead HttpHead.

Prototype

public HttpHead(final String uri) 

Source Link

Usage

From source file:org.fcrepo.indexer.JcrXmlRetriever.java

@Override
/**//from  ww w  .  j ava  2 s .co  m
 * Retrieve jcr/xml with no binary contents from the repository
 */
public InputStream get() {

    try {
        // make an initial HEAD request and check Link headers for descriptions located elsewhere
        final HttpHead headRequest = new HttpHead(identifier);
        final HttpResponse headResponse = httpClient.execute(headRequest);
        URI descriptionURI = null;
        final Header[] links = headResponse.getHeaders("Link");
        if (links != null) {
            for (Header h : headResponse.getHeaders("Link")) {
                final Link link = Link.valueOf(h.getValue());
                if (link.getRel().equals("describedby")) {
                    descriptionURI = link.getUri();
                    LOGGER.debug("Using URI from Link header: {}", descriptionURI);
                }
            }
        }
        if (descriptionURI == null) {
            descriptionURI = identifier;
        }

        final HttpUriRequest request = new HttpGet(descriptionURI.toString() + "/fcr:export?skipBinary=true");
        LOGGER.debug("Retrieving jcr/xml content from: {}...", request.getURI());
        final HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() == SC_OK) {
            return response.getEntity().getContent();
        } else {
            throw new HttpException(response.getStatusLine().getStatusCode() + " : "
                    + EntityUtils.toString(response.getEntity()));
        }
    } catch (IOException | HttpException e) {
        throw propagate(e);
    }
}

From source file:tech.beshu.ror.integration.FieldLevelSecurityTests.java

private static void insertDoc(String docName, RestClient restClient, String idx, String field) {
    if (adminClient == null) {
        adminClient = restClient;/*from   w ww. ja  v a 2 s .  c om*/
    }

    String path = "/" + IDX_PREFIX + idx + "/documents/doc-" + docName + String.valueOf(Math.random());
    try {

        HttpPut request = new HttpPut(restClient.from(path));
        request.setHeader("Content-Type", "application/json");
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");

        String body = "{\"" + field + "\": \"" + docName + "\", \"dummy2\": true}";
        System.out.println("inserting: " + body);
        request.setEntity(new StringEntity(body));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        Thread.sleep(5000);

        HttpResponse response;
        do {
            HttpHead request = new HttpHead(restClient.from(path));
            request.setHeader("x-api-key", "p");
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
            Thread.sleep(200);
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }

}

From source file:org.dataconservancy.dcs.ingest.client.impl.HttpDepositDocument.java

public Map<String, String> getMetadata() {
    poll(new HttpHead(docUrl));

    Map<String, String> metadata = new HashMap<String, String>();
    for (Header h : headers) {
        if (!metadata.containsKey(h.getName())) {
            metadata.put(h.getName(), h.getValue());
        } else {/* w  w  w.  j a v a 2 s .  c om*/
            metadata.put(h.getName(), String.format("%s,%s", metadata.get(h.getName()), h.getValue()));
        }
    }
    return metadata;
}

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

public static HttpUriRequest createRequest(String method, String uri, HttpEntity entity,
        RequestOptions options) {/*  ww w.j av a 2  s .co  m*/
    if (method == null)
        return null;
    if (options == null)
        options = createAtomDefaultRequestOptions().get();
    Method m = Method.get(method);
    Method actual = null;
    HttpUriRequest httpMethod = null;
    if (options.isUsePostOverride() && !nopostoveride.contains(m)) {
        actual = m;
        m = Method.POST;
    }
    if (m == GET)
        httpMethod = new HttpGet(uri);
    else if (m == POST) {
        httpMethod = new HttpPost(uri);
        if (entity != null)
            ((HttpPost) httpMethod).setEntity(entity);
    } else if (m == PUT) {
        httpMethod = new HttpPut(uri);
        if (entity != null)
            ((HttpPut) httpMethod).setEntity(entity);
    } else if (m == DELETE)
        httpMethod = new HttpDelete(uri);
    else if (m == HEAD)
        httpMethod = new HttpHead(uri);
    else if (m == OPTIONS)
        httpMethod = new HttpOptions(uri);
    else if (m == TRACE)
        httpMethod = new HttpTrace(uri);
    //        else if (m == PATCH)
    //          httpMethod = new ExtensionRequest(m.name(),uri,entity);
    else
        httpMethod = new ExtensionRequest(m.name(), uri, entity);
    if (actual != null) {
        httpMethod.addHeader("X-HTTP-Method-Override", actual.name());
    }
    initHeaders(options, httpMethod);
    HttpParams params = httpMethod.getParams();
    if (!options.isUseExpectContinue()) {
        params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    } else {
        if (options.getWaitForContinue() > -1)
            params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, options.getWaitForContinue());
    }
    if (!(httpMethod instanceof HttpEntityEnclosingRequest))
        params.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, options.isFollowRedirects());
    return httpMethod;
}

From source file:org.gradle.internal.resource.transport.http.HttpClientHelper.java

public HttpResponse performRawHead(String source) {
    return performRequest(new HttpHead(source));
}

From source file:org.bireme.cl.CheckUrl.java

public static int check(final String url, final boolean checkOnlyHeader) {
    if (url == null) {
        throw new NullPointerException();
    }/*from   w  w w  .  j a  va 2  s . co  m*/

    final CloseableHttpClient httpclient = HttpClients.createDefault();
    int responseCode = -1;

    try {
        final HttpRequestBase httpX = checkOnlyHeader ? new HttpHead(fixUrl(url)) : new HttpGet(fixUrl(url));
        //final HttpHead httpX = new HttpHead(fixUrl(url)); // Some servers return 500
        //final HttpGet httpX = new HttpGet(fixUrl(url));
        httpX.setConfig(CONFIG);
        httpX.setHeader(new BasicHeader("User-Agent", "Wget/1.16.1 (linux-gnu)"));
        httpX.setHeader(new BasicHeader("Accept", "*/*"));
        httpX.setHeader(new BasicHeader("Accept-Encoding", "identity"));
        httpX.setHeader(new BasicHeader("Connection", "Keep-Alive"));

        // Create a custom response handler
        final ResponseHandler<Integer> responseHandler = new ResponseHandler<Integer>() {

            @Override
            public Integer handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                return response.getStatusLine().getStatusCode();
            }
        };
        responseCode = httpclient.execute(httpX, responseHandler);
    } catch (Exception ex) {
        responseCode = getExceptionCode(ex);
    } finally {
        try {
            httpclient.close();
        } catch (Exception ioe) {
            System.err.println(ioe.getMessage());
        }
    }
    return (((responseCode == 403) || (responseCode == 500)) && checkOnlyHeader) ? check(url, false)
            : responseCode;
}

From source file:tech.beshu.ror.integration.ClosedIndicesTests.java

private static void insertDoc(String docName, RestClient restClient) {
    if (adminClient == null) {
        adminClient = restClient;//from   w w  w  .ja  v a 2 s.  c o  m
    }

    String path = "/" + IDX_PREFIX + docName + "/documents/doc-" + docName;
    try {

        HttpPut request = new HttpPut(restClient.from(path));
        request.setHeader("Content-Type", "application/json");
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");
        request.setEntity(new StringEntity("{\"title\": \"" + docName + "\"}"));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        HttpResponse response;
        do {
            HttpHead request = new HttpHead(restClient.from(path));
            request.setHeader("x-api-key", "p");
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
            Thread.sleep(200);
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }
}

From source file:org.modeshape.jcr.index.elasticsearch.client.EsClient.java

/**
 * Tests for the index existence with specified name.
 *
 * @param name the name of the index to test.
 * @return true if index with given name exists and false otherwise.
 * @throws IOException communication exception.
 *///from w w w  . j  a v  a  2  s  .c  o m
public boolean indexExists(String name) throws IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpHead head = new HttpHead(String.format("http://%s:%d/%s", host, port, name));
    try {
        CloseableHttpResponse response = client.execute(head);
        return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
    } finally {
        head.releaseConnection();
    }
}

From source file:org.dspace.app.util.WebAppServiceImpl.java

@Override
public List<WebApp> getApps() {
    ArrayList<WebApp> apps = new ArrayList<>();

    Context context = null;//w w w  .j  av  a2  s  .  co m
    HttpHead method = null;
    try {
        context = new Context();
        List<WebApp> webApps = findAll(context);

        for (WebApp app : webApps) {
            method = new HttpHead(app.getUrl());
            HttpClient client = new DefaultHttpClient();
            HttpResponse response = client.execute(method);
            int status = response.getStatusLine().getStatusCode();
            if (status != HttpStatus.SC_OK) {
                delete(context, app

                );
                continue;
            }

            apps.add(app);
        }
    } catch (SQLException e) {
        log.error("Unable to list running applications", e);
    } catch (IOException e) {
        log.error("Failure checking for a running webapp", e);
    } finally {
        if (null != method) {
            method.releaseConnection();
        }
        if (null != context) {
            context.abort();
        }
    }

    return apps;
}

From source file:de.unirostock.sems.cbarchive.web.HttpImporter.java

private boolean checkFile() throws ImporterException {

    try {//from  ww w.j  a  va2 s .com
        HttpResponse headResponse = client.execute(new HttpHead(remoteUrl));

        // check if file exists
        if (headResponse.getStatusLine().getStatusCode() != 200) {
            LOGGER.error(headResponse.getStatusLine().getStatusCode(), " ",
                    headResponse.getStatusLine().getReasonPhrase(), " while check ", remoteUrl);
            throw new ImporterException(String.valueOf(headResponse.getStatusLine().getStatusCode()) + " "
                    + headResponse.getStatusLine().getReasonPhrase() + " while check");
        }

        // check if file is in the Quota range
        Header contentLengthHeader = headResponse.getFirstHeader("Content-Length");

        // check if Content-Size header is set
        if (contentLengthHeader != null && contentLengthHeader.getValue() != null
                && contentLengthHeader.getValue().isEmpty() == false) {
            length = Long.valueOf(contentLengthHeader.getValue());
        } else {
            LOGGER.warn("Remote file ", remoteUrl, " does not provide Content-Length");
            throw new ImporterException("Remote file does not provide Content-Length");
        }

        // compares this header with the quota
        checkQuotas();

    } catch (IOException e) {
        LOGGER.error(e, "Exception while check file from ", remoteUrl);
        throw new ImporterException("Exception while check remote file", e);
    }

    return true;
}