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.vmware.photon.controller.api.client.resource.ApiTestBase.java

@SuppressWarnings("unchecked")
public final void setupMocks(String serializedResponse, int responseCode) throws IOException {
    this.asyncHttpClient = mock(CloseableHttpAsyncClient.class);
    this.httpClient = mock(HttpClient.class);

    doAnswer(new Answer<Object>() {
        @Override/*from   w  w w.  j  a va  2  s .co m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return null;
        }
    }).when(this.asyncHttpClient).close();

    this.restClient = new RestClient("http://1.1.1.1", this.asyncHttpClient, this.httpClient);

    final HttpResponse httpResponse = mock(HttpResponse.class);
    StatusLine statusLine = mock(StatusLine.class);
    when(httpResponse.getStatusLine()).thenReturn(statusLine);
    when(statusLine.getStatusCode()).thenReturn(responseCode);
    when(httpResponse.getEntity())
            .thenReturn(new StringEntity(serializedResponse, ContentType.APPLICATION_JSON));

    final Future<HttpResponse> httpResponseFuture = new Future<HttpResponse>() {
        @Override
        public boolean cancel(boolean mayInterruptIfRunning) {
            return false;
        }

        @Override
        public boolean isCancelled() {
            return false;
        }

        @Override
        public boolean isDone() {
            return true;
        }

        @Override
        public HttpResponse get() throws InterruptedException, ExecutionException {
            return httpResponse;
        }

        @Override
        public HttpResponse get(long timeout, TimeUnit unit)
                throws InterruptedException, ExecutionException, TimeoutException {
            return httpResponse;
        }
    };

    when(this.httpClient.execute(any(HttpUriRequest.class))).thenReturn(httpResponse);

    when(this.asyncHttpClient.execute(any(HttpUriRequest.class), any(BasicHttpContext.class),
            any(FutureCallback.class))).thenAnswer(new Answer<Object>() {
                @Override
                public Object answer(InvocationOnMock invocation) throws Throwable {
                    if (invocation.getArguments()[ARGUMENT_INDEX_TWO] != null) {
                        ((FutureCallback<HttpResponse>) invocation.getArguments()[ARGUMENT_INDEX_TWO])
                                .completed(httpResponse);
                    }
                    return httpResponseFuture;
                }
            });
}

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

@Override
public void sendNotification(Check check, Subscription subscription, List<Alert> alerts)
        throws NotificationFailedException {

    String httpUrl = StringUtils.trimToNull(subscription.getTarget());

    if (httpUrl == null) {
        LOGGER.warn("URL needs to be set before sending notifications to HTTP");
        return;/*from   w  w w  .  j a v a2  s  .  c  om*/
    }
    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("preview", getPreviewImage(check));

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

    HttpPost post = new HttpPost(subscription.getTarget());
    try {
        HttpEntity entity = new StringEntity(MAPPER.writeValueAsString(body), ContentType.APPLICATION_JSON);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            LOGGER.info("Response : {} ", EntityUtils.toString(responseEntity));
        }
    } catch (Exception e) {
        throw new NotificationFailedException("Failed to send notification to HTTP", e);
    } finally {
        post.releaseConnection();
        HttpClientUtils.closeQuietly(client);
    }
}

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

@Test(expected = ReportPortalException.class)
public void handle_known_error() throws Exception {
    //  given:/*from  w w w. java2 s . c  om*/
    LinkedListMultimap<String, String> invalidHeaders = LinkedListMultimap.create();
    invalidHeaders.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());

    Response<ByteSource> invalidResponse = createFakeResponse(500, invalidHeaders,
            "{\"error_code\": \"4004\",\"stack_trace\": \"test.com\",\"message\": \"Test message goes here\"}");

    //  when:
    reportPortalErrorHandler.handle(invalidResponse);
}

From source file:guru.nidi.atlassian.remote.meta.client.JiraExportClient.java

private String generateExport(JiraGenerateRequest request) throws IOException {
    final String jsonRequest = mapper.writeValueAsString(new RequestHolder(request));
    final HttpPost post = new HttpPost(serverUrl + "/action/generate/jira");
    post.setEntity(new StringEntity(jsonRequest, ContentType.APPLICATION_JSON));
    HttpUtils.setAuthHeader(post, username, password);
    final HttpResponse response = client.execute(post);
    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throwClientException("Problem generating the export", response);
    }/*from ww  w  .j a v a 2s  . c  om*/
    return mapper.readValue(response.getEntity().getContent(), UrlHolder.class).getUrl();
}

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

@Test
public void testOkResponse() throws TransportException, IOException {
    byte[] respPayload = "{}".getBytes(StandardCharsets.UTF_8);
    byte[] payload = "foo".getBytes();

    HttpClient client = getMockClientWithResponse(respPayload, ContentType.APPLICATION_JSON, HttpStatus.SC_OK,
            false);/*from   ww w. j  a v a 2 s  .co m*/
    HttpTransport transport = new HttpTransport(client, "", false, 1, 1);
    transport.sendBatch(payload);
}

From source file:net.fischboeck.discogs.DiscogsClient.java

