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.arcbees.vcs.stash.StashApi.java

@Override
public Comment postComment(Integer pullRequestId, String comment) throws IOException {
    String requestUrl = apiPaths.addComment(repositoryOwner, repositoryName, pullRequestId);

    HttpPost request = new HttpPost(requestUrl);
    request.setHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()));
    request.setEntity(new ByteArrayEntity(gson.toJson(new StashComment(comment)).getBytes(Charsets.UTF_8)));

    return processResponse(httpClient, request, credentials, gson, StashComment.class);
}

From source file:org.apache.calcite.adapter.elasticsearch.ElasticsearchTable.java

private ElasticsearchSearchResult httpRequest(String query) throws IOException {
    Objects.requireNonNull(query, "query");
    String uri = String.format(Locale.ROOT, "/%s/%s/_search", indexName, typeName);
    HttpEntity entity = new StringEntity(query, ContentType.APPLICATION_JSON);
    Response response = restClient.performRequest("POST", uri, Collections.emptyMap(), entity);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        final String error = EntityUtils.toString(response.getEntity());
        final String message = String.format(Locale.ROOT,
                "Error while querying Elastic (on %s/%s) status: %s\nQuery:\n%s\nError:\n%s\n",
                response.getHost(), response.getRequestLine(), response.getStatusLine(), query, error);
        throw new RuntimeException(message);
    }/*from w w w .  j a v a2  s  .c om*/

    try (InputStream is = response.getEntity().getContent()) {
        return mapper.readValue(is, ElasticsearchSearchResult.class);
    }
}

From source file:it.larusba.neo4j.jdbc.http.driver.CypherExecutor.java

/**
 * Execute a list of cypher queries./*  w ww  .  j av  a 2  s. c o  m*/
 *
 * @param queries List of cypher query object
 * @return A list of Neo4j response
 * @throws SQLException
 */
public Neo4jResponse executeQueries(List<Neo4jStatement> queries) throws SQLException {
    // Prepare the headers query
    HttpPost request = new HttpPost(currentTransactionUrl);

    // Prepare body request
    StringEntity requestEntity = new StringEntity(Neo4jStatement.toJson(queries, this.mapper),
            ContentType.APPLICATION_JSON);
    request.setEntity(requestEntity);

    // Make the request
    return this.executeHttpRequest(request);
}

From source file:com.nextdoor.bender.ipc.es.ElasticSearchTransporterTest.java

@Test(expected = TransportException.class)
public void testErrorsResponse() throws TransportException, IOException {
    byte[] respPayload = getResponse().getBytes(StandardCharsets.UTF_8);

    HttpClient client = getMockClientWithResponse(respPayload, ContentType.APPLICATION_JSON, HttpStatus.SC_OK);
    ElasticSearchTransport transport = new ElasticSearchTransport(client, false);

    try {//from   www  .j  a v  a 2  s  .  c o m
        transport.sendBatch("foo".getBytes());
    } catch (Exception e) {
        assertEquals("es index failure count is 1", e.getCause().getMessage());
        throw e;
    }
}

From source file:org.biokoframework.system.services.push.impl.SendPushCommand.java

private void sendPush(String userToken, String message, Boolean production)
        throws NotificationFailureException {
    try {//from www  .  j av a  2s  .c  om

        Fields fields = new Fields();
        fields.put(AbstractPushNotificationService.APP_TOKEN, fAppToken);
        fields.put(AbstractPushNotificationService.APP_SECRET, fAppSecret);
        fields.put(AbstractPushNotificationService.USER_TOKEN, userToken);
        fields.put(AbstractPushNotificationService.MESSAGE, message);
        fields.put(IPushNotificationService.PRODUCTION, production);

        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(fPusherdrilloUrl + AbstractPushNotificationService.SEND_TARGETED_MESSAGE);
        post.setEntity(new StringEntity(fields.toJSONString(), ContentType.APPLICATION_JSON));

        post.completed();

        HttpResponse response = client.execute(post);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new NotificationFailureException(EntityUtils.toString(response.getEntity()));
        }

    } catch (NotificationFailureException exception) {
        throw exception;
    } catch (Exception exception) {
        throw new NotificationFailureException(exception);
    }
}

From source file:org.apache.metron.elasticsearch.integration.ElasticsearchSearchIntegrationTest.java

