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

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

Introduction

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

Prototype

String METHOD_NAME

To view the source code for org.apache.http.client.methods HttpHead METHOD_NAME.

Click Source Link

Usage

From source file:spaceRedirectStrategy.java

public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    URI uri = getLocationURI(request, response, context);
    String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else {//from   ww w .  j  a  va2 s .  co m
        return new HttpGet(uri);
    }
}

From source file:com.microsoft.windowsazure.mobileservices.sdk.testapp.test.CustomApiClientTests.java

public void testInvokeWithNotSupportedMethodShouldThrowException() throws Throwable {

    // Container to store callback's results and do the asserts.
    final ResultsContainer container = new ResultsContainer();

    MobileServiceClient client = null;/*  w w  w  . java2s  . c o  m*/
    try {
        client = new MobileServiceClient(appUrl, appKey, getInstrumentation().getTargetContext());
        client.invokeApi("myApi", new Object(), HttpHead.METHOD_NAME, null, null).get();
    } catch (Exception exception) {
        container.setException(exception);
    }

    // Asserts
    Exception exception = container.getException();
    if (!(exception instanceof IllegalArgumentException)) {
        fail("Expected Exception IllegalArgumentException");
    }
}

From source file:com.amos.tool.SelfRedirectStrategy.java

public HttpUriRequest getRedirect(final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws ProtocolException {
    final URI uri = getLocationURI(request, response, context);
    final String method = request.getRequestLine().getMethod();
    if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        return new HttpHead(uri);
    } else if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        return new HttpGet(uri);
    } else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
        return new HttpPost(uri);
    } else {//from  w  w w . ja  va2 s .  c  o m
        final int status = response.getStatusLine().getStatusCode();
        if (status == HttpStatus.SC_TEMPORARY_REDIRECT) {
            return RequestBuilder.copy(request).setUri(uri).build();
        } else {
            return new HttpGet(uri);
        }
    }
}

From source file:org.elasticsearch.repositories.s3.AmazonS3Fixture.java

