Example usage for org.apache.http.entity ContentType APPLICATION_JSON

List of usage examples for org.apache.http.entity ContentType APPLICATION_JSON

Introduction

In this page you can find the example usage for org.apache.http.entity ContentType APPLICATION_JSON.

Prototype

ContentType APPLICATION_JSON

To view the source code for org.apache.http.entity ContentType APPLICATION_JSON.

Click Source Link

Usage

From source file:org.elasticsearch.upgrades.TokenBackwardsCompatibilityIT.java

public void testMixedCluster() throws Exception {
    assumeTrue("this test should only run against the mixed cluster", clusterType == CLUSTER_TYPE.MIXED);
    assumeTrue("the master must be on the latest version before we can write", isMasterOnLatestVersion());
    Response getResponse = client().performRequest("GET",
            "token_backwards_compatibility_it/doc/old_cluster_token2");
    assertOK(getResponse);/*ww w  .ja v a  2s . c  om*/
    Map<String, Object> source = (Map<String, Object>) entityAsMap(getResponse).get("_source");
    final String token = (String) source.get("token");
    assertTokenWorks(token);

    final StringEntity body = new StringEntity("{\"token\": \"" + token + "\"}", ContentType.APPLICATION_JSON);
    Response invalidationResponse = client().performRequest("DELETE", "_xpack/security/oauth2/token",
            Collections.emptyMap(), body);
    assertOK(invalidationResponse);
    assertTokenDoesNotWork(token);

    // create token and refresh on version that supports it
    final StringEntity tokenPostBody = new StringEntity("{\n" + "    \"username\": \"test_user\",\n"
            + "    \"password\": \"x-pack-test-password\",\n" + "    \"grant_type\": \"password\"\n" + "}",
            ContentType.APPLICATION_JSON);
    try (RestClient client = getRestClientForCurrentVersionNodesOnly()) {
        Response response = client.performRequest("POST", "_xpack/security/oauth2/token",
                Collections.emptyMap(), tokenPostBody);
        assertOK(response);
        Map<String, Object> responseMap = entityAsMap(response);
        String accessToken = (String) responseMap.get("access_token");
        String refreshToken = (String) responseMap.get("refresh_token");
        assertNotNull(accessToken);
        assertNotNull(refreshToken);
        assertTokenWorks(accessToken);

        final StringEntity tokenRefresh = new StringEntity("{\n" + "    \"refresh_token\": \"" + refreshToken
                + "\",\n" + "    \"grant_type\": \"refresh_token\"\n" + "}", ContentType.APPLICATION_JSON);
        response = client.performRequest("POST", "_xpack/security/oauth2/token", Collections.emptyMap(),
                tokenRefresh);
        assertOK(response);
        responseMap = entityAsMap(response);
        String updatedAccessToken = (String) responseMap.get("access_token");
        String updatedRefreshToken = (String) responseMap.get("refresh_token");
        assertNotNull(updatedAccessToken);
        assertNotNull(updatedRefreshToken);
        assertTokenWorks(updatedAccessToken);
        assertTokenWorks(accessToken);
        assertNotEquals(accessToken, updatedAccessToken);
        assertNotEquals(refreshToken, updatedRefreshToken);
    }
}

From source file:org.kitodo.data.index.elasticsearch.type.TaskType.java

@SuppressWarnings("unchecked")
@Override//ww  w  .j  a v  a2s.c  o m
public HttpEntity createDocument(Task task) {

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    LinkedHashMap<String, String> orderedTaskMap = new LinkedHashMap<>();
    orderedTaskMap.put("title", task.getTitle());
    String priority = task.getPriority() != null ? task.getPriority().toString() : "null";
    orderedTaskMap.put("priority", priority);
    String ordering = task.getOrdering() != null ? task.getOrdering().toString() : "null";
    orderedTaskMap.put("ordering", ordering);
    String processingStatus = task.getProcessingStatusEnum() != null ? task.getProcessingStatusEnum().toString()
            : "null";
    orderedTaskMap.put("processingStatus", processingStatus);
    String processingTime = task.getProcessingTime() != null ? dateFormat.format(task.getProcessingTime())
            : null;
    orderedTaskMap.put("processingTime", processingTime);
    String processingBegin = task.getProcessingBegin() != null ? dateFormat.format(task.getProcessingBegin())
            : null;
    orderedTaskMap.put("processingBegin", processingBegin);
    String processingEnd = task.getProcessingEnd() != null ? dateFormat.format(task.getProcessingEnd()) : null;
    orderedTaskMap.put("processingEnd", processingEnd);
    orderedTaskMap.put("homeDirectory", String.valueOf(task.getHomeDirectory()));
    orderedTaskMap.put("typeMetadata", String.valueOf(task.isTypeMetadata()));
    orderedTaskMap.put("typeAutomatic", String.valueOf(task.isTypeAutomatic()));
    orderedTaskMap.put("typeImportFileUpload", String.valueOf(task.isTypeImportFileUpload()));
    orderedTaskMap.put("typeExportRussian", String.valueOf(task.isTypeExportRussian()));
    orderedTaskMap.put("typeImagesRead", String.valueOf(task.isTypeImagesRead()));
    orderedTaskMap.put("typeImagesWrite", String.valueOf(task.isTypeImagesWrite()));
    orderedTaskMap.put("batchStep", String.valueOf(task.isBatchStep()));
    String processingUser = task.getProcessingUser() != null ? task.getProcessingUser().getId().toString()
            : "null";
    orderedTaskMap.put("processingUser", processingUser);
    String process = task.getProcess() != null ? task.getProcess().getId().toString() : "null";
    orderedTaskMap.put("process", process);

    JSONObject taskObject = new JSONObject(orderedTaskMap);

    JSONArray users = new JSONArray();
    List<User> taskUsers = task.getUsers();
    for (User user : taskUsers) {
        JSONObject propertyObject = new JSONObject();
        propertyObject.put("id", user.getId());
        users.add(propertyObject);
    }
    taskObject.put("users", users);

    JSONArray userGroups = new JSONArray();
    List<UserGroup> taskUserGroups = task.getUserGroups();
    for (UserGroup userGroup : taskUserGroups) {
        JSONObject userGroupObject = new JSONObject();
        userGroupObject.put("id", userGroup.getId().toString());
        userGroups.add(userGroupObject);
    }
    taskObject.put("userGroups", userGroups);

    return new NStringEntity(taskObject.toJSONString(), ContentType.APPLICATION_JSON);
}

