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.multi_node.GlobalCheckpointSyncActionIT.java

public void testGlobalCheckpointSyncActionRunsAsPrivilegedUser() throws Exception {
    // create the test-index index
    try (XContentBuilder builder = jsonBuilder()) {
        builder.startObject();/*w w  w  . jav  a  2  s .  c  o m*/
        {
            builder.startObject("settings");
            {
                builder.field("index.number_of_shards", 1);
                builder.field("index.number_of_replicas", 1);
            }
            builder.endObject();
        }
        builder.endObject();
        final StringEntity entity = new StringEntity(Strings.toString(builder), ContentType.APPLICATION_JSON);
        client().performRequest("PUT", "test-index", Collections.emptyMap(), entity);
    }

    // wait for the replica to recover
    client().performRequest("GET", "/_cluster/health", Collections.singletonMap("wait_for_status", "green"));

    // index some documents
    final int numberOfDocuments = randomIntBetween(0, 128);
    for (int i = 0; i < numberOfDocuments; i++) {
        try (XContentBuilder builder = jsonBuilder()) {
            builder.startObject();
            {
                builder.field("foo", i);
            }
            builder.endObject();
            final StringEntity entity = new StringEntity(Strings.toString(builder),
                    ContentType.APPLICATION_JSON);
            client().performRequest("PUT", "/test-index/test-type/" + i, Collections.emptyMap(), entity);
        }
    }

    // we have to wait for the post-operation global checkpoint sync to propagate to the replica
    assertBusy(() -> {
        final Map<String, String> params = new HashMap<>(2);
        params.put("level", "shards");
        params.put("filter_path", "**.seq_no");
        final Response response = client().performRequest("GET", "/test-index/_stats", params);
        final ObjectPath path = ObjectPath.createFromResponse(response);
        // int looks funny here since global checkpoints are longs but the response parser does not know enough to treat them as long
        final int shard0GlobalCheckpoint = path
                .evaluate("indices.test-index.shards.0.0.seq_no.global_checkpoint");
        assertThat(shard0GlobalCheckpoint, equalTo(numberOfDocuments - 1));
        final int shard1GlobalCheckpoint = path
                .evaluate("indices.test-index.shards.0.1.seq_no.global_checkpoint");
        assertThat(shard1GlobalCheckpoint, equalTo(numberOfDocuments - 1));
    });
}

From source file:org.kiji.bento.box.TestUpgradeServerClient.java

@Test
public void testCheckin() throws IOException, URISyntaxException {
    LOG.info("Creating mocks.");
    // We'll create an UpgradeServerClient using a mock http client. The client will
    // execute one request, which will return an http response, which in turn will return
    // an entity that will provide the content for the response.
    InputStream contentStream = IOUtils.toInputStream(RESPONSE_JSON);
    HttpEntity mockResponseEntity = EasyMock.createMock(HttpEntity.class);
    EasyMock.expect(mockResponseEntity.getContent()).andReturn(contentStream);
    EasyMock.expect(mockResponseEntity.getContentLength()).andReturn(-1L).times(2);
    EasyMock.expect(mockResponseEntity.getContentType())
            .andReturn(new BasicHeader("ContentType", ContentType.APPLICATION_JSON.toString()));

    HttpResponse mockResponse = EasyMock.createMock(HttpResponse.class);
    EasyMock.expect(mockResponse.getEntity()).andReturn(mockResponseEntity);

    HttpClient mockClient = EasyMock.createMock(HttpClient.class);
    EasyMock.expect(mockClient.execute(EasyMock.isA(HttpPost.class))).andReturn(mockResponse);

    LOG.info("Replaying mocks.");
    EasyMock.replay(mockResponseEntity);
    EasyMock.replay(mockResponse);//from  www.  ja va2s . c  om
    EasyMock.replay(mockClient);

    // Create the upgrade server client.
    LOG.info("Creating upgrade server client and making request.");
    UpgradeServerClient upgradeClient = UpgradeServerClient.create(mockClient,
            new URI("http://www.foocorp.com"));
    UpgradeCheckin checkinMessage = new UpgradeCheckin.Builder().withId("12345").withLastUsedMillis(1L).build();
    UpgradeResponse response = upgradeClient.checkin(checkinMessage);

    LOG.info("Verifying mocks.");
    EasyMock.verify(mockResponseEntity, mockResponse, mockClient);

    // Verify the response content.
    LOG.info("Verifying response content.");
    assertEquals("Bad response format.", "bento-checkversion-1.0.0", response.getResponseFormat());
    assertEquals("Bad latest version", "2.0.0", response.getLatestVersion());
    assertEquals("Bad latest version URL.", "http://www.foocorp.com",
            response.getLatestVersionURL().toString());
    assertEquals("Bad compatible version.", "2.0.0", response.getCompatibleVersion());
    assertEquals("Bad compatible version URL.", "http://www.foocorp.com",
            response.getCompatibleVersionURL().toString());
    assertEquals("Bad response msg.", "better upgrade!", response.getMessage());
}

