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

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

Introduction

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

Prototype

String METHOD_NAME

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

Click Source Link

Usage

From source file:org.jtalks.poulpe.service.JcommuneHttpNotifier.java

/**
 * Notifies JCommune that an element is about to be deleted (for instance Component, Branch, Section).
 *
 * @param url JCommune Url//from  w w  w .j a va 2s . c o m
 * @throws NoConnectionToJcommuneException
 *          some connection problems happened, while trying to notify Jcommune
 * @throws JcommuneRespondedWithErrorException
 *          occurs when the response status is not in the interval {@code MIN_HTTP_STATUS} and {@code
 *          MAX_HTTP_STATUS}
 * @throws JcommuneUrlNotConfiguredException
 *          occurs when the {@code url} is incorrect
 */
protected void notifyAboutDeleteElement(String url) throws NoConnectionToJcommuneException,
        JcommuneRespondedWithErrorException, JcommuneUrlNotConfiguredException {
    checkUrlIsConfigured(url);
    createAndSendRequest(url, HttpDelete.METHOD_NAME);
}

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

@Test
public void testDelete() throws Exception {
    getConnection().setRequestMethod(HttpDelete.METHOD_NAME);
    getConnection().connect();//from ww w .j a  va 2 s . co m
    assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, getConnection().getResponseCode());
}

From source file:com.uploader.Vimeo.java

public VimeoResponse removeTextTrack(String videoEndPoint, String textTrackId) throws IOException {
    return apiRequest(new StringBuffer(videoEndPoint).append("/texttracks/").append(textTrackId).toString(),
            HttpDelete.METHOD_NAME, null, null);
}

From source file:com.clickntap.vimeo.Vimeo.java

private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file)
        throws IOException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpRequestBase request = null;//from   www  .ja v  a2 s. com
    String url = null;
    if (endpoint.startsWith("http")) {
        url = endpoint;
    } else {
        url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString();
    }
    if (methodName.equals(HttpGet.METHOD_NAME)) {
        request = new HttpGet(url);
    } else if (methodName.equals(HttpPost.METHOD_NAME)) {
        request = new HttpPost(url);
    } else if (methodName.equals(HttpPut.METHOD_NAME)) {
        request = new HttpPut(url);
    } else if (methodName.equals(HttpDelete.METHOD_NAME)) {
        request = new HttpDelete(url);
    } else if (methodName.equals(HttpPatch.METHOD_NAME)) {
        request = new HttpPatch(url);
    }
    request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2");
    request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString());
    HttpEntity entity = null;
    if (params != null) {
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            postParameters.add(new BasicNameValuePair(key, params.get(key)));
        }
        entity = new UrlEncodedFormEntity(postParameters);
    } else if (file != null) {
        entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA);
    }
    if (entity != null) {
        if (request instanceof HttpPost) {
            ((HttpPost) request).setEntity(entity);
        } else if (request instanceof HttpPatch) {
            ((HttpPatch) request).setEntity(entity);
        } else if (request instanceof HttpPut) {
            ((HttpPut) request).setEntity(entity);
        }
    }
    CloseableHttpResponse response = client.execute(request);
    String responseAsString = null;
    int statusCode = response.getStatusLine().getStatusCode();
    if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) {
        JSONObject out = new JSONObject();
        for (Header header : response.getAllHeaders()) {
            out.put(header.getName(), header.getValue());
        }
        responseAsString = out.toString();
    } else if (statusCode != 204) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        responseAsString = out.toString("UTF-8");
        out.close();
    }
    JSONObject json = null;
    try {
        json = new JSONObject(responseAsString);
    } catch (Exception e) {
        json = new JSONObject();
    }
    VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode);
    response.close();
    client.close();
    return vimeoResponse;
}

From source file:com.uploader.Vimeo.java