protected static void loadTestData() throws ParseException, IOException {
    // add bro template
    JSONObject broTemplate = JSONUtils.INSTANCE.load(new File(broTemplatePath), JSONObject.class);
    addTestFieldMappings(broTemplate, "bro_doc");
    String broTemplateJson = JSONUtils.INSTANCE.toJSON(broTemplate, true);
    HttpEntity broEntity = new NStringEntity(broTemplateJson, ContentType.APPLICATION_JSON);
    Response response = lowLevelClient.performRequest("PUT", "/_template/bro_template", Collections.emptyMap(),
            broEntity);// w w w.jav  a 2s .  co  m
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    // add snort template
    JSONObject snortTemplate = JSONUtils.INSTANCE.load(new File(snortTemplatePath), JSONObject.class);
    addTestFieldMappings(snortTemplate, "snort_doc");
    String snortTemplateJson = JSONUtils.INSTANCE.toJSON(snortTemplate, true);
    HttpEntity snortEntity = new NStringEntity(snortTemplateJson, ContentType.APPLICATION_JSON);
    response = lowLevelClient.performRequest("PUT", "/_template/snort_template", Collections.emptyMap(),
            snortEntity);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    // create bro index
    response = lowLevelClient.performRequest("PUT", BRO_INDEX);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    // create snort index
    response = lowLevelClient.performRequest("PUT", SNORT_INDEX);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));

    JSONArray broRecords = (JSONArray) new JSONParser().parse(broData);

    BulkRequest bulkRequest = new BulkRequest();
    for (Object o : broRecords) {
        JSONObject json = (JSONObject) o;
        IndexRequest indexRequest = new IndexRequest(BRO_INDEX, "bro_doc", (String) json.get("guid"));
        indexRequest.source(json);
        indexRequest.timestamp(json.get("timestamp").toString());
        bulkRequest.add(indexRequest);
    }
    bulkRequest.setRefreshPolicy(RefreshPolicy.WAIT_UNTIL);
    BulkResponse bulkResponse = highLevelClient.bulk(bulkRequest);
    assertFalse(bulkResponse.hasFailures());
    assertThat(bulkResponse.status().getStatus(), equalTo(200));

    JSONArray snortRecords = (JSONArray) new JSONParser().parse(snortData);

    bulkRequest = new BulkRequest();
    for (Object o : snortRecords) {
        JSONObject json = (JSONObject) o;
        IndexRequest indexRequest = new IndexRequest(SNORT_INDEX, "snort_doc", (String) json.get("guid"));
        indexRequest.source(json);
        indexRequest.timestamp(json.get("timestamp").toString());
        bulkRequest.add(indexRequest);
    }
    bulkRequest.setRefreshPolicy(RefreshPolicy.WAIT_UNTIL);
    bulkResponse = highLevelClient.bulk(bulkRequest);
    assertFalse(bulkResponse.hasFailures());
    assertThat(bulkResponse.status().getStatus(), equalTo(200));
}

From source file:net.freifunk.autodeploy.firmware.FreifunkHamburgConfigurator.java

private HttpResponse doPost(final URI uri, final Map<String, String> postData) throws IOException {
    final HttpPost request = new HttpPost(uri);

    request.setEntity(/*from   w  w w . ja va2s  . c o m*/
            new StringEntity(_objectMapper.writeValueAsString(postData), ContentType.APPLICATION_JSON));

    return _httpClient.execute(request);
}

From source file:com.arpnetworking.tsdcore.sinks.HttpPostSink.java

/**
 * Creates an HTTP request from a serialized data entry. Default is an <code>HttpPost</code> containing
 * serializedData as the body with content type of application/json
 * @param serializedData The serialized data.
 * @return <code>HttpRequest</code> to execute
 *///from ww w  . jav  a 2  s .co m
protected HttpUriRequest createRequest(final String serializedData) {
    final StringEntity requestEntity = new StringEntity(serializedData, ContentType.APPLICATION_JSON);
    final HttpPost request = new HttpPost(_uri);
    request.setEntity(requestEntity);
    return request;
}

From source file:org.modeshape.jcr.index.elasticsearch.client.EsClient.java

/**
 * Indexes document./*from  w  w w .jav a  2 s . c o m*/
 *
 * @param name the name of the index.
 * @param type index type
 * @param id document id
 * @param doc document
 * @return true if document was indexed.
 * @throws IOException
 */
public boolean storeDocument(String name, String type, String id, EsRequest doc) throws IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost method = new HttpPost(String.format("http://%s:%d/%s/%s/%s", host, port, name, type, id));
    try {
        StringEntity requestEntity = new StringEntity(doc.toString(), ContentType.APPLICATION_JSON);
        method.setEntity(requestEntity);
        CloseableHttpResponse resp = client.execute(method);
        int statusCode = resp.getStatusLine().getStatusCode();
        return statusCode == HttpStatus.SC_CREATED || statusCode == HttpStatus.SC_OK;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.jivesoftware.os.routing.bird.http.client.ApacheHttpClient441BackedHttpClient.java

private HttpStreamResponse executePostJsonStreamingResponse(HttpEntityEnclosingRequestBase requestBase,
        String jsonBody, Map<String, String> headers) throws HttpClientException {
    try {/*w  ww .j av a  2 s  . com*/
        setRequestHeaders(headers, requestBase);

        requestBase.setEntity(new StringEntity(jsonBody, ContentType.APPLICATION_JSON));
        requestBase.addHeader(CONTENT_TYPE_HEADER_NAME, APPLICATION_JSON_CONTENT_TYPE);
        return executeStream(requestBase);
    } catch (IOException | UnsupportedCharsetException | OAuthCommunicationException
            | OAuthExpectationFailedException | OAuthMessageSignerException e) {
        String trimmedMethodBody = (jsonBody.length() > JSON_POST_LOG_LENGTH_LIMIT)
                ? jsonBody.substring(0, JSON_POST_LOG_LENGTH_LIMIT)
                : jsonBody;
        throw new HttpClientException(
                "Error executing " + requestBase.getMethod() + " request to: " + clientToString() + " path: "
                        + requestBase.getURI().getPath() + " JSON body: " + trimmedMethodBody,
                e);
    }
}