private Collection<Header> getDefaultHeaders() {
    Set<Header> defaultHeaders = new HashSet<Header>();

    // set accept and content type headers
    defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()));
    defaultHeaders.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()));

    return defaultHeaders;
}

From source file:com.nextdoor.bender.ipc.es.ElasticSearchTransporterTest.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);
    ElasticSearchTransport transport = new ElasticSearchTransport(client, false);

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

From source file:info.losd.galen.scheduler.Scheduler.java

@Scheduled(fixedDelay = 500)
public void processTasks() {
    List<Task> tasks = repo.findTasksToBeRun();
    LOG.debug("There are {} tasks waiting", tasks.size());

    tasks.forEach(task -> {/*from   w w  w . j  ava 2s .  c o m*/
        LOG.debug("processing: {}", task.toString());

        Map<String, String> headers = new HashMap<>();
        task.getHeaders().forEach(header -> {
            headers.put(header.getHeader(), header.getValue());
        });

        SchedulerHealthcheck healthcheckRequest = new SchedulerHealthcheck();
        healthcheckRequest.setHeaders(headers);
        healthcheckRequest.setMethod(task.getMethod());
        healthcheckRequest.setTag(task.getName());
        healthcheckRequest.setUrl(task.getUrl());

        try {
            String body = mapper.writeValueAsString(healthcheckRequest);

            HttpResponse response = Request.Post("http://127.0.0.1:8080/healthchecks")
                    .bodyString(body, ContentType.APPLICATION_JSON).execute().returnResponse();

            StatusLine status = response.getStatusLine();
            if (status.getStatusCode() == 200) {
                task.setLastUpdated(Instant.now());
                repo.save(task);
                LOG.debug("processed:  {}", task.getId());
            } else {
                LOG.error("task: {}, status code: {}, reason: {}\nbody: {}", task.getId(),
                        status.getStatusCode(), status.getReasonPhrase(),
                        IOUtils.toString(response.getEntity().getContent()));
            }
        } catch (Exception e) {
            LOG.error("Problem processing task {}", task.getId(), e);
        }
    });
}

From source file:com.srotya.tau.dengine.bolts.helpers.AlertViewerBolt.java

@Override
public void execute(Tuple tuple) {
    short ruleId = 0;
    try {/*from  w  w w  . j  ava  2s  .  c o  m*/
        ruleId = tuple.getShortByField(Constants.FIELD_RULE_ID);
        String endPoint = uiEndpoint + ruleId;
        TauEvent event = (TauEvent) tuple.getValueByField(Constants.FIELD_EVENT);
        HttpPost req = new HttpPost(endPoint);
        req.setEntity(new StringEntity(new Gson().toJson(event.getHeaders()), ContentType.APPLICATION_JSON));
        CloseableHttpResponse resp = client.execute(req);
        counter++;
        if (counter % 1000 == 0) {
            System.out.println(endPoint + "\t" + resp.getStatusLine().getStatusCode() + "\t"
                    + EntityUtils.toString(resp.getEntity()));
            System.err.println("Alerts sent to UI:" + counter);
        }
    } catch (Exception e) {
        StormContextUtil.emitErrorTuple(collector, tuple, AlertViewerBolt.class, tuple.toString(),
                "Failed to send alert to UI", e);
    }
    collector.ack(tuple);
}

From source file:com.example.app.communication.service.SmsService.java

/**
 * Send an Sms message to the specified phone number with the given content.
 *
 * @param recipient the intended recipient of the message
 * @param content the content of the message
 *
 * @return a Future representing the success of the action.
 */// ww w . jav a  2 s.com
public Future<Boolean> sendSms(@Nonnull final PhoneNumber recipient, @Nonnull final String content) {
    return _executorConfig.executorService().submit(() -> {
        //All we want is a raw number with a '+' in front -- so we strip the formatting.
        String numberToDial = PAT_PHONE_SEPARATORS.matcher(recipient.toExternalForm()).replaceAll("");

        Gson gson = new GsonBuilder().create();

        TropoRequest request = new TropoRequest();
        request.action = "create";
        request.message = content;
        request.numberToDial = numberToDial;
        request.token = _tropoMessageApiKey;

        try {
            return Request.Post(_tropoEndpoint).addHeader("accept", "application/json")
                    .addHeader("content-type", "application/json")
                    .bodyString(gson.toJson(request), ContentType.APPLICATION_JSON).execute()
                    .handleResponse(httpResponse -> {
                        if (httpResponse.getStatusLine().getStatusCode() != ResponseStatus.OK.getCode()) {
                            _logger.warn("Sms Message sending failed.  Status code: "
                                    + httpResponse.getStatusLine().getStatusCode() + " was returned.");
                            return false;
                        }
                        String responseString = EntityUtils.toString(httpResponse.getEntity());
                        TropoResponse response = gson.fromJson(responseString, TropoResponse.class);
                        if (response.success == null || !response.success) {
                            _logger.warn("Sms Message sending failed. Tropo Response: " + responseString);
                            return false;
                        }
                        return true;
                    });
        } catch (IOException e) {
            _logger.error("Unable to send Sms message request to Tropo.", e);
            return false;
        }
    });
}