From source file:org.matmaul.freeboxos.internal.RestManager.java

public HttpEntity createJsonEntity(JSONObject jsonObj) {
    return new StringEntity(jsonObj.toString(), ContentType.APPLICATION_JSON);
}

From source file:io.opentracing.contrib.elasticsearch5.TracingTest.java

@Test
public void restClient() throws Exception {
    RestClient restClient = RestClient.builder(new HttpHost("localhost", HTTP_PORT, "http"))
            .setHttpClientConfigCallback(new TracingHttpClientConfigCallback(mockTracer)).build();

    HttpEntity entity = new NStringEntity(
            "{\n" + "    \"user\" : \"kimchy\",\n" + "    \"post_date\" : \"2009-11-15T14:12:12\",\n"
                    + "    \"message\" : \"trying out Elasticsearch\"\n" + "}",
            ContentType.APPLICATION_JSON);

    Response indexResponse = restClient.performRequest("PUT", "/twitter/tweet/1",
            Collections.<String, String>emptyMap(), entity);

    assertNotNull(indexResponse);//ww w. jav  a2  s .c  o m

    final CountDownLatch latch = new CountDownLatch(1);
    restClient.performRequestAsync("PUT", "/twitter/tweet/2", Collections.<String, String>emptyMap(), entity,
            new ResponseListener() {
                @Override
                public void onSuccess(Response response) {
                    latch.countDown();
                }

                @Override
                public void onFailure(Exception exception) {
                    latch.countDown();
                }
            });

    latch.await(30, TimeUnit.SECONDS);
    restClient.close();

    List<MockSpan> finishedSpans = mockTracer.finishedSpans();
    assertEquals(2, finishedSpans.size());
    checkSpans(finishedSpans, "PUT");
    assertNull(mockTracer.activeSpan());
}

From source file:org.imsglobal.caliper.request.ApacheHttpRequestor.java

/**
 * Post envelope./*from www  .  java2s .  com*/
 * @param data
 * @return status
 */
@Override
public boolean send(Sensor sensor, List<T> data) throws IOException {
    boolean status = Boolean.FALSE;

    if (log.isDebugEnabled()) {
        log.debug("Entering send()...");
    }

    // Check if HttpClient is initialized.
    checkInitialized();

    // Create mapper
    ObjectMapper mapper = JsonObjectMapper.create(options.getJsonInclude());

    // Create envelope, serialize it as a JSON string.
    Envelope<T> envelope = createEnvelope(sensor, DateTime.now(), data);

    // Serialize envelope with mapper
    String json = serializeEnvelope(envelope, mapper);

    // Create an HTTP StringEntity payload with the envelope JSON.
    StringEntity payload = generatePayload(json, ContentType.APPLICATION_JSON);

    // Do the post
    HttpPost httpPost = new HttpPost(this.getOptions().getHost());
    httpPost.setHeader("Authorization", this.getOptions().getApiKey());
    httpPost.setHeader(payload.getContentType());

    httpPost.setEntity(payload);
    response = httpClient.execute(httpPost);

    if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
        int statusCode = response.getStatusLine().getStatusCode();
        response.close();
        throw new RuntimeException("Failed : HTTP error code : " + statusCode);
    } else {
        if (log.isDebugEnabled()) {
            log.debug(response.getStatusLine().toString());
            log.debug(EntityUtils.toString(response.getEntity()));
        }

        response.close();
        status = Boolean.TRUE;

        if (log.isDebugEnabled()) {
            log.debug("Exiting send()...");
        }
    }

    return status;
}