/** Builds the default request handlers **/
private PathTrie<RequestHandler> defaultHandlers(final Map<String, Bucket> buckets, final Bucket ec2Bucket,
        final Bucket ecsBucket) {
    final PathTrie<RequestHandler> handlers = new PathTrie<>(RestUtils.REST_DECODER);

    // HEAD Object
    ///*  w  w  w.ja  v  a  2s  . c o m*/
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html
    objectsPaths(authPath(HttpHead.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String bucketName = request.getParam("bucket");

                final Bucket bucket = buckets.get(bucketName);
                if (bucket == null) {
                    return newBucketNotFoundError(request.getId(), bucketName);
                }

                final String objectName = objectName(request.getParameters());
                for (Map.Entry<String, byte[]> object : bucket.objects.entrySet()) {
                    if (object.getKey().equals(objectName)) {
                        return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
                    }
                }
                return newObjectNotFoundError(request.getId(), objectName);
            }));

    // PUT Object
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html
    objectsPaths(authPath(HttpPut.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String destBucketName = request.getParam("bucket");

                final Bucket destBucket = buckets.get(destBucketName);
                if (destBucket == null) {
                    return newBucketNotFoundError(request.getId(), destBucketName);
                }

                final String destObjectName = objectName(request.getParameters());

                // This is a chunked upload request. We should have the header "Content-Encoding : aws-chunked,gzip"
                // to detect it but it seems that the AWS SDK does not follow the S3 guidelines here.
                //
                // See https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html
                //
                String headerDecodedContentLength = request.getHeader("X-amz-decoded-content-length");
                if (headerDecodedContentLength != null) {
                    int contentLength = Integer.valueOf(headerDecodedContentLength);

                    // Chunked requests have a payload like this:
                    //
                    // 105;chunk-signature=01d0de6be013115a7f4794db8c4b9414e6ec71262cc33ae562a71f2eaed1efe8
                    // ...  bytes of data ....
                    // 0;chunk-signature=f890420b1974c5469aaf2112e9e6f2e0334929fd45909e03c0eff7a84124f6a4
                    //
                    try (BufferedInputStream inputStream = new BufferedInputStream(
                            new ByteArrayInputStream(request.getBody()))) {
                        int b;
                        // Moves to the end of the first signature line
                        while ((b = inputStream.read()) != -1) {
                            if (b == '\n') {
                                break;
                            }
                        }

                        final byte[] bytes = new byte[contentLength];
                        inputStream.read(bytes, 0, contentLength);

                        destBucket.objects.put(destObjectName, bytes);
                        return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
                    }
                }

                return newInternalError(request.getId(), "Something is wrong with this PUT request");
            }));

    // DELETE Object
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html
    objectsPaths(authPath(HttpDelete.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String bucketName = request.getParam("bucket");

                final Bucket bucket = buckets.get(bucketName);
                if (bucket == null) {
                    return newBucketNotFoundError(request.getId(), bucketName);
                }

                final String objectName = objectName(request.getParameters());
                bucket.objects.remove(objectName);
                return new Response(RestStatus.NO_CONTENT.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
            }));

    // GET Object
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html
    objectsPaths(authPath(HttpGet.METHOD_NAME, "/{bucket}"))
            .forEach(path -> handlers.insert(path, (request) -> {
                final String bucketName = request.getParam("bucket");

                final Bucket bucket = buckets.get(bucketName);
                if (bucket == null) {
                    return newBucketNotFoundError(request.getId(), bucketName);
                }

                final String objectName = objectName(request.getParameters());
                if (bucket.objects.containsKey(objectName)) {
                    return new Response(RestStatus.OK.getStatus(), contentType("application/octet-stream"),
                            bucket.objects.get(objectName));

                }
                return newObjectNotFoundError(request.getId(), objectName);
            }));

    // HEAD Bucket
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html
    handlers.insert(authPath(HttpHead.METHOD_NAME, "/{bucket}"), (request) -> {
        String bucket = request.getParam("bucket");
        if (Strings.hasText(bucket) && buckets.containsKey(bucket)) {
            return new Response(RestStatus.OK.getStatus(), TEXT_PLAIN_CONTENT_TYPE, EMPTY_BYTE);
        } else {
            return newBucketNotFoundError(request.getId(), bucket);
        }
    });

    // GET Bucket (List Objects) Version 1
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
    handlers.insert(authPath(HttpGet.METHOD_NAME, "/{bucket}/"), (request) -> {
        final String bucketName = request.getParam("bucket");

        final Bucket bucket = buckets.get(bucketName);
        if (bucket == null) {
            return newBucketNotFoundError(request.getId(), bucketName);
        }

        String prefix = request.getParam("prefix");
        if (prefix == null) {
            prefix = request.getHeader("Prefix");
        }
        return newListBucketResultResponse(request.getId(), bucket, prefix);
    });

    // Delete Multiple Objects
    //
    // https://docs.aws.amazon.com/AmazonS3/latest/API/multiobjectdeleteapi.html
    handlers.insert(nonAuthPath(HttpPost.METHOD_NAME, "/"), (request) -> {
        final List<String> deletes = new ArrayList<>();
        final List<String> errors = new ArrayList<>();

        if (request.getParam("delete") != null) {
            // The request body is something like:
            // <Delete><Object><Key>...</Key></Object><Object><Key>...</Key></Object></Delete>
            String requestBody = Streams
                    .copyToString(new InputStreamReader(new ByteArrayInputStream(request.getBody()), UTF_8));
            if (requestBody.startsWith("<Delete>")) {
                final String startMarker = "<Key>";
                final String endMarker = "</Key>";

                int offset = 0;
                while (offset != -1) {
                    offset = requestBody.indexOf(startMarker, offset);
                    if (offset > 0) {
                        int closingOffset = requestBody.indexOf(endMarker, offset);
                        if (closingOffset != -1) {
                            offset = offset + startMarker.length();
                            final String objectName = requestBody.substring(offset, closingOffset);

                            boolean found = false;
                            for (Bucket bucket : buckets.values()) {
                                if (bucket.objects.containsKey(objectName)) {
                                    final Response authResponse = authenticateBucket(request, bucket);
                                    if (authResponse != null) {
                                        return authResponse;
                                    }
                                    bucket.objects.remove(objectName);
                                    found = true;
                                }
                            }

                            if (found) {
                                deletes.add(objectName);
                            } else {
                                errors.add(objectName);
                            }
                        }
                    }
                }
                return newDeleteResultResponse(request.getId(), deletes, errors);
            }
        }
        return newInternalError(request.getId(), "Something is wrong with this POST multiple deletes request");
    });

    // non-authorized requests

    TriFunction<String, String, String, Response> credentialResponseFunction = (profileName, key, token) -> {
        final Date expiration = new Date(new Date().getTime() + TimeUnit.DAYS.toMillis(1));
        final String response = "{" + "\"AccessKeyId\": \"" + key + "\"," + "\"Expiration\": \""
                + DateUtils.formatISO8601Date(expiration) + "\"," + "\"RoleArn\": \""
                + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"SecretAccessKey\": \""
                + randomAsciiAlphanumOfLengthBetween(random, 1, 20) + "\"," + "\"Token\": \"" + token + "\""
                + "}";

        final Map<String, String> headers = new HashMap<>(contentType("application/json"));
        return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8));
    };

    // GET
    //
    // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
    handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/"),
            (request) -> {
                final String response = EC2_PROFILE;

                final Map<String, String> headers = new HashMap<>(contentType("text/plain"));
                return new Response(RestStatus.OK.getStatus(), headers, response.getBytes(UTF_8));
            });

    // GET
    //
    // http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-roles-for-amazon-ec2.html
    handlers.insert(
            nonAuthPath(HttpGet.METHOD_NAME, "/latest/meta-data/iam/security-credentials/{profileName}"),
            (request) -> {
                final String profileName = request.getParam("profileName");
                if (EC2_PROFILE.equals(profileName) == false) {
                    return new Response(RestStatus.NOT_FOUND.getStatus(), new HashMap<>(),
                            "unknown profile".getBytes(UTF_8));
                }
                return credentialResponseFunction.apply(profileName, ec2Bucket.key, ec2Bucket.token);
            });

    // GET
    //
    // https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task-iam-roles.html
    handlers.insert(nonAuthPath(HttpGet.METHOD_NAME, "/ecs_credentials_endpoint"),
            (request) -> credentialResponseFunction.apply("CPV_ECS", ecsBucket.key, ecsBucket.token));

    return handlers;
}

