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:io.github.jonestimd.neo4j.client.http.ApacheHttpDriverTest.java

@Test
public void post() throws Exception {
    BasicHeader header = new BasicHeader("", "header-value");
    StringEntity responseEntity = new StringEntity("response entity");
    when(client.execute(any(HttpUriRequest.class), any(HttpClientContext.class))).thenReturn(httpResponse);
    when(httpResponse.getFirstHeader(anyString())).thenReturn(null, header);
    when(httpResponse.getEntity()).thenReturn(responseEntity);

    HttpResponse response = driver.post(uri, "json entity");

    verify(client).execute(postCaptor.capture(), same(context));
    HttpPost post = postCaptor.getValue();
    assertThat(post.getURI().toString()).isEqualTo(uri);
    assertThat(post.getEntity().getContentType().getValue()).isEqualTo(ContentType.APPLICATION_JSON.toString());
    assertThat(getContent(post.getEntity().getContent())).isEqualTo("json entity");
    assertThat(response.getHeader("header1")).isNull();
    assertThat(response.getHeader("header2")).isEqualTo(header.getValue());
    verify(httpResponse).getFirstHeader("header1");
    verify(httpResponse).getFirstHeader("header2");
    assertThat(getContent(response.getEntityContent())).isEqualTo("response entity");
    response.close();/*from   w  w  w. ja  va2 s . co  m*/
    verify(httpResponse).close();
}

From source file:com.nextdoor.bender.ipc.http.HttpTransportTest.java

@Test(expected = TransportException.class)
public void testNotOkResponse() throws TransportException, IOException {
    byte[] respPayload = "{\"foo\": \"bar\"}".getBytes(StandardCharsets.UTF_8);

    HttpClient client = getMockClientWithResponse(respPayload, ContentType.APPLICATION_JSON,
            HttpStatus.SC_INTERNAL_SERVER_ERROR, false);
    HttpTransport transport = new HttpTransport(client, "", false, 1, 1);

    transport.sendBatch("foo".getBytes());
}

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

private void givenIDisEmpty() {
    stubFor(givenIDisLookedUp("", accessToken).willReturn(
            aResponse().withStatus(SC_OK).withHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType())
                    .withBodyFile("query_all_users.json")));
}

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

/**
 * This method updates an account in salesforce.com and returns a success message with updated account id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap //w  ww  .j  a  v a2  s  .com
 */
private Map<String, String> update() {
    Map<String, String> outMap = new HashMap<String, String>();
    final String SALESFORCE_UPDATE_ACCOUNT_URL = args.get(INSTANCE_URL) + SALESFORCE_ACCOUNT_URL + args.get(ID);
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));
    Map<String, Object> accountAttrMap = new HashMap<String, Object>();
    accountAttrMap.put(S_NAME, args.get(NAME));

    TransportTools tst = new TransportTools(SALESFORCE_UPDATE_ACCOUNT_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(accountAttrMap));

    try {
        TransportMachinery.patch(tst).entityToString();
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outMap;
}

From source file:org.apache.beam.sdk.io.elasticsearch.ElasticSearchIOTestUtils.java

/** Inserts the given number of test documents into Elasticsearch. */
static void insertTestDocuments(ConnectionConfiguration connectionConfiguration, long numDocs,
        RestClient restClient) throws IOException {
    List<String> data = ElasticSearchIOTestUtils.createDocuments(numDocs,
            ElasticSearchIOTestUtils.InjectionMode.DO_NOT_INJECT_INVALID_DOCS);
    StringBuilder bulkRequest = new StringBuilder();
    int i = 0;//w  w w .ja  v  a  2s.c  om
    for (String document : data) {
        bulkRequest.append(String.format(
                "{ \"index\" : { \"_index\" : \"%s\", \"_type\" : \"%s\", \"_id\" : \"%s\" } }%n%s%n",
                connectionConfiguration.getIndex(), connectionConfiguration.getType(), i++, document));
    }
    String endPoint = String.format("/%s/%s/_bulk", connectionConfiguration.getIndex(),
            connectionConfiguration.getType());
    HttpEntity requestBody = new NStringEntity(bulkRequest.toString(), ContentType.APPLICATION_JSON);
    Response response = restClient.performRequest("POST", endPoint, Collections.singletonMap("refresh", "true"),
            requestBody);
    ElasticsearchIO.checkForErrors(response, ElasticsearchIO.getBackendVersion(connectionConfiguration));
}

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

/**
 * this method creates a lead in salesforce.com and returns that lead id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /* w  ww.j a v a  2  s.  com*/
 */
