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.osiam.client.connector.OsiamConnectorTest.java

private void givenUserIDcanBeFound() {
    stubFor(givenUserIDisLookedUp(userIdString, accessToken).willReturn(
            aResponse().withStatus(SC_OK).withHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType())
                    .withBodyFile("user_" + userIdString + ".json")));
}

From source file:com.shinwootns.common.infoblox.InfobloxWAPIHandler.java

public boolean insertMacFilter(String macAddr, String filterName, String userName) {

    if (restClient == null)
        return false;

    StringBuilder sb = new StringBuilder();

    sb.append("/wapi/v1.0/macfilteraddress");
    sb.append("?mac=").append(macAddr);
    sb.append("&filter=").append(filterName);
    sb.append("&username=").append(userName);
    sb.append("&_return_type=json");

    String value = restClient.Post(sb.toString(), ContentType.APPLICATION_JSON, null);

    if (value != null && value.indexOf("macfilteraddress") >= 0)
        return true;

    return false;
}

From source file:mx.openpay.client.core.impl.DefaultHttpServiceClient.java

/**
 * @see mx.openpay.client.core.HttpServiceClient#put(java.lang.String, java.lang.String)
 *///from w w  w .j  a va  2  s  .c o  m
@Override
public HttpServiceResponse put(final String url, final String json) throws ServiceUnavailableException {
    HttpPut request = new HttpPut(URI.create(url));
    request.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
    return this.executeOperation(request);
}

From source file:com.ibm.streamsx.topology.internal.context.AnalyticsServiceStreamsContext.java

private BigInteger postJob(CloseableHttpClient httpClient, JSONObject credentials, File bundle,
        JSONObject submitConfig) throws ClientProtocolException, IOException {

    String url = getSubmitURL(credentials, bundle);

    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());

    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(submitConfig.serialize(), ContentType.APPLICATION_JSON);

    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bundleBody)
            .addPart("json", configBody).build();

    postJobWithConfig.setEntity(reqEntity);

    JSONObject jsonResponse = getJsonResponse(httpClient, postJobWithConfig);

    Topology.STREAMS_LOGGER.info("Streaming Analytics Service submit job response:" + jsonResponse.serialize());

    Object jobId = jsonResponse.get("jobId");
    if (jobId == null)
        return BigInteger.valueOf(-1);
    return new BigInteger(jobId.toString());
}

From source file:com.yahoo.ycsb.db.elasticsearch5.ElasticsearchRestClient.java

@Override
public Status insert(final String table, final String key, final Map<String, ByteIterator> values) {
    try {// ww  w  . j  a  v a 2s .c  o  m
        final Map<String, String> data = StringByteIterator.getStringMap(values);
        data.put(KEY, key);

        final Response response = restClient.performRequest("POST", "/" + indexKey + "/" + table + "/",
                Collections.<String, String>emptyMap(),
                new NStringEntity(new ObjectMapper().writeValueAsString(data), ContentType.APPLICATION_JSON));

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            return Status.ERROR;
        }

        if (!isRefreshNeeded) {
            synchronized (this) {
                isRefreshNeeded = true;
            }
        }

        return Status.OK;
    } catch (final Exception e) {
        e.printStackTrace();
        return Status.ERROR;
    }
}

From source file:org.phenotips.vocabulary.internal.RemoteGeneNomenclature.java