From source file:services.SecurityService.java

public void otpv2(String otp) throws IOException, JSONException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    JSONObject obj = new JSONObject();
    JSONObject msgObject = new JSONObject();
    msgObject.put("body", otp);
    msgObject.put("title", "notification");

    obj.put("to",
            "etN09hk7SII:APA91bGSE-G6jEKywU6D368rNRrd77zgL2UmKglsDhs-mdOsSJB4zrSS450D6TrrnwGiANx8wrn1mRCxYoJE_Qr743PVLCeN-mzL36UCQFYXMyqBJMQZr9nFKrvW7HmAQ5_507CUK7ys");
    obj.put("notification", msgObject);

    StringEntity requestEntity = new StringEntity(obj.toString(), ContentType.APPLICATION_JSON);

    HttpPost postMethod = new HttpPost(ANDROID_NOTIFICATION_URL);
    postMethod.setHeader("Content-type", "application/json");
    postMethod.setHeader("Authorization", "key=" + ANDROID_NOTIFICATION_KEY);
    postMethod.setEntity(requestEntity);
    HttpResponse rawResponse = client.execute(postMethod);
}

From source file:org.robertburrelldonkin.template4couchdb.rest.HttpClientRestClient.java

@Override
public <R, D> R post(String url, IDocumentMarshaller<D> documentMarshaller, D document,
        IDocumentUnmarshaller<R> responseUnmarshaller) {
    final ContentProducer producer = codecFactory.producerFor(documentMarshaller, document);
    final EntityTemplate entity = new EntityTemplate(producer);
    entity.setContentType(ContentType.APPLICATION_JSON.toString());
    final ResponseHandler<R> handler = codecFactory.handlerFor(responseUnmarshaller);
    final HttpPost post = new HttpPost(url);
    post.setEntity(entity);//from   w w  w . j  a va2 s  . co m
    final R response;
    try {
        response = httpClient.execute(post, handler);
    } catch (ClientProtocolException e) {
        throw new HttpClientRestClientException(e);
    } catch (IOException e) {
        throw new HttpClientRestClientException(e);
    }
    return response;
}

From source file:net.gbmb.collector.CollectionStepdefs.java

@Then("^I add in it a simple record with (.+)$")
public void i_add_in_it_a_simple_record_with(String json) throws Throwable {
    response = given().log().all().when().contentType(ContentType.APPLICATION_JSON.getMimeType()).body(json)
            .post(String.format("/records/%s/add", currentCid)).then();
}

From source file:com.huawei.ais.demo.TokenDemo.java

/**
 * ?Token? ??HTTPHeader???Token// ww  w.ja  v a2s .  c o  m
 * ???: X-Subject-Token
 * 
 * @param username   ??
 * @param password   ?
 * @param regionName ????
 * @return ?Token
 * @throws URISyntaxException
 * @throws UnsupportedOperationException
 * @throws IOException
 */
private static String getToken(String username, String password, String regionName)
        throws URISyntaxException, UnsupportedOperationException, IOException {

    // 1.?Token??
    String requestBody = requestBody(username, password, username, regionName);
    String url = "https://iam.cn-north-1.myhuaweicloud.com/v3/auth/tokens";
    Header[] headers = new Header[] {
            new BasicHeader("Content-Type", ContentType.APPLICATION_JSON.toString()) };
    StringEntity stringEntity = new StringEntity(requestBody, "utf-8");

    // 2.IAM??, POST??Token value
    HttpResponse response = HttpClientUtils.post(url, headers, stringEntity);
    Header[] xst = response.getHeaders("X-Subject-Token");
    return xst[0].getValue();

}

From source file:org.vas.test.rest.RestImpl.java