private Map<String, String> create() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_CREATE_LEAD_URL = args.get(INSTANCE_URL) + SALESFORCE_LEAD_URL;

    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_COMPANY, args.get(COMPANY));
    userAttrMap.put(S_LASTNAME, args.get(LASTNAME));

    TransportTools tst = new TransportTools(SALESFORCE_CREATE_LEAD_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    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:org.megam.deccanplato.provider.salesforce.crm.handler.PriceBookImpl.java

/**
 * This method updates an account in salesforce.com and returns a success message with updated account id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap //ww w  .  ja v  a  2  s .c om
 */
private Map<String, String> update() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_UPDATE_PRICEBOOK_URL = args.get(INSTANCE_URL) + SALESFORCE_PRICEBOOK_URL
            + args.get(ID);
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));
    Map<String, Object> priceBookAttrMap = new HashMap<String, Object>();
    priceBookAttrMap.put(S_NAME, args.get(NAME));
    priceBookAttrMap.put(S_DESCRIPTION, args.get(DESCRIPTION));
    priceBookAttrMap.put(S_ISACTIVE, Boolean.parseBoolean(args.get(ISACTIVE)));

    TransportTools tst = new TransportTools(SALESFORCE_UPDATE_PRICEBOOK_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(priceBookAttrMap));
    try {
        TransportMachinery.patch(tst);
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outMap;
}

From source file:org.ow2.proactive.procci.service.CloudAutomationVariablesClient.java

public void update(String key, String value) {
    logger.debug("update " + key + " on " + requestUtils.getProperty(VARIABLES_ENDPOINT));
    String url = getResourceUrl(key);
    try {//w ww .j av  a2  s.  c o m
        HttpResponse response = Request.Put(url)

                .useExpectContinue().version(HttpVersion.HTTP_1_1)
                .bodyString(value, ContentType.APPLICATION_JSON).execute().returnResponse();

        requestUtils.readHttpResponse(response, url, "PUT " + value);

    } catch (IOException ex) {
        logger.error("Unable to put on " + getResourceUrl(key) + " ,exception : " + ex.getMessage());
        throw new ServerException();
    }
}

From source file:com.epam.reportportal.service.ReportPortalErrorHandlerTest.java

@Test
public void hasError() throws Exception {
    //  given:/* www.ja va2s . c o  m*/
    LinkedListMultimap<String, String> validHeaders = LinkedListMultimap.create();
    validHeaders.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());

    LinkedListMultimap<String, String> validHeaders2 = LinkedListMultimap.create();
    validHeaders2.put(HttpHeaders.CONTENT_TYPE, "application/json;charset=UTF-8");

    LinkedListMultimap<String, String> invalidHeaders1 = LinkedListMultimap.create();
    invalidHeaders1.put(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_HTML.getMimeType());

    LinkedListMultimap<String, String> invalidHeaders2 = LinkedListMultimap.create();
    invalidHeaders2.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM.getMimeType());

    //  then:
    assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(500, validHeaders)));
    assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(404, validHeaders)));

    assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(200, invalidHeaders1)));
    assertTrue(reportPortalErrorHandler.hasError(createFakeResponse(200, invalidHeaders2)));

    //      and:
    assertFalse(reportPortalErrorHandler.hasError(createFakeResponse(200, validHeaders)));
    assertFalse(reportPortalErrorHandler.hasError(createFakeResponse(200, validHeaders2)));
}

From source file:org.piwik.java.tracking.PiwikTracker.java

/**
 * Send multiple requests in a single HTTP call.  More efficient than sending
 * several individual requests.  Specify the AuthToken if parameters that require
 * an auth token is used.//from   w  w  w  .  ja v  a2s .  com
 * @param requests the requests to send
 * @param authToken specify if any of the parameters use require AuthToken
 * @return the response from these requests
 * @throws IOException thrown if there was a problem with this connection
 */
public HttpResponse sendBulkRequest(Iterable<PiwikRequest> requests, String authToken) throws IOException {
    if (authToken != null && authToken.length() != PiwikRequest.AUTH_TOKEN_LENGTH) {
        throw new IllegalArgumentException(
                authToken + " is not " + PiwikRequest.AUTH_TOKEN_LENGTH + " characters long.");
    }

    JsonObjectBuilder ob = Json.createObjectBuilder();
    JsonArrayBuilder ab = Json.createArrayBuilder();

    for (PiwikRequest request : requests) {
        ab.add("?" + request.getQueryString());
    }

    ob.add(REQUESTS, ab);

    if (authToken != null) {
        ob.add(AUTH_TOKEN, authToken);
    }

    HttpClient client = getHttpClient();
    HttpPost post = new HttpPost(uriBuilder.build());
    post.setEntity(new StringEntity(ob.build().toString(), ContentType.APPLICATION_JSON));

    return client.execute(post);
}