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.hardisonbrewing.s3j.FileSyncer.java

public HttpResponse head(String path) throws Exception {

    String url = getUrl(path);//  w w w  . j  av  a2 s  .  c om
    HttpRequestBase httpRequest = new HttpHead(url);
    addHeaders(httpRequest, path);

    System.out.println("Head: " + url);
    HttpUtil.printHeaders(httpRequest);

    return httpClient.execute(httpRequest);
}

From source file:ch.cyberduck.core.dav.DAVSession.java

@Override
public boolean alert(final ConnectionCallback callback) throws BackgroundException {
    if (super.alert(callback)) {
        // Propose protocol change if HEAD request redirects to HTTPS
        final Path home = new DefaultHomeFinderService(this).find();
        try {//from w w w .  j a v a  2 s . co  m
            final RequestConfig context = client.context().getRequestConfig();
            final HttpHead request = new HttpHead(new DAVPathEncoder().encode(home));
            request.setConfig(RequestConfig.copy(context).setRedirectsEnabled(false).build());
            final Header location = client.execute(request, new ValidatingResponseHandler<Header>() {
                @Override
                public Header handleResponse(final HttpResponse response) throws IOException {
                    if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_PERMANENTLY) {
                        return response.getFirstHeader(HttpHeaders.LOCATION);
                    }
                    return null;
                }
            });
            // Reset default redirect configuration in context
            client.context().setRequestConfig(RequestConfig.copy(context).setRedirectsEnabled(true).build());
            if (null != location) {
                final URL url = new URL(location.getValue());
                if (StringUtils.equals(Scheme.https.name(), url.getProtocol())) {
                    try {
                        callback.warn(host,
                                MessageFormat.format(LocaleFactory.localizedString("Unsecured {0} connection",
                                        "Credentials"), host.getProtocol().getName()),
                                MessageFormat.format("{0} {1}.",
                                        MessageFormat.format(LocaleFactory.localizedString(
                                                "The server supports encrypted connections. Do you want to switch to {0}?",
                                                "Credentials"), new DAVSSLProtocol().getName()),
                                        LocaleFactory.localizedString(
                                                "Please contact your web hosting service provider for assistance",
                                                "Support")),
                                LocaleFactory.localizedString("Continue", "Credentials"),
                                LocaleFactory.localizedString("Change", "Credentials"),
                                String.format("connection.unsecure.%s", host.getHostname()));
                        // Continue chosen. Login using plain FTP.
                    } catch (LoginCanceledException e) {
                        // Protocol switch
                        host.setHostname(url.getHost());
                        host.setProtocol(ProtocolFactory.get().forScheme(Scheme.davs));
                        return false;
                    }
                }
            }
            // Continue with default alert
        } catch (SardineException e) {
            // Ignore failure
            log.warn(String.format("Ignore failed HEAD request to %s with %s.", host, e.getResponsePhrase()));
        } catch (IOException e) {
            throw new HttpExceptionMappingService().map(e);
        }
        return preferences.getBoolean("webdav.basic.preemptive");
    }
    return false;
}

From source file:uk.co.tfd.sm.proxy.ProxyClientServiceImpl.java

/**
 * Executes a HTTP call using a path in the JCR to point to a template and a
 * map of properties to populate that template with. An example might be a
 * SOAP call.//from   w w w  .  j  a va  2  s  .  c o  m
 * 
 * <pre>
 * {http://www.w3.org/2001/12/soap-envelope}Envelope:{
 *  {http://www.w3.org/2001/12/soap-envelope}Body:{
 *   {http://www.example.org/stock}GetStockPriceResponse:{
 *    &gt;body:[       ]
 *    {http://www.example.org/stock}Price:{
 *     &gt;body:[34.5]
 *    }
 *   }
 *   &gt;body:[  ]
 *  }
 *  &gt;body:[   ]
 *  {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding]
 * }
 * 
 * </pre>
 * 
 * @param resource
 *            the resource containing the proxy end point specification.
 * @param headers
 *            a map of headers to set int the request.
 * @param input
 *            a map of parameters for all templates (both url and body)
 * @param requestInputStream
 *            containing the request body (can be null if the call requires
 *            no body or the template will be used to generate the body)
 * @param requestContentLength
 *            if the requestImputStream is specified, the length specifies
 *            the lenght of the body.
 * @param requerstContentType
 *            the content type of the request, if null the node property
 *            sakai:proxy-request-content-type will be used.
 * @throws ProxyClientException
 */
