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:net.bis5.slack.command.gcal.SlashCommandApi.java

@RequestMapping(path = "/execute", method = RequestMethod.POST)
public ResponseEntity<String> execute(@ModelAttribute RequestPayload payload) {
    log.info("Request: " + payload.toString());

    EventRequest event = payload.createEvent();
    log.info("Parsed Request: " + event.toString());

    try {//from   w  w w . j  a v a 2 s .  c  om
        Event result = client.events().insert(config.getTargetCalendarId(), createEvent(event)).execute();
        log.info("Event Create Result: " + result.toString());

        ResponsePayload response = new ResponsePayload();
        Date date = toDate(event.getDate().atStartOfDay());
        Date start = toDate(LocalDateTime.of(event.getDate(), event.getFrom()));
        Date end = toDate(LocalDateTime.of(event.getDate(), event.getTo()));
        String user = payload.getUser_name();
        String title = event.getTitle();
        response.setText(String.format(
                "%s?????\n: %tY/%tm/%td\n: %tH:%tM\n: %tH:%tM\n??: %s", //
                user, date, date, date, start, start, end, end, title));

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            ObjectMapper mapper = new ObjectMapper();
            String responseBody = mapper.writeValueAsString(response);
            log.info("Response Payload: " + responseBody);
            Request.Post(payload.getResponse_url()).bodyString(responseBody, ContentType.APPLICATION_JSON)
                    .execute();
        }

        return ResponseEntity.ok(null);
    } catch (IOException ex) {
        log.error(ex.toString());
        return ResponseEntity.ok(ex.getMessage()); // OK??????????
    }
}

From source file:org.megam.deccanplato.provider.salesforce.crm.handler.ProductImpl.java

/**
 * this method creates an protuct in salesforce.com and returns that product id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap //from   w  w  w .  j  ava 2  s.  c  om
 */