@Override
public List<VocabularyTerm> search(Map<String, ?> fieldValues, Map<String, String> queryOptions) {
    try {//from   www. ja v a  2 s.  c  o  m
        HttpGet method = new HttpGet(
                this.searchServiceURL + URLEncoder.encode(generateQuery(fieldValues), Consts.UTF_8.name()));
        method.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
        try (CloseableHttpResponse httpResponse = this.client.execute(method)) {
            String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8);
            JSONObject responseJSON = new JSONObject(response);
            JSONArray docs = responseJSON.getJSONObject(RESPONSE_KEY).getJSONArray(DATA_KEY);
            if (docs.length() >= 1) {
                List<VocabularyTerm> result = new LinkedList<>();
                // The remote service doesn't offer any query control, manually select the right range
                int start = 0;
                if (queryOptions.containsKey(CommonParams.START)
                        && StringUtils.isNumeric(queryOptions.get(CommonParams.START))) {
                    start = Math.max(0, Integer.parseInt(queryOptions.get(CommonParams.START)));
                }
                int end = docs.length();
                if (queryOptions.containsKey(CommonParams.ROWS)
                        && StringUtils.isNumeric(queryOptions.get(CommonParams.ROWS))) {
                    end = Math.min(end, start + Integer.parseInt(queryOptions.get(CommonParams.ROWS)));
                }

                for (int i = start; i < end; ++i) {
                    result.add(new JSONOntologyTerm(docs.getJSONObject(i), this));
                }
                return result;
                // This is too slow, for the moment only return summaries
                // return getTerms(ids);
            }
        } catch (IOException | JSONException ex) {
            this.logger.warn("Failed to search gene names: {}", ex.getMessage());
        }
    } catch (UnsupportedEncodingException ex) {
        // This will not happen, UTF-8 is always available
    }
    return Collections.emptyList();
}

From source file:com.addthis.hydra.task.output.HttpOutputWriter.java

@Nonnull
private Integer request(String[] endpoints, String body, MutableInt retry) throws IOException {
    rotation = (rotation + 1) % endpoints.length;
    String endpoint = endpoints[rotation];
    if (retry.getValue() > 0) {
        log.info("Attempting to send to {}. Retry {}", endpoint, retry.getValue());
    }/*w  ww. j  av a2  s  .  c o  m*/
    retry.increment();
    CloseableHttpResponse response = null;
    try {
        HttpEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
        HttpUriRequest request = buildRequest(requestType, endpoint, entity);

        response = httpClient.execute(request);
        EntityUtils.consume(response.getEntity());
        return response.getStatusLine().getStatusCode();
    } finally {
        if (response != null) {
            response.close();
        }
    }
}

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

@Override
public HttpResponse postJson(String path, String postJsonBody, Map<String, String> headers)
        throws HttpClientException {
    try {// www  . j  a va2  s. com
        HttpPost post = new HttpPost(toURI(path));

        setRequestHeaders(headers, post);

        post.setEntity(new StringEntity(postJsonBody, ContentType.APPLICATION_JSON));
        post.setHeader(CONTENT_TYPE_HEADER_NAME, APPLICATION_JSON_CONTENT_TYPE);
        return execute(post);
    } catch (IOException | UnsupportedCharsetException | OAuthCommunicationException
            | OAuthExpectationFailedException | OAuthMessageSignerException e) {
        String trimmedPostBody = (postJsonBody.length() > JSON_POST_LOG_LENGTH_LIMIT)
                ? postJsonBody.substring(0, JSON_POST_LOG_LENGTH_LIMIT)
                : postJsonBody;
        throw new HttpClientException("Error executing POST request to: " + clientToString() + " path: " + path
                + " JSON body: " + trimmedPostBody, e);
    }
}

From source file:com.enitalk.opentok.CheckAvailabilityRunnable.java

