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.blacklocus.jres.handler.JresJsonResponseHandler.java

<RESPONSE extends JresReply> Pair<JsonNode, RESPONSE> read(HttpResponse http, Class<RESPONSE> responseClass) {
    if (http.getEntity() == null) {
        return null;

    } else {//w  w  w.  ja v  a 2s  .  c o m
        ContentType contentType = ContentType.parse(http.getEntity().getContentType().getValue());
        if (ContentType.APPLICATION_JSON.getMimeType().equals(contentType.getMimeType())) {
            try {

                JsonNode node = ObjectMappers.fromJson(http.getEntity().getContent(), JsonNode.class);
                if (LOG.isDebugEnabled()) {
                    LOG.debug(ObjectMappers.toJson(node));
                }
                return Pair.of(node,
                        responseClass == null ? null : ObjectMappers.fromJson(node, responseClass));

            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else {
            throw new RuntimeException("Unable to read content with " + contentType
                    + ". This ResponseHandler can only decode " + ContentType.APPLICATION_JSON);
        }
    }
}

From source file:com.seyren.core.service.notification.HubotNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String hubotUrl = StringUtils.trimToNull(seyrenConfig.getHubotUrl());

    if (hubotUrl == null) {
        LOGGER.warn("Hubot URL needs to be set before sending notifications to Hubot");
        return;//from w w  w.  j  a  va  2 s. c  o  m
    }

    Map<String, Object> body = new HashMap<String, Object>();
    body.put("seyrenUrl", seyrenConfig.getBaseUrl());
    body.put("check", check);
    body.put("subscription", subscription);
    body.put("alerts", alerts);
    body.put("rooms", subscription.getTarget().split(","));

    HttpClient client = HttpClientBuilder.create().useSystemProperties().build();

    HttpPost post = new HttpPost(hubotUrl + "/seyren/alert");
    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        client.execute(post);
    } catch (IOException e) {
        throw new NotificationFailedException("Sending notification to Hubot at " + hubotUrl + " failed.", e);
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

From source file:com.urswolfer.intellij.plugin.gerrit.errorreport.PluginErrorReportSubmitter.java

private void postError(String json) {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(ERROR_REPORT_URL);
    httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
    try {//  www .  ja  v a 2 s  .  co m
        httpClient.execute(httpPost);
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
}

From source file:org.elasticstore.server.integration.ItemIT.java

@Test
public void testCreateRetrieveAndDeleteItem() throws Exception {
    final Item item = Fixtures.randomItem();
    // create the item
    HttpResponse resp = executor//from  w ww  . ja  v  a 2 s  . c o m
            .execute(Request.Post(serverUrl + "/item").useExpectContinue()
                    .bodyString(mapper.writeValueAsString(item), ContentType.APPLICATION_JSON))
            .returnResponse();

    assertEquals(201, resp.getStatusLine().getStatusCode());

    // retrieve the item
    resp = executor.execute(Request.Get(serverUrl + "/item/" + item.getId()).useExpectContinue())
            .returnResponse();
    assertEquals(200, resp.getStatusLine().getStatusCode());
    final Item fetched = mapper.readValue(resp.getEntity().getContent(), Item.class);
    assertEquals(item.getId(), fetched.getId());
    assertEquals(item.getLabel(), fetched.getLabel());
    assertNotNull(fetched.getCreated());
    assertNotNull(fetched.getLastModified());

    // delete the item
    resp = executor.execute(Request.Delete(serverUrl + "/item/" + item.getId()).useExpectContinue())
            .returnResponse();
    Assert.assertEquals(200, resp.getStatusLine().getStatusCode());

    //retrieve the item again and assert a 404
    resp = executor.execute(Request.Get(serverUrl + "/item/" + item.getId()).useExpectContinue())
            .returnResponse();
    assertEquals(404, resp.getStatusLine().getStatusCode());
}

From source file:org.apache.hawq.ranger.integration.service.tests.common.RESTClient.java

private String executeRequest(HttpUriRequest request) throws IOException {

    LOG.debug("--> request URI = " + request.getURI());

    request.setHeader("Authorization", AUTH_HEADER);
    request.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());

    CloseableHttpResponse response = httpClient.execute(request);
    String payload = null;/*w w  w .  j  a va  2s.c om*/
    try {
        int responseCode = response.getStatusLine().getStatusCode();
        LOG.debug("<-- response code = " + responseCode);

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            payload = EntityUtils.toString(response.getEntity());
        }
        LOG.debug("<-- response payload = " + payload);

        if (responseCode == HttpStatus.SC_NOT_FOUND) {
            throw new ResourceNotFoundException();
        } else if (responseCode >= 300) {
            throw new ClientProtocolException("Unexpected HTTP response code = " + responseCode);
        }
    } finally {
        response.close();
    }

    return payload;
}

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

@Override
public HttpServletResponse build(HttpServletResponse response, Exception exception, Fields input, Fields output)
        throws IOException {
    response.setContentType(ContentType.APPLICATION_JSON.toString());

    LOGGER.info("Before choosing");
    response.setStatus(chooseStatusCode(exception));
    LOGGER.info("After choosing");

    List<ErrorEntity> errors = null;
    if (exception instanceof BiokoException) {
        errors = ((BiokoException) exception).getErrors();
    }/*w w w  . ja  v  a2  s . com*/

    if (errors == null || errors.isEmpty()) {
        errors = new ArrayList<>();
        StringBuilder message = new StringBuilder().append("An unexpected exception as been captured ")
                .append(descriptionOf(exception));

        ErrorEntity entity = new ErrorEntity();
        entity.setAll(new Fields(ErrorEntity.ERROR_CODE, FieldNames.CONTAINER_EXCEPTION_CODE,
                ErrorEntity.ERROR_MESSAGE, message.toString()));
        errors.add(entity);
    }
    IOUtils.copy(new StringReader(JSONValue.toJSONString(errors)), response.getWriter());

    return response;
}

From source file:io.crate.integrationtests.SQLHttpIntegrationTest.java

protected CloseableHttpResponse post(String body, @Nullable Header[] headers) throws IOException {
    if (body != null) {
        StringEntity bodyEntity = new StringEntity(body, ContentType.APPLICATION_JSON);
        httpPost.setEntity(bodyEntity);//  w w w . j  a v  a2  s.c  om
    }
    httpPost.setHeaders(headers);
    return httpClient.execute(httpPost);
}

From source file:com.jive.myco.seyren.core.service.notification.HubotNotificationService.java

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {
    String hubotUrl = StringUtils.trimToNull(seyrenConfig.getHubotUrl());

    if (hubotUrl == null) {
        LOGGER.warn("Hubot URL needs to be set before sending notifications to Hubot");
        return;//from  www .ja v  a  2s  .  c  o  m
    }

    Map<String, Object> body = new HashMap<String, Object>();
    body.put("seyrenUrl", seyrenConfig.getBaseUrl());
    body.put("check", check);
    body.put("subscription", subscription);
    body.put("alerts", alerts);
    body.put("rooms", subscription.getTarget().split(","));

    HttpClient client = HttpClientBuilder.create().build();

    HttpPost post = new HttpPost(hubotUrl + "/seyren/alert");
    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        client.execute(post);
    } catch (IOException e) {
        throw new NotificationFailedException("Sending notification to Hubot at " + hubotUrl + " failed.", e);
    } finally {
        HttpClientUtils.closeQuietly(client);
    }
}

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