private Map<String, String> create() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_CREATE_PRODUCT_URL = args.get(INSTANCE_URL) + SALESFORCE_PRODUCT_URL;

    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));
    Map<String, Object> userAttrMap = new HashMap<String, Object>();
    userAttrMap.put("Name", args.get(NAME));
    userAttrMap.put("ProductCode", args.get(PRODUCT_CODE));
    userAttrMap.put("Description", args.get(DESCRIPTION));

    TransportTools tst = new TransportTools(SALESFORCE_CREATE_PRODUCT_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    String responseBody = null;

    TransportResponse response = null;
    try {
        response = TransportMachinery.post(tst);
        responseBody = response.entityToString();

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    outMap.put(OUTPUT, responseBody);
    return outMap;
}

From source file:dataprocessing.elasticsearch.ElasticSearchClient.java

/** ***************************************************************
 * @param corpus Corpus line is from//from  w w  w  .j  a v a2s  . c  om
 * @param line Line number in corpus
 * @param text line text
 * Indexes line from corpus
 *
 * Mapping for chatbot/dialog:
 PUT chatbot
 {
     "mappings": {
         "dialog": {
             "properties": {
                 "corpus": {
                     "type": "string",
                             "index": "not_analyzed"
                 },
                 "file": {
                     "type": "string",
                             "index": "not_analyzed"
                 },
                 "line": {
                     "type": "long",
                             "index": "not_analyzed"
                 },
                 "text": {
                     "type": "string",
                             "index": "analyzed",
                             "analyzer": "english"
                 }
             }
         }
     }
 }
 */
public void indexDocument(String corpus, String file, int line, String text) {

    try {
        JSONObject entity = new JSONObject();
        entity.put("corpus", corpus);
        entity.put("file", file);
        entity.put("line", line);
        entity.put("text", text);

        // Post JSON entity
        client.performRequest("POST", String.format("/%s/%s/%s", index, type, corpus + "_" + file + "_" + line),
                Collections.emptyMap(), new NStringEntity(entity.toString(), ContentType.APPLICATION_JSON),
                header);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

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

    HttpClient client = getMockClientWithResponse(respPayload, ContentType.APPLICATION_JSON, HttpStatus.SC_OK,
            false);// w w  w  .ja va  2 s.co  m
    HttpTransport transport = new HttpTransport(client, "", false, 1, 1);

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

From source file:org.megam.deccanplato.provider.salesforce.chatter.handler.FeedImpl.java

/**
 * Comment post not working/*from   w  w w .  j  a va  2 s .  co m*/
 * @param outMap
 * @return
 */
private Map<String, String> postcomment() {

    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_CHATTER_URL = args.get(INSTANCE_URL) + "/services/data/v25.0/chatter/feed-items/"
            + args.get(ID) + "/comments?";
    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));
    Gson gson = new Gson();
    Map<String, Object> accountAttrMap = new HashMap<String, Object>();

    accountAttrMap.put(S_TEXT, gson.toJson(new Post(args.get(TYPE), args.get(TEXT))));

    TransportTools tst = new TransportTools(SALESFORCE_CHATTER_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(accountAttrMap));
    try {
        String response = TransportMachinery.post(tst).entityToString();
        outMap.put(OUTPUT, response);

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outMap;
}

From source file:org.sentilo.platform.server.test.request.SentiloRequestHandlerTest.java

@Test
public void handlerNotFound() {
    when(httpRequest.getRequestLine()).thenReturn(requestLine);
    when(requestLine.getMethod()).thenReturn("GET");
    when(requestLine.getUri()).thenReturn("http://lab.sentilo.io/data/mock");
    requestHandler.handle(httpRequest, httpResponse, httpContext);

    verify(httpResponse).setStatusCode(HttpStatus.SC_NOT_FOUND);
    verify(httpResponse).setHeader(HttpHeader.CONTENT_TYPE.toString(), ContentType.APPLICATION_JSON.toString());

}

From source file:org.megam.deccanplato.provider.salesforce.crm.handler.TaskImpl.java

/**
 * this method creates an task in salesforce.com and returns that task id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /*from ww  w . j ava  2 s.  c  o  m*/
 */
private Map<String, String> create() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_CREATE_PRODUCT_URL = args.get(INSTANCE_URL) + SALESFORCE_TASK_URL;

    Map<String, String> header = new HashMap<String, String>();
    header.put(S_AUTHORIZATION, S_OAUTH + args.get(ACCESS_TOKEN));

    Map<String, Object> userAttrMap = new HashMap<String, Object>();
    Date date = new Date();
    userAttrMap.put(S_SUBJECT, args.get(SUBJECT));
    userAttrMap.put(S_PRIORITY, args.get(PRIORITY));
    userAttrMap.put(S_STATUS, args.get(STATUS));

    TransportTools tst = new TransportTools(SALESFORCE_CREATE_PRODUCT_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    try {
        String response = TransportMachinery.post(tst).entityToString();
        outMap.put(OUTPUT, response);

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return outMap;
}

From source file:com.blacklocus.jres.http.HttpMethods.java

/**
 * @param method  http method, case-insensitive
 * @param url     destination of request
 * @param payload (optional) request body. An InputStream or String will be sent as is, while any other type will
 *                be serialized with {@link ObjectMappers#NORMAL} to JSON.
 * @return HttpUriRequest with header <code>Accept: application/json; charset=UTF-8</code>
 *///  w w w .  j  a va 2  s.  com
public static HttpUriRequest createRequest(String method, String url, final Object payload) {

    LOG.debug("{} {}", method, url);

    HttpUriRequest httpUriRequest = METHODS.get(method.toUpperCase()).newMethod(url);
    httpUriRequest.addHeader("Accept", ContentType.APPLICATION_JSON.toString());

    if (payload != null) {
        try {

            // This cast will except if a body is given for non-HttpEntityEnclosingRequest types. Deal with it later.
            ((HttpEntityEnclosingRequest) httpUriRequest).setEntity(createEntity(payload));

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

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

/**
 * Creates index in elastic search given mapping.
 *
 * @param index index of the index//from www  .java  2 s .  c  o m
 * @param mapping field and field type mapping
 * @throws IOException if there is an error
 */
void createIndex(String index, Map<String, String> mapping) throws IOException {
    Objects.requireNonNull(index, "index");
    Objects.requireNonNull(mapping, "mapping");

    ObjectNode json = mapper().createObjectNode();
    for (Map.Entry<String, String> entry : mapping.entrySet()) {
        json.set(entry.getKey(), json.objectNode().put("type", entry.getValue()));
    }

    json = (ObjectNode) json.objectNode().set("properties", json);
    json = (ObjectNode) json.objectNode().set(index, json);
    json = (ObjectNode) json.objectNode().set("mappings", json);

    // create index and mapping
    final HttpEntity entity = new StringEntity(mapper().writeValueAsString(json), ContentType.APPLICATION_JSON);
    restClient().performRequest("PUT", "/" + index, Collections.emptyMap(), entity);
}

From source file:com.ctrip.infosec.rule.resource.hystrix.DataProxyQueryCommand.java

@Override
protected Map<String, Object> run() throws Exception {

    DataProxyRequest request = new DataProxyRequest();
    request.setServiceName(serviceName);
    request.setOperationName(operationName);
    request.setParams(params);//  w ww.  j  av a  2s.  c om

    List<DataProxyRequest> requests = new ArrayList<>();
    requests.add(request);

    DataProxyResponse response = null;
    if (VENUS.equals(apiMode)) {
        DataProxyVenusService dataProxyVenusService = SpringContextHolder.getBean(DataProxyVenusService.class);
        List<DataProxyResponse> responses = dataProxyVenusService.dataproxyQueries(requests);
        if (responses == null || responses.size() < 1) {
            return null;
        }
        response = responses.get(0);
        if (response.getRtnCode() != 0) {
            logger.warn(Contexts.getLogPrefix() + "invoke DataProxy.queryForMap fault. RtnCode="
                    + response.getRtnCode() + ", RtnMessage=" + response.getMessage());
            return null;
        }
    } else {
        String responseTxt = Request.Post(urlPrefix + "/rest/dataproxy/query")
                .body(new StringEntity(JSON.toJSONString(request), ContentType.APPLICATION_JSON)).execute()
                .returnContent().asString();
        response = JSON.parseObject(responseTxt, DataProxyResponse.class);
    }

    if (response != null) {
        if (response.getRtnCode() == 0) {
            return response.getResult();
        } else {
            logger.warn(Contexts.getLogPrefix() + "DataProxy. RtnCode=" + response.getRtnCode()
                    + ", RtnMessage=" + response.getMessage());
        }
    }
    return Collections.EMPTY_MAP;
}