public ProxyResponse executeCall(Map<String, Object> config, Map<String, Object> headers,
        Map<String, Object> input, InputStream requestInputStream, long requestContentLength,
        String requestContentType) throws ProxyClientException {
    try {
        LOGGER.info(
                "Calling Execute Call with Config:[{}] Headers:[{}] Input:[{}] "
                        + "RequestInputStream:[{}] InputStreamContentLength:[{}] RequestContentType:[{}] ",
                new Object[] { config, headers, input, requestInputStream, requestContentLength,
                        requestContentType });
        bindConfig(config);

        if (config != null && config.containsKey(CONFIG_REQUEST_PROXY_ENDPOINT)) {
            // setup the post request
            String endpointURL = (String) config.get(CONFIG_REQUEST_PROXY_ENDPOINT);
            if (isUnsafeProxyDefinition(config)) {
                try {
                    URL u = new URL(endpointURL);
                    String host = u.getHost();
                    if (host.indexOf('$') >= 0) {
                        throw new ProxyClientException(
                                "Invalid Endpoint template, relies on request to resolve valid URL " + u);
                    }
                } catch (MalformedURLException e) {
                    throw new ProxyClientException(
                            "Invalid Endpoint template, relies on request to resolve valid URL", e);
                }
            }

            LOGGER.info("Valied Endpoint Def");

            Map<String, Object> context = Maps.newHashMap(input);

            // add in the config properties from the bundle overwriting
            // everything else.
            context.put("config", configProperties);

            endpointURL = processUrlTemplate(endpointURL, context);

            LOGGER.info("Calling URL {} ", endpointURL);

            ProxyMethod proxyMethod = ProxyMethod.GET;
            if (config.containsKey(CONFIG_REQUEST_PROXY_METHOD)) {
                try {
                    proxyMethod = ProxyMethod.valueOf((String) config.get(CONFIG_REQUEST_PROXY_METHOD));
                } catch (Exception e) {

                }
            }

            HttpClient client = getHttpClient();

            HttpUriRequest method = null;
            switch (proxyMethod) {
            case GET:
                if (config.containsKey(CONFIG_LIMIT_GET_SIZE)) {
                    long maxSize = (Long) config.get(CONFIG_LIMIT_GET_SIZE);
                    HttpHead h = new HttpHead(endpointURL);

                    HttpParams params = h.getParams();
                    // make certain we reject the body of a head
                    params.setBooleanParameter("http.protocol.reject-head-body", true);
                    h.setParams(params);
                    populateMessage(method, config, headers);
                    HttpResponse response = client.execute(h);
                    if (response.getStatusLine().getStatusCode() == 200) {
                        // Check if the content-length is smaller than the
                        // maximum (if any).
                        Header contentLengthHeader = response.getLastHeader("Content-Length");
                        if (contentLengthHeader != null) {
                            long length = Long.parseLong(contentLengthHeader.getValue());
                            if (length > maxSize) {
                                return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED,
                                        "Response too large", response);
                            }
                        }
                    } else {
                        return new ProxyResponseImpl(response);
                    }
                }
                method = new HttpGet(endpointURL);
                break;
            case HEAD:
                method = new HttpHead(endpointURL);
                break;
            case OPTIONS:
                method = new HttpOptions(endpointURL);
                break;
            case POST:
                method = new HttpPost(endpointURL);
                break;
            case PUT:
                method = new HttpPut(endpointURL);
                break;
            default:
                method = new HttpGet(endpointURL);
            }

            populateMessage(method, config, headers);

            if (requestInputStream == null && !config.containsKey(CONFIG_PROXY_REQUEST_TEMPLATE)) {
                if (method instanceof HttpPost) {
                    HttpPost postMethod = (HttpPost) method;
                    MultipartEntity multipart = new MultipartEntity();
                    for (Entry<String, Object> param : input.entrySet()) {
                        String key = param.getKey();
                        Object value = param.getValue();
                        if (value instanceof Object[]) {
                            for (Object val : (Object[]) value) {
                                addPart(multipart, key, val);
                            }
                        } else {
                            addPart(multipart, key, value);
                        }
                        postMethod.setEntity(multipart);
                    }
                }
            } else {

                if (method instanceof HttpEntityEnclosingRequestBase) {
                    String contentType = requestContentType;
                    if (contentType == null && config.containsKey(CONFIG_REQUEST_CONTENT_TYPE)) {
                        contentType = (String) config.get(CONFIG_REQUEST_CONTENT_TYPE);

                    }
                    if (contentType == null) {
                        contentType = APPLICATION_OCTET_STREAM;
                    }
                    HttpEntityEnclosingRequestBase eemethod = (HttpEntityEnclosingRequestBase) method;
                    if (requestInputStream != null) {
                        eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
                        eemethod.setEntity(new InputStreamEntity(requestInputStream, requestContentLength));
                    } else {
                        // build the request
                        StringWriter body = new StringWriter();
                        templateService.evaluate(context, body, (String) config.get("path"),
                                (String) config.get(CONFIG_PROXY_REQUEST_TEMPLATE));
                        byte[] soapBodyContent = body.toString().getBytes("UTF-8");
                        eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
                        eemethod.setEntity(new InputStreamEntity(new ByteArrayInputStream(soapBodyContent),
                                soapBodyContent.length));

                    }
                }
            }

            HttpResponse response = client.execute(method);
            if (response.getStatusLine().getStatusCode() == 302
                    && method instanceof HttpEntityEnclosingRequestBase) {
                // handle redirects on post and put
                String url = response.getFirstHeader("Location").getValue();
                method = new HttpGet(url);
                response = client.execute(method);
            }

            return new ProxyResponseImpl(response);
        }

    } catch (ProxyClientException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new ProxyClientException("The Proxy request specified by  " + config + " failed, cause follows:",
                e);
    } finally {
        unbindConfig();
    }
    throw new ProxyClientException(
            "The Proxy request specified by " + config + " does not contain a valid endpoint specification ");
}

