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.ibm.mds.MobileServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String question = req.getParameter("questionText");

    if (question == null || question.trim().equals("")) {
        doResp(formartErrJsonMsg(RESP_ERR_COMMAND_NOT_CORRECT, RESP_TXT_COMMAND_NOT_CORRECT), resp);
        return;//from w w  w. j av  a 2 s  .c o  m
    }

    // create the { 'question' : {
    // 'questionText:'...',
    // 'evidenceRequest': { 'items': 5} } json as requested by the service
    JSONObject questionJson = new JSONObject();
    questionJson.put("questionText", question);
    JSONObject evidenceRequest = new JSONObject();
    evidenceRequest.put("items", 5);
    questionJson.put("evidenceRequest", evidenceRequest);

    JSONObject postData = new JSONObject();
    postData.put("question", questionJson);

    try {
        Executor executor = Executor.newInstance().auth(username, password);
        URI serviceURI = new URI(baseURL + "/v1/question/travel").normalize();

        String answersJsonStr = executor
                .execute(Request.Post(serviceURI).addHeader("Accept", "application/json")
                        .addHeader("X-SyncTimeout", "30")
                        .bodyString(postData.toString(), ContentType.APPLICATION_JSON))
                .returnContent().asString();

        JSONObject resultObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();

        JSONArray pipelines = JSONArray.parse(answersJsonStr);
        // the response has two pipelines, lets use the first one
        JSONObject answersJson = (JSONObject) pipelines.get(0);
        JSONArray answers = (JSONArray) ((JSONObject) answersJson.get("question")).get("evidencelist");

        for (int i = 0; i < answers.size(); i++) {
            JSONObject answer = (JSONObject) answers.get(i);
            double p = Double.parseDouble((String) answer.get("value"));
            p = Math.floor(p * 100);
            JSONObject obj = new JSONObject();
            obj.put("confidence", Double.toString(p) + "%");
            obj.put("text", (String) answer.get("text"));
            jsonArray.add(obj);
        }

        resultObject.put("respCode", RESP_SUCCESS);
        resultObject.put("body", jsonArray);

        doResp(resultObject.toString(), resp);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:io.symcpe.hendrix.storm.bolts.helpers.AlertViewerBolt.java

@Override
public void execute(Tuple tuple) {
    short ruleId = 0;
    try {/*from w w  w.j  a  v a 2  s.  c om*/
        ruleId = tuple.getShortByField(Constants.FIELD_RULE_ID);
        String endPoint = uiEndpoint + ruleId;
        HendrixEvent event = (HendrixEvent) 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:org.hawkular.component.availcreator.AvailPublisher.java

@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public void sendToMetricsViaRest(List<SingleAvail> availabilities) {
    // Send it to metrics via rest

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

    for (SingleAvail avr : availabilities) {

        String rid = avr.id;/* w w w .java  2 s  . c om*/
        String tenantId = avr.tenantId;

        HttpPost request = new HttpPost(METRICS_BASE_URI + "/availability/" + rid + "/data");
        request.addHeader("Hawkular-Tenant", tenantId);

        Availability availability = new Availability(avr.timestamp, avr.avail.toLowerCase());
        List<Availability> list = new ArrayList<>(1);
        list.add(availability);
        String payload = new Gson().toJson(list);
        request.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));

        try {
            HttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() > 399) {
                Log.LOG.wAvailPostStatus(response.getStatusLine().toString());
            }
        } catch (IOException e) {
            Log.LOG.wAvailPostStatus(e.getMessage());
        }
    }
}

From source file:org.megam.deccanplato.provider.box.handler.FolderImpl.java

/**
 * @return/*from w w w.  ja v  a2  s  . c  om*/
 */