private VimeoResponse apiRequest(String endpoint, String methodName, Map<String, String> params, File file)
        throws IOException {

    // try(CloseableHttpClient client = HttpClientBuilder.create().build()) {

    CloseableHttpClient client = HttpClientBuilder.create().build();
    // CloseableHttpClient client = HttpClients.createDefault();
    System.out.println("Building HTTP Client");

    // try {// w  w w. j a  va 2  s .c  o  m
    //     client = 
    // }   catch(Exception e) {
    //     System.out.println("Err in CloseableHttpClient");
    // }

    // System.out.println(client);

    HttpRequestBase request = null;
    String url = null;
    if (endpoint.startsWith("http")) {
        url = endpoint;
    } else {
        url = new StringBuffer(VIMEO_SERVER).append(endpoint).toString();
    }
    System.out.println(url);
    if (methodName.equals(HttpGet.METHOD_NAME)) {
        request = new HttpGet(url);
    } else if (methodName.equals(HttpPost.METHOD_NAME)) {
        request = new HttpPost(url);
    } else if (methodName.equals(HttpPut.METHOD_NAME)) {
        request = new HttpPut(url);
    } else if (methodName.equals(HttpDelete.METHOD_NAME)) {
        request = new HttpDelete(url);
    } else if (methodName.equals(HttpPatch.METHOD_NAME)) {
        request = new HttpPatch(url);
    }

    request.addHeader("Accept", "application/vnd.vimeo.*+json; version=3.2");
    request.addHeader("Authorization", new StringBuffer(tokenType).append(" ").append(token).toString());

    HttpEntity entity = null;
    if (params != null) {
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        for (String key : params.keySet()) {
            postParameters.add(new BasicNameValuePair(key, params.get(key)));
        }
        entity = new UrlEncodedFormEntity(postParameters);
    } else {
        if (file != null) {
            entity = new FileEntity(file, ContentType.MULTIPART_FORM_DATA);
        }
    }
    if (entity != null) {
        if (request instanceof HttpPost) {
            ((HttpPost) request).setEntity(entity);
        } else if (request instanceof HttpPatch) {
            ((HttpPatch) request).setEntity(entity);
        } else if (request instanceof HttpPut) {
            ((HttpPut) request).setEntity(entity);
        }
    }
    CloseableHttpResponse response = client.execute(request);
    String responseAsString = null;
    int statusCode = response.getStatusLine().getStatusCode();
    if (methodName.equals(HttpPut.METHOD_NAME) || methodName.equals(HttpDelete.METHOD_NAME)) {
        JSONObject out = new JSONObject();
        for (Header header : response.getAllHeaders()) {
            try {
                out.put(header.getName(), header.getValue());
            } catch (Exception e) {
                System.out.println("Err in out.put");
            }
        }
        responseAsString = out.toString();
    } else if (statusCode != 204) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        responseAsString = out.toString("UTF-8");
        out.close();
    }
    JSONObject json = null;
    try {
        json = new JSONObject(responseAsString);
    } catch (Exception e) {
        json = new JSONObject();
    }
    VimeoResponse vimeoResponse = new VimeoResponse(json, statusCode);
    response.close();
    client.close();

    return vimeoResponse;

    // }   catch(IOException e)  {
    //     System.out.println("Error Building HTTP Client");
    // }
}

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  ww .  j a  va  2 s. c om
    // 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.jtalks.poulpe.service.JcommuneHttpNotifier.java

/**
 * Creates HTTP request based on the specified method.
 *
 * @param httpMethod either {@link HttpDelete#getMethod()} or {@link HttpPost#getMethod()}
 * @param url        address of JCommune
 * @return constructed HTTP request based on specified method
 * @throws IllegalArgumentException if the method was neither DELETE nor POST
 *///from ww w  .ja  v a2s .  co  m
private HttpRequestBase createWithHttpMethod(String httpMethod, String url) {
    if (HttpDelete.METHOD_NAME.equals(httpMethod)) {
        return new HttpDelete(url);
    } else if (HttpPost.METHOD_NAME.equals(httpMethod)) {
        return new HttpPost(url);
    } else {
        throw new IllegalArgumentException("Wrong HTTP method name was specified: [" + httpMethod + "]");
    }
}

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