From source file:com.hoccer.tools.HttpHelper.java

public static long getSize(String url) throws IOException, HttpClientException, HttpServerException {

    HttpHead head = new HttpHead(url);
    HttpResponse response = executeHTTPMethod(head);

    if (!response.containsHeader("Content-Length")) {
        throw new RuntimeException("Could not retrieve content-length header.");
    }/*  w w w.  jav a 2s.  c o m*/

    return new Long(response.getFirstHeader("Content-Length").getValue());
}

From source file:edu.isi.misd.tagfiler.client.JakartaClient.java

/**
 * Get the length of a file to be downloaded
 * //from w w w  .  ja  va  2 s  .  co  m
 * @param url
 *            the query url
 * @param cookie
 *            the cookie to be set in the request
 * @return the HTTP Response
 */
public ClientURLResponse getFileLength(String url, String cookie) {
    HttpHead httphead = new HttpHead(url);
    httphead.setHeader("Accept", "text/uri-list");
    httphead.setHeader("Content-Type", "application/octet-stream");
    return execute(httphead, cookie);
}

From source file:edu.jhu.pha.vospace.storage.SwiftKeystoneStorageManager.java

public static FilesContainerInfo getContainerInfo(String container)
        throws IOException, HttpException, FilesException {

    if (isValidContainerName(container)) {

        HttpHead method = null;/*from w w  w . ja v a  2s. c o  m*/

        try {
            method = new HttpHead(getFileUrl + "/" + sanitizeForURI(container));
            method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
            method.setHeader(FilesConstants.X_AUTH_TOKEN, strToken);
            FilesResponse response = new FilesResponse(client.execute(method));

            if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
                int objCount = response.getContainerObjectCount();
                long objSize = response.getContainerBytesUsed();
                String syncTo = response.getContainerSyncTo();
                return new FilesContainerInfo(container, objCount, objSize, syncTo);
            } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                throw new FilesNotFoundException("Container not found: " + container,
                        response.getResponseHeaders(), response.getStatusLine());
            } else {
                throw new FilesException("Unexpected result from server", response.getResponseHeaders(),
                        response.getStatusLine());
            }
        } finally {
            if (method != null)
                method.abort();
        }
    } else {
        throw new FilesInvalidNameException(container);
    }

}

From source file:org.opencastproject.distribution.download.DownloadDistributionService.java

/**
 * Distribute a Mediapackage element to the download distribution service.
 * //from w  w  w .j  a  v  a2s  .co m
 * @param mediapackage
 *          The media package that contains the element to distribute.
 * @param elementId
 *          The id of the element that should be distributed contained within the media package.
 * @return A reference to the MediaPackageElement that has been distributed.
 * @throws DistributionException
 *           Thrown if the parent directory of the MediaPackageElement cannot be created, if the MediaPackageElement
 *           cannot be copied or another unexpected exception occurs.
 */
