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:com.sugarcrm.candybean.webservices.WS.java

/**
 * Send a DELETE, GET, POST, or PUT http request using a JSON body
 *
 * @param op      The type of http request
 * @param uri     The http endpoint//  ww w  .  j  a  va  2  s  .  c  o  m
 * @param headers Map of header key value pairs
 * @param body    Map of Key Value pairs
 * @return Key Value pairs of the response
 * @throws Exception If HTTP request failed
 */
public static Map<String, Object> request(OP op, String uri, Map<String, String> headers,
        Map<String, Object> body) throws Exception {
    return request(op, uri, headers, body, ContentType.APPLICATION_JSON);
}

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

public HttpEntity createJsonEntity(Object serializableObject) throws FreeboxException {
    StringWriter w = new StringWriter();
    try {/*from   w w  w .  j a  v  a  2 s .c  om*/
        jsonMapper.writeValue(w, serializableObject);
    } catch (Exception e) {
        throw new FreeboxException(e);
    }
    return new StringEntity(w.toString(), ContentType.APPLICATION_JSON);
}

From source file:org.elasticsearch.multi_node.RollupIT.java

public void testBigRollup() throws Exception {
    final int numDocs = 200;
    String dateFormat = "strict_date_optional_time";

    // create the test-index index
    try (XContentBuilder builder = jsonBuilder()) {
        builder.startObject();/*from   w  w  w.  j  av  a2s. c o m*/
        {
            builder.startObject("mappings").startObject("_doc").startObject("properties")
                    .startObject("timestamp").field("type", "date").field("format", dateFormat).endObject()
                    .startObject("value").field("type", "integer").endObject().endObject().endObject()
                    .endObject();
        }
        builder.endObject();
        final StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON);
        Request req = new Request("PUT", "rollup-docs");
        req.setEntity(entity);
        client().performRequest(req);
    }

    // index documents for the rollup job
    final StringBuilder bulk = new StringBuilder();
    for (int i = 0; i < numDocs; i++) {
        bulk.append("{\"index\":{\"_index\":\"rollup-docs\",\"_type\":\"_doc\"}}\n");
        ZonedDateTime zdt = ZonedDateTime.ofInstant(Instant.ofEpochSecond(1531221196 + (60 * i)),
                ZoneId.of("UTC"));
        String date = zdt.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
        bulk.append("{\"timestamp\":\"").append(date).append("\",\"value\":").append(i).append("}\n");
    }
    bulk.append("\r\n");

    final Request bulkRequest = new Request("POST", "/_bulk");
    bulkRequest.addParameter("refresh", "true");
    bulkRequest.setJsonEntity(bulk.toString());
    client().performRequest(bulkRequest);

    // create the rollup job
    final Request createRollupJobRequest = new Request("PUT", "/_xpack/rollup/job/rollup-job-test");
    int pageSize = randomIntBetween(2, 50);
    createRollupJobRequest.setJsonEntity("{" + "\"index_pattern\":\"rollup-*\","
            + "\"rollup_index\":\"results-rollup\"," + "\"cron\":\"*/1 * * * * ?\"," // fast cron so test runs quickly
            + "\"page_size\":" + pageSize + "," + "\"groups\":{" + "    \"date_histogram\":{"
            + "        \"field\":\"timestamp\"," + "        \"interval\":\"5m\"" + "      }" + "},"
            + "\"metrics\":[" + "    {\"field\":\"value\",\"metrics\":[\"min\",\"max\",\"sum\"]}" + "]" + "}");

    Map<String, Object> createRollupJobResponse = toMap(client().performRequest(createRollupJobRequest));
    assertThat(createRollupJobResponse.get("acknowledged"), equalTo(Boolean.TRUE));

    // start the rollup job
    final Request startRollupJobRequest = new Request("POST", "_xpack/rollup/job/rollup-job-test/_start");
    Map<String, Object> startRollupJobResponse = toMap(client().performRequest(startRollupJobRequest));
    assertThat(startRollupJobResponse.get("started"), equalTo(Boolean.TRUE));

    assertRollUpJob("rollup-job-test");

    // Wait for the job to finish, by watching how many rollup docs we've indexed
    assertBusy(() -> {
        final Request getRollupJobRequest = new Request("GET", "_xpack/rollup/job/rollup-job-test");
        Response getRollupJobResponse = client().performRequest(getRollupJobRequest);
        assertThat(getRollupJobResponse.getStatusLine().getStatusCode(), equalTo(RestStatus.OK.getStatus()));

        Map<String, Object> job = getJob(getRollupJobResponse, "rollup-job-test");
        if (job != null) {
            assertThat(ObjectPath.eval("status.job_state", job), equalTo("started"));
            assertThat(ObjectPath.eval("stats.rollups_indexed", job), equalTo(41));
        }
    }, 30L, TimeUnit.SECONDS);

    // Refresh the rollup index to make sure all newly indexed docs are searchable
    final Request refreshRollupIndex = new Request("POST", "results-rollup/_refresh");
    toMap(client().performRequest(refreshRollupIndex));

    String jsonRequestBody = "{\n" + "  \"size\": 0,\n" + "  \"query\": {\n" + "    \"match_all\": {}\n"
            + "  },\n" + "  \"aggs\": {\n" + "    \"date_histo\": {\n" + "      \"date_histogram\": {\n"
            + "        \"field\": \"timestamp\",\n" + "        \"interval\": \"1h\",\n"
            + "        \"format\": \"date_time\"\n" + "      },\n" + "      \"aggs\": {\n"
            + "        \"the_max\": {\n" + "          \"max\": {\n" + "            \"field\": \"value\"\n"
            + "          }\n" + "        }\n" + "      }\n" + "    }\n" + "  }\n" + "}";

    Request request = new Request("GET", "rollup-docs/_search");
    request.setJsonEntity(jsonRequestBody);
    Response liveResponse = client().performRequest(request);
    Map<String, Object> liveBody = toMap(liveResponse);

    request = new Request("GET", "results-rollup/_rollup_search");
    request.setJsonEntity(jsonRequestBody);
    Response rollupResponse = client().performRequest(request);
    Map<String, Object> rollupBody = toMap(rollupResponse);

    // Do the live agg results match the rollup agg results?
    assertThat(ObjectPath.eval("aggregations.date_histo.buckets", liveBody),
            equalTo(ObjectPath.eval("aggregations.date_histo.buckets", rollupBody)));

    request = new Request("GET", "rollup-docs/_rollup_search");
    request.setJsonEntity(jsonRequestBody);
    Response liveRollupResponse = client().performRequest(request);
    Map<String, Object> liveRollupBody = toMap(liveRollupResponse);

    // Does searching the live index via rollup_search work match the live search?
    assertThat(ObjectPath.eval("aggregations.date_histo.buckets", liveBody),
            equalTo(ObjectPath.eval("aggregations.date_histo.buckets", liveRollupBody)));

}