public void testDelete() {
    String index = randomAlphaOfLengthBetween(3, 10);
    String type = randomAlphaOfLengthBetween(3, 10);
    String id = randomAlphaOfLengthBetween(3, 10);
    DeleteRequest deleteRequest = new DeleteRequest(index, type, id);

    Map<String, String> expectedParams = new HashMap<>();

    setRandomTimeout(deleteRequest::timeout, ReplicationRequest.DEFAULT_TIMEOUT, expectedParams);
    setRandomRefreshPolicy(deleteRequest::setRefreshPolicy, expectedParams);
    setRandomVersion(deleteRequest, expectedParams);
    setRandomVersionType(deleteRequest::versionType, expectedParams);

    if (frequently()) {
        if (randomBoolean()) {
            String routing = randomAlphaOfLengthBetween(3, 10);
            deleteRequest.routing(routing);
            expectedParams.put("routing", routing);
        }/*from   w ww. ja va  2 s .  c  om*/
    }

    Request request = RequestConverters.delete(deleteRequest);
    assertEquals("/" + index + "/" + type + "/" + id, request.getEndpoint());
    assertEquals(expectedParams, request.getParameters());
    assertEquals(HttpDelete.METHOD_NAME, request.getMethod());
    assertNull(request.getEntity());
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.tests.CustomApiTests.java

private TestCase createHttpContentApiTest(final DataFormat inputFormat, final DataFormat outputFormat,
        final Random rndGen) {
    String name = String.format("HttpContent Overload - Input: %s - Output: %s", inputFormat, outputFormat);

    TestCase test = new TestCase(name) {
        private static final String TEST_HEADER_PREFIX = "x-test-zumo-";
        MobileServiceClient mClient;/*  ww w .j ava  2 s. c  om*/
        List<Pair<String, String>> mQuery;
        List<Pair<String, String>> mHeaders;
        TestExecutionCallback mCallback;
        JsonObject mExpectedResult;
        int mExpectedStatusCode;
        String mHttpMethod;
        byte[] mContent;
        TestResult mResult;

        @Override
        protected void executeTest(MobileServiceClient client, TestExecutionCallback callback) {
            mResult = new TestResult();
            mResult.setTestCase(this);
            mResult.setStatus(TestStatus.Passed);
            mClient = client;
            mCallback = callback;
            mHeaders = new ArrayList<Pair<String, String>>();

            createHttpContentTestInput(inputFormat, outputFormat, rndGen);

            try {

                ServiceFilterResponse response = mClient
                        .invokeApi(APP_API_NAME, mContent, mHttpMethod, mHeaders, mQuery).get();

                Exception ex = validateResponseHeaders(response);
                if (ex != null) {
                    createResultFromException(mResult, ex);
                } else {
                    mResult.getTestCase().log("Header validated successfully");

                    String responseContent = response.getContent();

                    mResult.getTestCase().log("Response content: " + responseContent);

                    JsonElement jsonResponse = null;
                    if (outputFormat == DataFormat.Json) {
                        jsonResponse = new JsonParser().parse(responseContent);
                    } else if (outputFormat == DataFormat.Other) {
                        String decodedContent = responseContent.replace("__{__", "{").replace("__}__", "}")
                                .replace("__[__", "[").replace("__]__", "]");
                        jsonResponse = new JsonParser().parse(decodedContent);
                    }

                    switch (outputFormat) {
                    case Json:
                    case Other:
                        if (!Util.compareJson(mExpectedResult, jsonResponse)) {
                            createResultFromException(mResult,
                                    new ExpectedValueException(mExpectedResult, jsonResponse));
                        }
                        break;
                    default:
                        String expectedResultContent = jsonToXml(mExpectedResult);
                        // Normalize CRLF
                        expectedResultContent = expectedResultContent.replace("\r\n", "\n");
                        responseContent = responseContent.replace("\r\n", "\n");

                        if (!expectedResultContent.equals(responseContent)) {
                            createResultFromException(mResult,
                                    new ExpectedValueException(expectedResultContent, responseContent));
                        }
                        break;
                    }

                }
            } catch (Exception exception) {
                createResultFromException(exception);
                mCallback.onTestComplete(mResult.getTestCase(), mResult);
                return;
            }

            mCallback.onTestComplete(mResult.getTestCase(), mResult);
        }

        private Exception validateResponseHeaders(ServiceFilterResponse response) {
            if (mExpectedStatusCode != response.getStatus().getStatusCode()) {
                mResult.getTestCase().log("Invalid status code");
                String content = response.getContent();
                if (content != null) {
                    mResult.getTestCase().log("Response: " + content);
                }
                return new ExpectedValueException(mExpectedStatusCode, response.getStatus().getStatusCode());
            } else {

                for (Pair<String, String> header : mHeaders) {
                    if (header.first.startsWith(TEST_HEADER_PREFIX)) {
                        if (!Util.responseContainsHeader(response, header.first)) {
                            mResult.getTestCase().log("Header " + header.first + " not found");
                            return new ExpectedValueException("Header: " + header.first, "");
                        } else {
                            String headerValue = Util.getHeaderValue(response, header.first);
                            if (!header.second.equals(headerValue)) {
                                mResult.getTestCase().log("Invalid Header value for " + header.first);
                                return new ExpectedValueException(header.second, headerValue);
                            }
                        }
                    }
                }
            }

            return null;
        }

        private void createHttpContentTestInput(DataFormat inputFormat, DataFormat outputFormat,
                Random rndGen) {
            mHttpMethod = createHttpMethod(rndGen);
            log("Method = " + mHttpMethod);

            mExpectedResult = new JsonObject();
            mExpectedResult.addProperty("method", mHttpMethod);
            JsonObject user = new JsonObject();
            user.addProperty("level", "anonymous");
            mExpectedResult.add("user", user);

            JsonElement body = null;
            String textBody = null;
            if (!mHttpMethod.equals(HttpGet.METHOD_NAME) && !mHttpMethod.equals(HttpDelete.METHOD_NAME)) {
                body = createJson(rndGen, 0, true);
                if (outputFormat == DataFormat.Xml || inputFormat == DataFormat.Xml) {
                    // to prevent non-XML names from interfering with checks
                    body = sanitizeJsonXml(body);
                }

                try {
                    switch (inputFormat) {
                    case Json:
                        mContent = body.toString().getBytes("utf-8");
                        mHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, "application/json"));
                        break;

                    case Xml:
                        textBody = jsonToXml(body);
                        mContent = textBody.getBytes("utf-8");
                        mHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, "text/xml"));
                        break;
                    default:
                        textBody = body.toString().replace('{', '<').replace('}', '>').replace("[", "__[__")
                                .replace("]", "__]__");
                        mContent = textBody.getBytes("utf-8");
                        mHeaders.add(new Pair<String, String>(HTTP.CONTENT_TYPE, "text/plain"));
                        break;
                    }
                } catch (UnsupportedEncodingException e) {
                    // this will never happen
                }
            }

            if (body != null) {
                if (inputFormat == DataFormat.Json) {
                    mExpectedResult.add("body", body);
                } else {
                    mExpectedResult.addProperty("body", textBody);
                }
            }

            int choice = rndGen.nextInt(5);
            for (int j = 0; j < choice; j++) {
                String name = TEST_HEADER_PREFIX + j;
                String value = Util.createSimpleRandomString(rndGen, rndGen.nextInt(10) + 1, 'a', 'z');
                mHeaders.add(new Pair<String, String>(name, value));
            }

            mQuery = createQuery(rndGen);
            if (mQuery == null) {
                mQuery = new ArrayList<Pair<String, String>>();
            }

            if (mQuery.size() > 0) {
                JsonObject outputQuery = new JsonObject();
                for (Pair<String, String> element : mQuery) {
                    outputQuery.addProperty(element.first, element.second);
                }

                mExpectedResult.add("query", outputQuery);
            }

            mQuery.add(new Pair<String, String>("format",
                    outputFormat.toString().toLowerCase(Locale.getDefault())));
            mExpectedStatusCode = 200;

            if (rndGen.nextInt(4) == 0) {
                // non-200 responses
                int[] options = new int[] { 400, 404, 500, 201 };
                int status = options[rndGen.nextInt(options.length)];
                mExpectedStatusCode = status;
                mQuery.add(new Pair<String, String>("status", Integer.valueOf(status).toString()));
            }
        }

        private String jsonToXml(JsonElement json) {
            StringBuilder sb = new StringBuilder();
            sb.append("<root>");
            jsonToXml(json, sb);
            sb.append("</root>");
            return sb.toString();
        }

        private void jsonToXml(JsonElement json, StringBuilder sb) {
            if (json == null) {
                json = new JsonPrimitive("");
            }

            if (json.isJsonNull()) {
                sb.append("null");
            } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isBoolean()) {
                sb.append(json.toString().toLowerCase(Locale.getDefault()));
            } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isNumber()) {
                sb.append(json.toString());
            } else if (json.isJsonPrimitive() && json.getAsJsonPrimitive().isString()) {
                sb.append(json.getAsJsonPrimitive().getAsString());
            } else if (json.isJsonArray()) {
                sb.append("<array>");
                JsonArray array = json.getAsJsonArray();
                for (int i = 0; i < array.size(); i++) {
                    sb.append("<item>");
                    jsonToXml(array.get(i), sb);
                    sb.append("</item>");
                }
                sb.append("</array>");
            } else {
                Set<Entry<String, JsonElement>> entrySet = json.getAsJsonObject().entrySet();

                List<String> keys = new ArrayList<String>();
                for (Entry<String, JsonElement> entry : entrySet) {
                    keys.add(entry.getKey());
                }

                Collections.sort(keys);
                for (String key : keys) {
                    sb.append("<" + key + ">");
                    jsonToXml(json.getAsJsonObject().get(key), sb);
                    sb.append("</" + key + ">");
                }

            }
        }

        private JsonElement sanitizeJsonXml(JsonElement body) {
            if (body.isJsonArray()) {
                JsonArray array = new JsonArray();
                for (JsonElement element : body.getAsJsonArray()) {
                    array.add(sanitizeJsonXml(element));
                }

                return array;
            } else if (body.isJsonObject()) {
                JsonObject object = new JsonObject();
                Set<Entry<String, JsonElement>> entrySet = body.getAsJsonObject().entrySet();

                int i = 0;
                for (Entry<String, JsonElement> entry : entrySet) {
                    object.add("memeber" + i, sanitizeJsonXml(entry.getValue()));
                    i++;
                }

                return object;
            } else {
                return body;
            }
        }
    };

    return test;
}

From source file:com.mirth.connect.client.core.ServerConnection.java

private HttpRequestBase createRequestBase(String method) {
    HttpRequestBase requestBase = null;/* ww  w  . j  av  a  2s  .  c  o m*/

    if (StringUtils.equalsIgnoreCase(HttpGet.METHOD_NAME, method)) {
        requestBase = new HttpGet();
    } else if (StringUtils.equalsIgnoreCase(HttpPost.METHOD_NAME, method)) {
        requestBase = new HttpPost();
    } else if (StringUtils.equalsIgnoreCase(HttpPut.METHOD_NAME, method)) {
        requestBase = new HttpPut();
    } else if (StringUtils.equalsIgnoreCase(HttpDelete.METHOD_NAME, method)) {
        requestBase = new HttpDelete();
    } else if (StringUtils.equalsIgnoreCase(HttpOptions.METHOD_NAME, method)) {
        requestBase = new HttpOptions();
    } else if (StringUtils.equalsIgnoreCase(HttpPatch.METHOD_NAME, method)) {
        requestBase = new HttpPatch();
    }

    requestBase.setConfig(requestConfig);
    return requestBase;
}