public MediaPackageElement distributeElement(MediaPackage mediapackage, String elementId)
        throws DistributionException {
    if (mediapackage == null)
        throw new IllegalArgumentException("Mediapackage must be specified");
    if (elementId == null)
        throw new IllegalArgumentException("Element ID must be specified");

    String mediaPackageId = mediapackage.getIdentifier().compact();
    MediaPackageElement element = mediapackage.getElementById(elementId);

    // Make sure the element exists
    if (mediapackage.getElementById(elementId) == null)
        throw new IllegalStateException("No element " + elementId + " found in mediapackage");

    try {
        File source;
        try {
            source = workspace.get(element.getURI());
        } catch (NotFoundException e) {
            throw new DistributionException("Unable to find " + element.getURI() + " in the workspace", e);
        } catch (IOException e) {
            throw new DistributionException("Error loading " + element.getURI() + " from the workspace", e);
        }
        File destination = getDistributionFile(mediapackage, element);

        // Put the file in place
        try {
            FileUtils.forceMkdir(destination.getParentFile());
        } catch (IOException e) {
            throw new DistributionException("Unable to create " + destination.getParentFile(), e);
        }
        logger.info("Distributing {} to {}", elementId, destination);

        try {
            FileSupport.link(source, destination, true);
        } catch (IOException e) {
            throw new DistributionException("Unable to copy " + source + " to " + destination, e);
        }

        // Create a representation of the distributed file in the mediapackage
        MediaPackageElement distributedElement = (MediaPackageElement) element.clone();
        try {
            distributedElement.setURI(getDistributionUri(mediaPackageId, element));
        } catch (URISyntaxException e) {
            throw new DistributionException("Distributed element produces an invalid URI", e);
        }
        distributedElement.setIdentifier(null);

        logger.info("Finished distribution of {}", element);
        URI uri = distributedElement.getURI();
        long now = 0L;
        while (true) {
            HttpResponse response = trustedHttpClient.execute(new HttpHead(uri));
            if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK)
                break;

            if (now < TIMEOUT) {
                try {
                    Thread.sleep(INTERVAL);
                    now += INTERVAL;
                    continue;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            logger.warn("Status code of distributed file {}: {}", uri,
                    response.getStatusLine().getStatusCode());
            throw new DistributionException("Unable to load distributed file " + uri.toString());
        }
        return distributedElement;
    } catch (Exception e) {
        logger.warn("Error distributing " + element, e);
        if (e instanceof DistributionException) {
            throw (DistributionException) e;
        } else {
            throw new DistributionException(e);
        }
    }
}

From source file:org.opencastproject.distribution.download.DownloadDistributionServiceImpl.java

/**
 * Distribute a Mediapackage element to the download distribution service.
 * /*from   w  w w. j a  v a  2  s. c  o  m*/
 * @param mediapackage
 *          The media package that contains the element to distribute.
 * @param elementId
 *          The id of the element that should be distributed contained within the media package.
 * @param checkAvailability
 *          Check the availability of the distributed element via http.
 * @return A reference to the MediaPackageElement that has been distributed.
 * @throws DistributionException
 *           Thrown if the parent directory of the MediaPackageElement cannot be created, if the MediaPackageElement
 *           cannot be copied or another unexpected exception occurs.
 */
public MediaPackageElement distributeElement(String channelId, MediaPackage mediapackage, String elementId,
        boolean checkAvailability) throws DistributionException {
    notNull(mediapackage, "mediapackage");
    notNull(elementId, "elementId");
    notNull(channelId, "channelId");

    final String mediapackageId = mediapackage.getIdentifier().compact();
    final MediaPackageElement element = mediapackage.getElementById(elementId);

    // Make sure the element exists
    if (mediapackage.getElementById(elementId) == null)
        throw new IllegalStateException(
                format("No element %s found in mediapackage %s", elementId, mediapackageId));

    try {
        File source;
        try {
            source = workspace.get(element.getURI());
        } catch (NotFoundException e) {
            throw new DistributionException("Unable to find " + element.getURI() + " in the workspace", e);
        } catch (IOException e) {
            throw new DistributionException("Error loading " + element.getURI() + " from the workspace", e);
        }
        File destination = getDistributionFile(channelId, mediapackage, element);

        // Put the file in place
        try {
            FileUtils.forceMkdir(destination.getParentFile());
        } catch (IOException e) {
            throw new DistributionException("Unable to create " + destination.getParentFile(), e);
        }
        logger.info(format("Distributing %s@%s for publication channel %s to %s", elementId, mediapackageId,
                channelId, destination));

        try {
            FileSupport.link(source, destination, true);
        } catch (IOException e) {
            throw new DistributionException(format("Unable to copy %s tp %s", source, destination), e);
        }

        // Create a representation of the distributed file in the mediapackage
        MediaPackageElement distributedElement = (MediaPackageElement) element.clone();
        try {
            distributedElement.setURI(getDistributionUri(channelId, mediapackageId, element));
        } catch (URISyntaxException e) {
            throw new DistributionException("Distributed element produces an invalid URI", e);
        }
        distributedElement.setIdentifier(null);

        logger.info(format("Finished distributing element %s@%s for publication channel %s", elementId,
                mediapackageId, channelId));
        URI uri = distributedElement.getURI();
        long now = 0L;
        while (checkAvailability) {
            HttpResponse response = trustedHttpClient.execute(new HttpHead(uri));
            if (response.getStatusLine().getStatusCode() == HttpServletResponse.SC_OK)
                break;

            if (now < TIMEOUT) {
                try {
                    Thread.sleep(INTERVAL);
                    now += INTERVAL;
                    continue;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            logger.warn("Status code of distributed file {}: {}", uri,
                    response.getStatusLine().getStatusCode());
            throw new DistributionException("Unable to load distributed file " + uri.toString());
        }
        return distributedElement;
    } catch (Exception e) {
        logger.warn("Error distributing " + element, e);
        if (e instanceof DistributionException) {
            throw (DistributionException) e;
        } else {
            throw new DistributionException(e);
        }
    }
}

From source file:com.anaplan.client.transport.ApacheHttpProvider.java

/** {@inheritDoc} */
@Override/*  w  w w. j a va2s.co m*/
public boolean head(String path) throws AnaplanAPITransportException {
    try {
        HttpHead httpHead = new HttpHead(getRequestPath(path));
        if (getDebugLevel() >= 1) {
            System.err.println(httpHead.getRequestLine().toString());
        }

        HttpResponse httpResponse = httpClient.execute(httpHost, httpHead, httpContext);
        HttpEntity httpEntity = httpResponse.getEntity();
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (200 <= statusCode && statusCode <= 299) {
            if (httpEntity != null) {
                EntityUtils.consume(httpEntity);
            }
            return true;
        } else if (statusCode == 404) {
            if (httpEntity != null) {
                EntityUtils.consume(httpEntity);
            }
            return false;
        }
        checkResponse(httpResponse);
        // Dead code - checkResponse should have thrown an exception
        return false;

    } catch (IOException ioException) {
        throw new AnaplanAPITransportException(getMessage(MSG_COMMS_FAILURE), ioException);
    }
}

From source file:com.ebixio.virtmus.stats.StatsLogger.java

/** Figure out where we should upload the logs.
 *
 * We don't want to post/send the entire log only to be redirected at the end.
 * We'll do a HEAD request instead (assuming that both HEAD and POST are
 * redirected the same way) to see if there is any redirection, and if there
 * is, this gives us a chance to POST to the new URI.
 *
 * @return If the return is null, it means we encountered a (temporary or
 * permanent) error./*from  ww  w  .  j a v  a  2s.c  o m*/
 */
private String getUploadUrl() {
    final String url = pref.get(Options.OptStatsUploadUrl, STATS_UPLOAD);
    String newUrl = null;

    HttpRedirectStrategy httpRedirect = new HttpRedirectStrategy() {
        @Override
        public void handlePermanentRedirect(HttpRequest request, HttpResponse response,
                HttpUriRequest redirect) {
            if (!Utils.isNullOrEmpty(newUrl) && !newUrl.equals(url)) {
                pref.put(Options.OptStatsUploadUrl, newUrl);
            }
        }
    };

    CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(httpRedirect).build();
    HttpHead head = new HttpHead(url);
    addHttpHeaders(head);

    int status = 0;
    try (CloseableHttpResponse response = client.execute(head)) {
        status = response.getStatusLine().getStatusCode();

        if (status == HttpStatus.SC_OK) {
            if (httpRedirect.wasRedirected()) {
                newUrl = httpRedirect.getNewUrl();
            } else {
                newUrl = url;
            }
        } else {
            if (httpRedirect.wasRedirected()) {
                /* This means either we got an error either at the original URI
                or somewhere along the redirection chain. Either way, we restore
                the original URI in case one of the redirects caused us to update
                the options. */
                pref.put(Options.OptStatsUploadUrl, url);
            }
            newUrl = null;
        }

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
    } catch (IOException ex) {
        // Ignore it. We don't have a network connection
        // TODO: Distinguish b/w no network and ebixio.com being down?
    }

    if (newUrl == null) {
        LogRecord rec = new LogRecord(Level.INFO, "HTTP Err");
        rec.setParameters(
                new Object[] { url, "Status: " + status, "Redirect: " + httpRedirect.wasRedirected() });
        getLogger().log(rec);
    }

    return newUrl;
}