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.artifactory.addon.wicket.WicketAddonsImpl.java

@Override
public HttpRequestBase getRemoteRepoTestMethod(String repoUrl, HttpRepoDescriptor repo) {
    return new HttpHead(HttpUtils.encodeQuery(repoUrl));
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

protected HttpRequestBase getMethod(@Nonnull String httpMethod, @Nonnull String endpoint,
        @Nonnull Map<String, String> queryParams, @Nullable Map<String, String> headers, boolean authorization)
        throws CloudException, InternalException {
    HttpRequestBase method;/*from  w w  w  . j av  a 2  s.  com*/

    if (httpMethod.equals("GET")) {
        method = new HttpGet(endpoint);
    } else if (httpMethod.equals("POST")) {
        method = new HttpPost(endpoint);
    } else if (httpMethod.equals("PUT")) {
        method = new HttpPut(endpoint);
    } else if (httpMethod.equals("DELETE")) {
        method = new HttpDelete(endpoint);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpHead(endpoint);
    } else if (httpMethod.equals("OPTIONS")) {
        method = new HttpOptions(endpoint);
    } else if (httpMethod.equals("HEAD")) {
        method = new HttpTrace(endpoint);
    } else {
        method = new HttpGet(endpoint);
    }
    if (!authorization) {
        return method;
    }
    if (headers == null) {
        headers = new TreeMap<String, String>();
    }

    String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
    DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN);

    rfc1123Format.setTimeZone(TimeZone.getTimeZone("GMT"));
    headers.put("Date", rfc1123Format.format(new Date()));
    headers.put(Header_Prefix_MS + "version", VERSION);
    for (String key : headers.keySet()) {
        method.addHeader(key, headers.get(key));
    }

    if (method.getFirstHeader("content-type") == null && !httpMethod.equals("GET")) {
        method.addHeader("content-type", "application/xml;charset=utf-8");
    }
    method.addHeader("Authorization", "SharedKeyLite " + getStorageAccount() + ":"
            + calculatedSharedKeyLiteSignature(method, queryParams));
    return method;
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcp3AuthNamespaceAdapter.java

@Override
protected boolean doTestConnection() throws ConnectionTestException {
    boolean isValid = false;

    HttpUriRequest request = null;/*from www. ja v a2 s .c  o  m*/

    HttpHost httpHost;
    try {
        httpHost = new HttpHost(getHost(), getProfile().getPort(), getProfile().getProtocol());
    } catch (StorageAdapterException e) {
        throw new ConnectionTestException(e, null, getProfile().getNamespace(), getProfile().getName());
    }

    String root = getProfile().resolvePath("/");
    request = new HttpHead(root);

    // Eventually we will just return this cookie which will be passed back to the caller.
    HcapAdapterCookie cookie = new HcapAdapterCookie(request, httpHost);
    synchronized (savingCookieLock) {
        if (savedCookie != null) {
            throw new RuntimeException(
                    "This adapter already has a current connection to host -- cannot create two at once.");
        }
        savedCookie = cookie;
    }

    Throwable cause = null;
    Integer statusCode = null;
    try {
        executeMethod(cookie);
    } catch (IOException e) {
        LOG.log(Level.WARNING, "IOException during testConnection", e);
        cause = e;
        isValid = false;
    } finally {
        close();
    }

    if (cookie.getResponse() != null) {
        statusCode = cookie.getResponse().getStatusLine().getStatusCode();
    }

    if (statusCode != null && statusCode == HttpStatus.SC_OK) {
        isValid = true;
    } else if (statusCode != null && statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
        throw new ConnectionTestException("Invalid namespace access configuration for namespace "
                + getProfile().getNamespace() + " using profile " + getProfile().getName(), statusCode);
    } else if (cause != null) {
        throw new ConnectionTestException(cause, statusCode, getProfile().getNamespace(),
                getProfile().getName());
    } else {
        throw new ConnectionTestException(statusCode, getProfile().getNamespace(), getProfile().getName());
    }

    try {
        if (!doesNamespaceHavePermissions()) {
            throw new ConnectionTestException(
                    "The profile user has no explicit permissions to namespace " + getProfile().getNamespace(),
                    (Integer) null);
        }
    } catch (ConnectionTestException e) {
        throw e;
    } catch (StorageAdapterException e) {
        throw new ConnectionTestException(e, null, null, null);
    } catch (Exception e) {
        throw new ConnectionTestException(e, null, null, null);
    }

    return isValid;
}

From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java

/**
 * Creates an {@link org.apache.http.HttpRequest} object to handle a particular connection method.
 *
 * @param method/* www .  j ava2  s. co m*/
 *        the HTTP method/connection-type to use, must be one of: PUT, HEAD, GET, DELETE
 * @param bucketName
 *        the bucket's name
 * @param objectKey
 *        the object's key name, may be null if the operation is on a bucket only.
 * @return
 *        the HTTP method object used to perform the request
 *
 * @throws org.jets3t.service.ServiceException
 */
protected HttpUriRequest setupConnection(HTTP_METHOD method, String bucketName, String objectKey,
        Map<String, String> requestParameters) throws ServiceException {
    if (bucketName == null) {
        throw new ServiceException("Cannot connect to S3 Service with a null path");
    }

    boolean disableDnsBuckets = this.getDisableDnsBuckets();
    String endPoint = this.getEndpoint();
    String hostname = ServiceUtils.generateS3HostnameForBucket(bucketName, disableDnsBuckets, endPoint);

    // Allow for non-standard virtual directory paths on the server-side
    String virtualPath = this.getVirtualPath();

    // Determine the resource string (ie the item's path in S3, including the bucket name)
    String resourceString = "/";
    if (hostname.equals(endPoint) && bucketName.length() > 0) {
        resourceString += bucketName;
    }
    if (objectKey != null) {
        resourceString += "/" + RestUtils.encodeUrlString(objectKey);
    }
    //        resourceString += (objectKey != null ? RestUtils.encodeUrlString(objectKey) : "");

    // Construct a URL representing a connection for the S3 resource.
    String url = null;
    if (isHttpsOnly()) {
        int securePort = this.getHttpsPort();
        url = "https://" + hostname + ":" + securePort + virtualPath + resourceString;
    } else {
        int insecurePort = this.getHttpPort();
        url = "http://" + hostname + ":" + insecurePort + virtualPath + resourceString;
    }
    if (log.isDebugEnabled()) {
        log.debug("S3 URL: " + url);
    }

    // Add additional request parameters to the URL for special cases (eg ACL operations)
    url = addRequestParametersToUrlPath(url, requestParameters);

    HttpUriRequest httpMethod = null;
    if (HTTP_METHOD.PUT.equals(method)) {
        httpMethod = new HttpPut(url);
    } else if (HTTP_METHOD.POST.equals(method)) {
        httpMethod = new HttpPost(url);
    } else if (HTTP_METHOD.HEAD.equals(method)) {
        httpMethod = new HttpHead(url);
    } else if (HTTP_METHOD.GET.equals(method)) {
        httpMethod = new HttpGet(url);
    } else if (HTTP_METHOD.DELETE.equals(method)) {
        httpMethod = new HttpDelete(url);
    } else {
        throw new IllegalArgumentException("Unrecognised HTTP method name: " + method);
    }

    // Set mandatory Request headers.
    if (httpMethod.getFirstHeader("Date") == null) {
        httpMethod.setHeader("Date", ServiceUtils.formatRfc822Date(getCurrentTimeWithOffset()));
    }

    return httpMethod;
}

From source file:ch.iterate.openstack.swift.Client.java

/**
 * Get an object's metadata//from www  .j a  va  2  s.  c  o  m
 *
 * @param container The name of the container
 * @param object    The name of the object
 * @return The object's metadata
 * @throws GenericException       Unexpected response
 * @throws AuthorizationException The Client's Login was invalid.
 * @throws ch.iterate.openstack.swift.exception.NotFoundException
 *                                The file was not found
 */
public ObjectMetadata getObjectMetaData(Region region, String container, String object) throws IOException {
    HttpHead method = new HttpHead(region.getStorageUrl(container, object));
    return this.execute(method, new ObjectMetadataResponseHandler());
}

From source file:org.dasein.cloud.openstack.nova.os.AbstractMethod.java

protected @Nullable Map<String, String> head(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource) throws CloudException, InternalException {
    Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
    Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".head(" + authToken + "," + endpoint + ","
                + resource + ")");
    }/*from w w  w. j a v  a 2s. c  o  m*/
    if (wire.isDebugEnabled()) {
        wire.debug("--------------------------------------------------------> " + endpoint + resource);
        wire.debug("");
    }
    HttpClient client = null;
    try {
        client = getClient();
        HttpHead head = new HttpHead(endpoint + resource);

        head.addHeader("X-Auth-Token", authToken);
        if (wire.isDebugEnabled()) {
            wire.debug(head.getRequestLine().toString());
            for (Header header : head.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            APITrace.trace(provider, "HEAD " + toAPIResource(resource));
            response = client.execute(head);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);
        if (code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_OK) {
            if (code == HttpStatus.SC_NOT_FOUND) {
                return null;
            }
            std.error("Expected OK for HEAD request, got " + code);
            String data = null;

            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    data = EntityUtils.toString(entity);
                    if (wire.isDebugEnabled()) {
                        wire.debug(data);
                        wire.debug("");
                    }
                }
            } catch (IOException e) {
                std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
                e.printStackTrace();
                throw new CloudException(e);
            }
            NovaException.ExceptionItems items = NovaException.parseException(code, data);

            if (items == null) {
                return null;
            }
            std.error("head(): [" + code + " : " + items.message + "] " + items.details);
            throw new NovaException(items);
        }
        HashMap<String, String> map = new HashMap<String, String>();

        for (Header h : response.getAllHeaders()) {
            map.put(h.getName().trim(), h.getValue().trim());
        }
        return map;
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".head()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + endpoint + resource);
        }
    }
}