@Override
@RabbitListener(queues = "youtube_check")
public void onMessage(Message msg) {
    try {// w  w  w  .j a v  a2s  .c  om
        JsonNode event = jackson.readTree(msg.getBody());
        String ii = event.path("ii").asText();
        logger.info("Check youtube came {}", ii);

        List<String> videos = jackson.convertValue(event.path("yt"), List.class);
        List<String> parts = new ArrayList<>();
        videos.stream().forEach((String link) -> {
            parts.add(StringUtils.substringAfterLast(link, "/"));
        });

        Credential credential = flow.loadCredential("yt");
        YouTube youtube = new YouTube.Builder(new NetHttpTransport(), JacksonFactory.getDefaultInstance(),
                credential).setApplicationName("enitalk").build();
        boolean refreshed = credential.refreshToken();
        logger.info("Yt refreshed {}", refreshed);

        HttpResponse rs = youtube.videos().list("processingDetails").setId(StringUtils.join(parts, ','))
                .executeUnparsed();
        InputStream is = rs.getContent();
        byte[] b = IOUtils.toByteArray(is);
        IOUtils.closeQuietly(is);

        JsonNode listTree = jackson.readTree(b);
        logger.info("List tree {}", listTree);

        List<JsonNode> items = listTree.path("items").findParents("id");
        long finished = items.stream().filter((JsonNode j) -> {
            return j.at("/processingDetails/processingStatus").asText().equals("succeeded");
        }).count();

        Query q = Query.query(Criteria.where("ii").is(ii));
        if (finished == parts.size()) {
            logger.info("Processing finished {}", ii);

            //send notification and email
            ObjectNode tree = (ObjectNode) jackson
                    .readTree(new ClassPathResource("emails/videoUploaded.json").getInputStream());
            tree.put("To", event.at("/student/email").asText());
            //                String text = tree.path("HtmlBody").asText() + StringUtils.join(videos, "\n");

            StringWriter writer = new StringWriter(29 * 1024);
            Template t = engine.getTemplate("video.html");
            VelocityContext context = new VelocityContext();
            context.put("video", videos.iterator().next());
            t.merge(context, writer);

            tree.put("HtmlBody", writer.toString());

            //make chat and attach it
            String chatTxt = makeChat(event);
            if (StringUtils.isNotBlank(chatTxt)) {
                ArrayNode attachments = jackson.createArrayNode();
                ObjectNode a = attachments.addObject();
                a.put("Name", "chat.txt");
                a.put("ContentType", "text/plain");
                a.put("Content", chatTxt.getBytes("UTF-8"));

                tree.set("Attachments", attachments);
            } else {
                logger.info("No chat available for {}", event.path("ii").asText());
            }

            logger.info("Sending video and chat {} to student", ii);

            org.apache.http.HttpResponse response = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r = EntityUtils.toByteArray(response.getEntity());
            JsonNode emailResp = jackson.readTree(r);

            Update u = new Update().set("video", 4);
            if (StringUtils.isNotBlank(chatTxt)) {
                u.set("chat", chatTxt);
            }

            u.set("student.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("student.uploader.rs", jackson.convertValue(emailResp, HashMap.class));

            tree.put("To", event.at("/teacher/email").asText());
            logger.info("Sending video and chat {} to teacher", ii);

            org.apache.http.HttpResponse response2 = Request.Post("https://api.postmarkapp.com/email")
                    .addHeader("X-Postmark-Server-Token", env.getProperty("postmark.token"))
                    .bodyByteArray(jackson.writeValueAsBytes(tree), ContentType.APPLICATION_JSON).execute()
                    .returnResponse();
            byte[] r2 = EntityUtils.toByteArray(response2.getEntity());
            JsonNode emailResp2 = jackson.readTree(r2);

            u.set("teacher.uploader.rq", jackson.convertValue(tree, HashMap.class));
            u.set("teacher.uploader.rs", jackson.convertValue(emailResp2, HashMap.class));
            u.set("f", 1);

            mongo.updateFirst(q, u, "events");

            //                JsonNode dest = event.at("/student/dest");
            //
            //                ArrayNode msgs = jackson.createArrayNode();
            //                ObjectNode o = msgs.addObject();
            //                o.set("dest", dest);
            //                ObjectNode m = jackson.createObjectNode();
            //                o.set("message", m);
            //                m.put("text", "0x1f3a5 We have uploaded your lesson to Youtube. It is available to you and the teacher only. \n"
            //                        + "Please, do not share it with anyone\n Also, we sent the video link and the text chat to your email.");
            //
            //                ArrayNode buttons = jackson.createArrayNode();
            //                m.set("buttons", buttons);
            //                m.put("buttonsPerRow", 1);
            //
            //                if (videos.size() == 1) {
            //                    botController.makeButtonHref(buttons, "Watch on Youtube", videos.get(0));
            //                } else {
            //                    AtomicInteger cc = new AtomicInteger(1);
            //                    videos.stream().forEach((String y) -> {
            //                        botController.makeButtonHref(buttons, "Watch on Youtube, part " + cc.getAndIncrement(), y);
            //                    });
            //                }
            //
            //                botController.sendMessages(msgs);
            //
            //                sendFeedback(dest, event);

        } else {
            logger.info("{} parts only finished for {}", finished, ii);
            mongo.updateFirst(q,
                    new Update().inc("check", 1).set("checkDate", new DateTime().plusMinutes(12).toDate()),
                    "events");
        }

    } catch (Exception e) {
        logger.error(ExceptionUtils.getFullStackTrace(e));
    }
}