From source file:org.jboss.as.test.integration.security.perimeter.WebConsoleSecurityTestCase.java

@Test
public void testHead() throws Exception {
    getConnection().setRequestMethod(HttpHead.METHOD_NAME);
    getConnection().connect();/*  www.j  a  v a 2s . co  m*/
    assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getConnection().getResponseCode());
}

From source file:org.elasticsearch.client.Request.java

static Request exists(GetRequest getRequest) {
    Request request = get(getRequest);
    return new Request(HttpHead.METHOD_NAME, request.endpoint, request.params, null);
}

From source file:org.elasticsearch.client.RequestConvertersTests.java

public void testPing() {
    Request request = RequestConverters.ping();
    assertEquals("/", request.getEndpoint());
    assertEquals(0, request.getParameters().size());
    assertNull(request.getEntity());//from w ww.ja  v  a 2s . com
    assertEquals(HttpHead.METHOD_NAME, request.getMethod());
}

From source file:org.hyperic.hq.plugin.netservices.HTTPCollector.java

public void collect() {
    if (isPingCompat.get()) {
        // back compat w/ old url.availability templates
        super.collect();
        return;//  www.j  a v  a2s .  com
    }
    this.matches.clear();
    HttpConfig config = new HttpConfig(getTimeoutMillis(), getTimeoutMillis(), proxyHost.get(),
            proxyPort.get());
    AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    log.debug("isAcceptUnverifiedCert:" + keystoreConfig.isAcceptUnverifiedCert());
    HQHttpClient client = new HQHttpClient(keystoreConfig, config, keystoreConfig.isAcceptUnverifiedCert());
    HttpParams params = client.getParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, useragent.get());
    if (this.hosthdr != null) {
        params.setParameter(ClientPNames.VIRTUAL_HOST, this.hosthdr);
    }
    HttpRequestBase request;
    double avail = 0;
    try {
        if (getMethod().equals(HttpHead.METHOD_NAME)) {
            request = new HttpHead(getURL());
            addParams(request, this.params.get());
        } else if (getMethod().equals(HttpPost.METHOD_NAME)) {
            HttpPost httpPost = new HttpPost(getURL());
            request = httpPost;
            addParams(httpPost, this.params.get());
        } else {
            request = new HttpGet(getURL());
            addParams(request, this.params.get());
        }
        request.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, isFollow());
        addCredentials(request, client);
        startTime();
        HttpResponse response = client.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        int tries = 0;
        while (statusCode == HttpURLConnection.HTTP_MOVED_TEMP && tries < 3) {
            tries++;
            Header header = response.getFirstHeader("Location");
            String url = header.getValue();
            String[] toks = url.split(";");
            String[] t = toks.length > 1 ? toks[1].split("\\?") : new String[0];
            response = getRedirect(toks[0], t.length > 1 ? t[1] : "");
            statusCode = response.getStatusLine().getStatusCode();
        }
        endTime();
        setResponseCode(statusCode);
        avail = getAvail(statusCode);
        StringBuilder msg = new StringBuilder(String.valueOf(statusCode));
        Header header = response.getFirstHeader("Server");
        msg.append(header != null ? " (" + header.getValue() + ")" : "");
        setLastModified(response, statusCode);
        avail = checkPattern(response, avail, msg);
        setAvailMsg(avail, msg);
    } catch (UnsupportedEncodingException e) {
        log.error("unsupported encoding: " + e, e);
    } catch (IOException e) {
        avail = Metric.AVAIL_DOWN;
        setErrorMessage(e.toString());
    } finally {
        setAvailability(avail);
    }
    netstat();
}

From source file:org.elasticsearch.client.Request.java

static Request ping() {
    return new Request(HttpHead.METHOD_NAME, "/", Collections.emptyMap(), null);
}