From source file:org.elasticsearch.xpack.ml.integration.DatafeedJobsRestIT.java

private void setupUser(String user, List<String> roles) throws IOException {
    String password = new String(SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING.getChars());

    String json = "{" + "  \"password\" : \"" + password + "\"," + "  \"roles\" : [ "
            + roles.stream().map(unquoted -> "\"" + unquoted + "\"").collect(Collectors.joining(", ")) + " ]"
            + "}";

    client().performRequest("put", "_xpack/security/user/" + user, Collections.emptyMap(),
            new StringEntity(json, ContentType.APPLICATION_JSON));
}

From source file:org.megam.deccanplato.provider.salesforce.crm.handler.OpportunitiesImpl.java

/**
 * this method creates an opportunity in salesforce.com and returns that opportunity id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap //  w w w . java2  s  .c  o m
 */
private Map<String, String> create() {
    final String SALESFORCE_CREATE_OPPORTUNITY_URL = args.get(INSTANCE_URL) + SALESFORCE_OPPORTUNITY_URL;
    Map<String, String> outMap = new HashMap<>();
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));
    Map<String, Object> userAttrMap = new HashMap<String, Object>();
    userAttrMap.put(S_NAME, args.get(NAME));
    userAttrMap.put(S_STAGENAME, args.get(STAGE_NAME));
    userAttrMap.put(S_CLOSEDATE, DateTime.parse(args.get(CLOSE_DATE)));

    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(DateTime.class, new DateTimeTypeConverter());
    Gson obj = gson.setPrettyPrinting().create();
    TransportTools tst = new TransportTools(SALESFORCE_CREATE_OPPORTUNITY_URL, null, header);
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    try {
        String responseBody = TransportMachinery.post(tst).entityToString();
        outMap.put(OUTPUT, responseBody);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outMap;
}

From source file:com.vmware.photon.controller.client.RestClientTest.java

@Test
public void testPerformPut() {
    String payload = "{name: DUMMY}";
    ArgumentCaptor<HttpUriRequest> argumentCaptor = setup(RestClient.Method.PUT,
            new StringEntity(payload, ContentType.APPLICATION_JSON));

    HttpUriRequest request = argumentCaptor.getValue();
    assertNotNull(request);/*from   w w  w  .  j  ava2s  .c om*/
    assertTrue(request.getMethod().equalsIgnoreCase(RestClient.Method.PUT.toString()));
    assertEquals(request.getURI().toString(), uri);

    HttpEntityEnclosingRequest httpEntityEnclosingRequest = (HttpEntityEnclosingRequest) request;
    String actualPayload = null;
    try {
        actualPayload = IOUtils.toString(httpEntityEnclosingRequest.getEntity().getContent());
    } catch (IOException e) {
        fail(e.getMessage());
    }

    assertEquals(actualPayload, payload);
}

From source file:org.osiam.client.OsiamUserMeTest.java

private void givenAccessTokenForMeIsValid() {
    stubFor(givenMeIsLookedUp(accessToken).willReturn(
            aResponse().withStatus(SC_OK).withHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType())
                    .withBodyFile("user_" + USER_ID + ".json")));
}

From source file:org.thingsboard.server.dao.audit.sink.ElasticsearchAuditLogSink.java

@Override
public void logAction(AuditLog auditLogEntry) {
    String jsonContent = createElasticJsonRecord(auditLogEntry);

    HttpEntity entity = new NStringEntity(jsonContent, ContentType.APPLICATION_JSON);

    restClient.performRequestAsync(HttpMethod.POST.name(),
            String.format("/%s/%s", getIndexName(auditLogEntry.getTenantId()), INDEX_TYPE),
            Collections.emptyMap(), entity, responseListener);
}

From source file:io.crate.rest.AdminUIIntegrationTest.java

private static void assertIsJsonInfoResponse(CloseableHttpResponse response) throws IOException {
    //status should be 200 OK
    assertThat(response.getStatusLine().getStatusCode(), is(200));

    //response body should not be null
    String bodyAsString = EntityUtils.toString(response.getEntity());
    assertThat(bodyAsString, notNullValue());

    //check content-type of response is json
    String contentMimeType = ContentType.getOrDefault(response.getEntity()).getMimeType();
    assertThat(contentMimeType, equalTo(ContentType.APPLICATION_JSON.getMimeType()));
}