From source file:ch.iterate.openstack.swift.Client.java

/**
 * Get an container's metadata// w w  w  .j  a v  a  2s.c  o m
 *
 * @param container The name of the container
 * @return The container's metadata
 * @throws GenericException       Unexpected response
 * @throws AuthorizationException The Client's Login was invalid.
 */
public ContainerMetadata getContainerMetaData(Region region, String container) throws IOException {
    HttpHead method = new HttpHead(region.getStorageUrl(container));
    return this.execute(method, new ContainerMetadataResponseHandler());
}

From source file:com.infinities.skyport.openstack.nova.os.SkyportNovaMethod.java

@Override
protected @Nullable Map<String, String> head(@Nonnull String authToken, @Nonnull String endpoint,
        @Nonnull String resource) throws CloudException, InternalException {
    Logger std = NovaOpenStack.getLogger(NovaOpenStack.class, "std");
    Logger wire = NovaOpenStack.getLogger(NovaOpenStack.class, "wire");

    if (std.isTraceEnabled()) {
        std.trace("enter - " + AbstractMethod.class.getName() + ".head(" + authToken + "," + endpoint + ","
                + resource + ")");
    }/* w  w  w . j  a  v  a  2  s.co m*/
    if (wire.isDebugEnabled()) {
        wire.debug("--------------------------------------------------------> " + endpoint + resource);
        wire.debug("");
    }
    HttpClient client = null;
    try {
        client = getClient();
        HttpHead head = new HttpHead(endpoint + resource);

        head.addHeader("X-Auth-Token", authToken);
        if (wire.isDebugEnabled()) {
            wire.debug(head.getRequestLine().toString());
            for (Header header : head.getAllHeaders()) {
                wire.debug(header.getName() + ": " + header.getValue());
            }
            wire.debug("");
        }
        HttpResponse response;

        try {
            APITrace.trace(provider, "HEAD " + toAPIResource(resource));
            response = client.execute(head);
            if (wire.isDebugEnabled()) {
                wire.debug(response.getStatusLine().toString());
                for (Header header : response.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
                wire.debug("");
            }
        } catch (IOException e) {
            std.error("I/O error from server communications: " + e.getMessage());
            e.printStackTrace();
            throw new InternalException(e);
        }
        int code = response.getStatusLine().getStatusCode();

        std.debug("HTTP STATUS: " + code);
        if (code != HttpStatus.SC_NO_CONTENT && code != HttpStatus.SC_OK) {
            if (code == HttpStatus.SC_NOT_FOUND) {
                return null;
            }
            std.error("Expected OK for HEAD request, got " + code);
            String data = null;

            try {
                HttpEntity entity = response.getEntity();

                if (entity != null) {
                    data = EntityUtils.toString(entity);
                    if (wire.isDebugEnabled()) {
                        wire.debug(data);
                        wire.debug("");
                    }
                }
            } catch (IOException e) {
                std.error("Failed to read response error due to a cloud I/O error: " + e.getMessage());
                e.printStackTrace();
                throw new CloudException(e);
            }
            NovaException.ExceptionItems items = NovaException.parseException(code, data);

            if (items == null) {
                return null;
            }
            std.error("head(): [" + code + " : " + items.message + "] " + items.details);
            throw new NovaException(items);
        }
        HashMap<String, String> map = new HashMap<String, String>();

        for (Header h : response.getAllHeaders()) {
            map.put(h.getName().trim(), h.getValue().trim());
        }
        return map;
    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
        if (std.isTraceEnabled()) {
            std.trace("exit - " + AbstractMethod.class.getName() + ".head()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------> " + endpoint + resource);
        }
    }
}