private Map<String, String> retrive() {

    Map<String, String> outMap = new HashMap<>();
    final String BOX_RETRIVE = "/folders/" + args.get(FOLDER_ID) + "/items";

    Map<String, String> headerMap = new HashMap<String, String>();
    headerMap.put("Authorization", "BoxAuth api_key=" + args.get(API_KEY) + "&auth_token=" + args.get(TOKEN));

    Map<String, String> boxList = new HashMap<>();
    boxList.put("limit", args.get(LIMIT));
    boxList.put("offset", args.get(OFFSET));

    TransportTools tools = new TransportTools(BOX_URI + BOX_RETRIVE, null, headerMap);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tools.setContentType(ContentType.APPLICATION_JSON, obj.toJson(boxList));
    String responseBody = "";
    TransportResponse response = null;
    try {
        response = TransportMachinery.get(tools);
        responseBody = response.entityToString();
        System.out.println("OUTPUT:" + responseBody);
    } catch (ClientProtocolException ce) {
        ce.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    outMap.put(OUTPUT, responseBody);
    return outMap;
}

From source file:com.qwazr.graph.test.FullTest.java

@Test
public void test100PutProductNodes() throws IOException {
    for (int i = 0; i < PRODUCT_NUMBER; i++) {
        GraphNode node = new GraphNode();
        node.properties = new HashMap<String, Object>();
        node.properties.put("type", "product");
        node.properties.put("name", "product" + i);
        HttpResponse response = Request.Post(BASE_URL + '/' + TEST_BASE + "/node/p" + i)
                .bodyString(JsonMapper.MAPPER.writeValueAsString(node), ContentType.APPLICATION_JSON)
                .connectTimeout(60000).socketTimeout(60000).execute().returnResponse();
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    }/*from   www  .  j  ava2 s  .c om*/
}

From source file:org.elasticsearch.test.NativeRealmIntegTestCase.java

public void setupReservedPasswords(RestClient restClient) throws IOException {
    logger.info("setting up reserved passwords for test");
    {//from   ww  w .j  a  v a  2  s .  co m
        String payload = "{\"password\": \"" + new String(reservedPassword.getChars()) + "\"}";
        HttpEntity entity = new NStringEntity(payload, ContentType.APPLICATION_JSON);
        BasicHeader authHeader = new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
                UsernamePasswordToken.basicAuthHeaderValue(ElasticUser.NAME, BOOTSTRAP_PASSWORD));
        String route = "/_xpack/security/user/elastic/_password";
        Response response = restClient.performRequest("PUT", route, Collections.emptyMap(), entity, authHeader);
        assertEquals(response.getStatusLine().getReasonPhrase(), 200, response.getStatusLine().getStatusCode());
    }

    for (String username : Arrays.asList(KibanaUser.NAME, LogstashSystemUser.NAME, BeatsSystemUser.NAME)) {
        String payload = "{\"password\": \"" + new String(reservedPassword.getChars()) + "\"}";
        HttpEntity entity = new NStringEntity(payload, ContentType.APPLICATION_JSON);
        BasicHeader authHeader = new BasicHeader(UsernamePasswordToken.BASIC_AUTH_HEADER,
                UsernamePasswordToken.basicAuthHeaderValue(ElasticUser.NAME, reservedPassword));
        String route = "/_xpack/security/user/" + username + "/_password";
        Response response = restClient.performRequest("PUT", route, Collections.emptyMap(), entity, authHeader);
        assertEquals(response.getStatusLine().getReasonPhrase(), 200, response.getStatusLine().getStatusCode());
    }
    logger.info("setting up reserved passwords finished");
}

From source file:org.elasticsearch.client.StoredScriptsIT.java

public void testGetStoredScript() throws Exception {
    final StoredScriptSource scriptSource = new StoredScriptSource("painless",
            "Math.log(_score * 2) + params.my_modifier",
            Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()));

    final String script = Strings.toString(scriptSource.toXContent(jsonBuilder(), ToXContent.EMPTY_PARAMS));
    // TODO: change to HighLevel PutStoredScriptRequest when it will be ready
    // so far - using low-level REST API
    Response putResponse = adminClient().performRequest("PUT", "/_scripts/calculate-score", emptyMap(),
            new StringEntity("{\"script\":" + script + "}", ContentType.APPLICATION_JSON));
    assertEquals(putResponse.getStatusLine().getReasonPhrase(), 200,
            putResponse.getStatusLine().getStatusCode());
    assertEquals("{\"acknowledged\":true}", EntityUtils.toString(putResponse.getEntity()));

    GetStoredScriptRequest getRequest = new GetStoredScriptRequest("calculate-score");
    getRequest.masterNodeTimeout("50s");

    GetStoredScriptResponse getResponse = execute(getRequest, highLevelClient()::getScript,
            highLevelClient()::getScriptAsync);

    assertThat(getResponse.getSource(), equalTo(scriptSource));
}

From source file:com.mashape.galileo.agent.network.AnalyticsBatchRequest.java

private void send(List<ALF> alfs)
        throws IllegalStateException, IOException, InterruptedException, ExecutionException, TimeoutException {
    String data = config.getGson().toJson(alfs);
    LOGGER.debug(String.format("sending batch of (%d) ALFs", alfs.size()));
    HttpPost post = new HttpPost(config.getAnalyticsServerURI());
    post.addHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
    post.setEntity(new StringEntity(data, "UTF-8"));
    HttpRequestFutureTask<Boolean> futureTask = config.getFutureRequestExecutor().execute(post, null,
            new AnalyticsResponseHandler(), new AnalyticsResponseCallback());
    post.releaseConnection();//from  w  w  w.j av  a  2s  .c o m
}

From source file:com.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   www.j av a2  s.co  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("preview", getPreviewImage(check));

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

    if (StringUtils.isNotBlank(seyrenConfig.getHttpNotificationUrl())) {
        post = new HttpPost(seyrenConfig.getHttpNotificationUrl());
    } else {
        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.enitalk.controllers.youtube.BotAware.java

public JsonNode getBotCommandsByTag(JsonNode dest, String tag) throws IOException, ExecutionException {
    String auth = botAuth();/*from w w w . j a  va 2 s .  c  om*/
    ObjectNode j = jackson.createObjectNode();
    j.set("dest", dest);
    j.put("tag", tag);

    String tagResponse = Request.Post(env.getProperty("bot.commands.by.tag"))
            .addHeader("Authorization", "Bearer " + auth).bodyString(j.toString(), ContentType.APPLICATION_JSON)
            .socketTimeout(20000).connectTimeout(5000).execute().returnContent().asString();

    logger.info("Command by tag find response {}", tagResponse);
    return jackson.readTree(tagResponse);
}