public void post(String key, String value) {

    logger.debug("post " + key + " on " + requestUtils.getProperty(VARIABLES_ENDPOINT));
    String url = getQueryUrl(key);
    try {/*from w w  w . j av  a 2s  . c  o m*/
        HttpResponse response = Request.Post(url)

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

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

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

}

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

@SuppressWarnings("unchecked")
@Override//from w  w  w .  j ava2s.  c o  m
public HttpEntity createDocument(Task task) {
    JSONObject taskObject = new JSONObject();
    taskObject.put("title", task.getTitle());
    taskObject.put("priority", task.getPriority());
    taskObject.put("ordering", task.getOrdering());
    Integer processingStatus = task.getProcessingStatusEnum() != null
            ? task.getProcessingStatusEnum().getValue()
            : null;
    taskObject.put("processingStatus", processingStatus);
    String processingTime = task.getProcessingTime() != null ? formatDate(task.getProcessingTime()) : null;
    taskObject.put("processingTime", processingTime);
    String processingBegin = task.getProcessingBegin() != null ? formatDate(task.getProcessingBegin()) : null;
    taskObject.put("processingBegin", processingBegin);
    String processingEnd = task.getProcessingEnd() != null ? formatDate(task.getProcessingEnd()) : null;
    taskObject.put("processingEnd", processingEnd);
    taskObject.put("homeDirectory", String.valueOf(task.getHomeDirectory()));
    taskObject.put("typeMetadata", String.valueOf(task.isTypeMetadata()));
    taskObject.put("typeAutomatic", String.valueOf(task.isTypeAutomatic()));
    taskObject.put("typeImportFileUpload", String.valueOf(task.isTypeImportFileUpload()));
    taskObject.put("typeExportRussian", String.valueOf(task.isTypeExportRussian()));
    taskObject.put("typeImagesRead", String.valueOf(task.isTypeImagesRead()));
    taskObject.put("typeImagesWrite", String.valueOf(task.isTypeImagesWrite()));
    taskObject.put("typeModuleName", task.getTypeModuleName());
    taskObject.put("batchStep", String.valueOf(task.isBatchStep()));
    Integer processingUser = task.getProcessingUser() != null ? task.getProcessingUser().getId() : null;
    taskObject.put("processingUser", processingUser);
    Integer process = task.getProcess() != null ? task.getProcess().getId() : null;
    taskObject.put("process", process);
    taskObject.put("users", addObjectRelation(task.getUsers()));
    taskObject.put("userGroups", addObjectRelation(task.getUserGroups()));

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