From source file:org.elasticsearch.integration.BulkUpdateTests.java

public void testThatBulkUpdateDoesNotLoseFieldsHttp() throws IOException {
    final String path = "/index1/type/1";
    final Header basicAuthHeader = new BasicHeader("Authorization",
            UsernamePasswordToken.basicAuthHeaderValue(SecuritySettingsSource.TEST_USER_NAME,
                    new SecureString(SecuritySettingsSourceField.TEST_PASSWORD.toCharArray())));

    StringEntity body = new StringEntity("{\"test\":\"test\"}", ContentType.APPLICATION_JSON);
    Response response = getRestClient().performRequest("PUT", path, Collections.emptyMap(), body,
            basicAuthHeader);/*from w  w  w  . j a  v a 2s. c om*/
    assertThat(response.getStatusLine().getStatusCode(), equalTo(201));

    response = getRestClient().performRequest("GET", path, basicAuthHeader);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    assertThat(EntityUtils.toString(response.getEntity()), containsString("\"test\":\"test\""));

    if (randomBoolean()) {
        flushAndRefresh();
    }

    //update with new field
    body = new StringEntity("{\"doc\": {\"not test\": \"not test\"}}", ContentType.APPLICATION_JSON);
    response = getRestClient().performRequest("POST", path + "/_update", Collections.emptyMap(), body,
            basicAuthHeader);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

    response = getRestClient().performRequest("GET", path, basicAuthHeader);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    String responseBody = EntityUtils.toString(response.getEntity());
    assertThat(responseBody, containsString("\"test\":\"test\""));
    assertThat(responseBody, containsString("\"not test\":\"not test\""));

    // this part is important. Without this, the document may be read from the translog which would bypass the bug where
    // FLS kicks in because the request can't be found and only returns meta fields
    flushAndRefresh();

    body = new StringEntity("{\"update\": {\"_index\": \"index1\", \"_type\": \"type\", \"_id\": \"1\"}}\n"
            + "{\"doc\": {\"bulk updated\":\"bulk updated\"}}\n", ContentType.APPLICATION_JSON);
    response = getRestClient().performRequest("POST", "/_bulk", Collections.emptyMap(), body, basicAuthHeader);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

    response = getRestClient().performRequest("GET", path, basicAuthHeader);
    responseBody = EntityUtils.toString(response.getEntity());
    assertThat(responseBody, containsString("\"test\":\"test\""));
    assertThat(responseBody, containsString("\"not test\":\"not test\""));
    assertThat(responseBody, containsString("\"bulk updated\":\"bulk updated\""));
}

From source file:tech.sirwellington.alchemy.http.HttpVerbImplTest.java

@Before
public void setUp() throws IOException {
    instance = new HttpVerbImpl(requestMapper);
    verifyZeroInteractions(requestMapper);

    when(requestMapper.convertToApacheRequest(request)).thenReturn(apacheRequest);

    responseBody = one(jsonElements());//w  w w .j  a va2  s  .c  o m

    entity = new StringEntity(responseBody.toString(), ContentType.APPLICATION_JSON);

    setupResponse();
}

From source file:eu.over9000.cathode.resources.implementations.ChannelsImpl.java

@Override
public Result<Channel> putChannel(final String channelName, final ChannelOptions options) {
    return dispatcher.performPut(Channel.class, Channels.PATH + "/" + channelName,
            new StringEntity(options.encode(), ContentType.APPLICATION_JSON));
}

From source file:au.com.borner.salesforce.client.rest.ConnectionManager.java

public <Response extends AbstractJSONObject, Request extends AbstractJSONObject> Response executePost(
        String path, Request bodyObject, Class<Response> responseClass) {
    HttpPost httpPost = new HttpPost(buildUri(path, null));
    String body = bodyObject.toString();
    httpPost.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
    return execute(httpPost, responseClass);
}

From source file:org.biokoframework.http.exception.impl.ExceptionResponseBuilderTest.java

@Test
public void testNestedBiokoException() throws IOException {
    ExceptionResponseBuilderImpl builder = new ExceptionResponseBuilderImpl(fCodesMap);

    MockResponse mockResponse = new MockResponse();
    ErrorEntity error = new ErrorEntity();
    error.setAll(new Fields(ErrorEntity.ERROR_CODE, 12345, ErrorEntity.ERROR_MESSAGE, "Failed at life"));
    MockException mockException = new MockException(new CommandException(error));

    mockResponse = (MockResponse) builder.build(mockResponse, mockException, null, null);

    assertThat(mockResponse.getContentType(), is(equalTo(ContentType.APPLICATION_JSON.toString())));
    assertThat(mockResponse.getStatus(), is(equalTo(626)));
    assertThat(mockResponse, hasToString(matchesPattern(
            "^.*An unexpected exception as been captured [\\w\\.\\$]+MockException .*Caused by [\\w\\.\\$]+CommandException.*$")));

}