public RestImpl(Map<String, String> defaultHeaders) {
    super();// w w w  .  ja v  a 2s. c  o  m
    if (defaultHeaders == null) {
        this.defaultHeaders = Maps.newHashMap();
    } else {
        this.defaultHeaders = defaultHeaders;
    }

    if (!this.defaultHeaders.containsKey(HttpHeaders.ALLOW)) {
        this.defaultHeaders.put(HttpHeaders.ALLOW, ContentType.APPLICATION_JSON.getMimeType());
    }
}

From source file:org.kiji.checkin.TestCheckinClient.java

@Test
public void testCheckin() throws IOException, URISyntaxException {
    LOG.info("Creating mocks.");
    // We'll create an UpgradeServerClient using a mock http client. The client will
    // execute one request, which will return an http response, which in turn will return
    // an entity that will provide the content for the response.
    InputStream contentStream = IOUtils.toInputStream(RESPONSE_JSON);
    HttpEntity mockResponseEntity = EasyMock.createMock(HttpEntity.class);
    EasyMock.expect(mockResponseEntity.getContent()).andReturn(contentStream);
    EasyMock.expect(mockResponseEntity.getContentLength()).andReturn(-1L).times(2);
    EasyMock.expect(mockResponseEntity.getContentType())
            .andReturn(new BasicHeader("ContentType", ContentType.APPLICATION_JSON.toString()));

    HttpResponse mockResponse = EasyMock.createMock(HttpResponse.class);
    EasyMock.expect(mockResponse.getEntity()).andReturn(mockResponseEntity);

    HttpClient mockClient = EasyMock.createMock(HttpClient.class);
    EasyMock.expect(mockClient.execute(EasyMock.isA(HttpPost.class))).andReturn(mockResponse);

    LOG.info("Replaying mocks.");
    EasyMock.replay(mockResponseEntity);
    EasyMock.replay(mockResponse);// w w w.  j  a va  2  s  .c o  m
    EasyMock.replay(mockClient);

    // Create the upgrade server client.
    LOG.info("Creating upgrade server client and making request.");
    CheckinClient upgradeClient = CheckinClient.create(mockClient, new URI("http://www.foocorp.com"));
    UpgradeCheckin checkinMessage = new UpgradeCheckin.Builder(this.getClass()).withId("12345")
            .withLastUsedMillis(1L).build();
    UpgradeResponse response = upgradeClient.checkin(checkinMessage);

    LOG.info("Verifying mocks.");
    EasyMock.verify(mockResponseEntity, mockResponse, mockClient);

    // Verify the response content.
    LOG.info("Verifying response content.");
    assertEquals("Bad response format.", "bento-checkversion-1.0.0", response.getResponseFormat());
    assertEquals("Bad latest version", "2.0.0", response.getLatestVersion());
    assertEquals("Bad latest version URL.", "http://www.foocorp.com",
            response.getLatestVersionURL().toString());
    assertEquals("Bad compatible version.", "2.0.0", response.getCompatibleVersion());
    assertEquals("Bad compatible version URL.", "http://www.foocorp.com",
            response.getCompatibleVersionURL().toString());
    assertEquals("Bad response msg.", "better upgrade!", response.getMessage());
}

From source file:org.kitodo.data.elasticsearch.search.SearchRestClient.java

/**
 * Count amount of documents responding to given query.
 *
 * @param query/* www.  j  a v  a 2 s  .co  m*/
 *            to find a document
 * @return http entity as String
 */
String countDocuments(QueryBuilder query) throws CustomResponseException, DataException {
    String wrappedQuery = "{\n \"query\": " + query.toString() + "\n}";
    HttpEntity entity = new NStringEntity(wrappedQuery, ContentType.APPLICATION_JSON);
    return performRequest(entity, HttpMethod.GET, "_count");
}

From source file:org.elasticsearch.smoketest.MonitoringWithWatcherRestIT.java

public void testThatLocalExporterAddsWatches() throws Exception {
    String watchId = createMonitoringWatch();

    String body = BytesReference.bytes(jsonBuilder().startObject().startObject("transient")
            .field("xpack.monitoring.exporters.my_local_exporter.type", "local")
            .field("xpack.monitoring.exporters.my_local_exporter.cluster_alerts.management.enabled", true)
            .endObject().endObject()).utf8ToString();

    adminClient().performRequest("PUT", "_cluster/settings", Collections.emptyMap(),
            new StringEntity(body, ContentType.APPLICATION_JSON));

    assertTotalWatchCount(ClusterAlertsUtil.WATCH_IDS.length);

    assertMonitoringWatchHasBeenOverWritten(watchId);
}