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.elasticsearch.backwards.IndexingIT.java

private int indexDocs(String index, final int idStart, final int numDocs) throws IOException {
    for (int i = 0; i < numDocs; i++) {
        final int id = idStart + i;
        assertOK(client().performRequest("PUT", index + "/test/" + id, emptyMap(),
                new StringEntity("{\"test\": \"test_" + id + "\"}", ContentType.APPLICATION_JSON)));
    }//from  w w  w  .  j a  v  a2s  .  c o  m
    return numDocs;
}

From source file:org.elasticsearch.wildfly.WildflyIT.java

public void testTransportClient() throws URISyntaxException, IOException {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        final String str = String.format(Locale.ROOT,
                "http://localhost:38080/wildfly-%s%s/transport/employees/1", Version.CURRENT,
                Build.CURRENT.isSnapshot() ? "-SNAPSHOT" : "");
        final HttpPut put = new HttpPut(new URI(str));
        final String body;
        try (XContentBuilder builder = jsonBuilder()) {
            builder.startObject();// w  ww.ja va  2s  . c  o  m
            {
                builder.field("first_name", "John");
                builder.field("last_name", "Smith");
                builder.field("age", 25);
                builder.field("about", "I love to go rock climbing");
                builder.startArray("interests");
                {
                    builder.value("sports");
                    builder.value("music");
                }
                builder.endArray();
            }
            builder.endObject();
            body = builder.string();
        }
        put.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        try (CloseableHttpResponse response = client.execute(put)) {
            assertThat(response.getStatusLine().getStatusCode(), equalTo(201));
        }

        final HttpGet get = new HttpGet(new URI(str));
        try (CloseableHttpResponse response = client.execute(get);
                XContentParser parser = JsonXContent.jsonXContent.createParser(
                        new NamedXContentRegistry(ClusterModule.getNamedXWriteables()),
                        response.getEntity().getContent())) {
            final Map<String, Object> map = parser.map();
            assertThat(map.get("first_name"), equalTo("John"));
            assertThat(map.get("last_name"), equalTo("Smith"));
            assertThat(map.get("age"), equalTo(25));
            assertThat(map.get("about"), equalTo("I love to go rock climbing"));
            final Object interests = map.get("interests");
            assertThat(interests, instanceOf(List.class));
            @SuppressWarnings("unchecked")
            final List<String> interestsAsList = (List<String>) interests;
            assertThat(interestsAsList, containsInAnyOrder("sports", "music"));
        }
    }
}

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

/**
 * this method creates an case in salesforce.com and returns that case id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /*from   www .jav a2s . co  m*/
 */
private Map<String, String> create() {
    final String SALESFORCE_CREATE_CASE_URL = args.get(INSTANCE_URL) + SALESFORCE_CASE_URL;
    Map<String, String> outMap = new HashMap<>();
    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(S_SUBJECT, args.get(SUBJECT));
    userAttrMap.put(S_CONTACTID, args.get(CONTACT_ID));
    userAttrMap.put(S_ACCOUNTID, args.get(ACCOUNT_ID));

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

    try {
        String responseBody = TransportMachinery.post(tst).entityToString();
        outMap.put(OUTPUT, responseBody);

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

From source file:com.qwazr.utils.json.client.JsonClientAbstract.java

private Request setBodyString(Request request, Object bodyObject) throws JsonProcessingException {
    if (bodyObject == null)
        return request;
    if (bodyObject instanceof String)
        return request.bodyString(bodyObject.toString(), ContentType.TEXT_PLAIN);
    else if (bodyObject instanceof InputStream)
        return request.bodyStream((InputStream) bodyObject, ContentType.APPLICATION_OCTET_STREAM);
    else/*from  ww w.j  a  v  a2s  .  co m*/
        return request.bodyString(JsonMapper.MAPPER.writeValueAsString(bodyObject),
                ContentType.APPLICATION_JSON);
}

From source file:com.srotya.tau.ui.rules.RulesManager.java

public short saveRule(UserBean ub, Tenant tenant, Rule currRule) throws Exception {
    if (currRule == null || tenant == null) {
        logger.info("Rule was null can't save");
        return -1;
    }//  w w  w.  j  a v a 2s .c o  m
    RuleValidator.getInstance().validate(currRule);
    logger.info("Rule is valid attempting to save");
    CloseableHttpClient client = Utils.buildClient(am.getBaseUrl(), am.getConnectTimeout(),
            am.getRequestTimeout());
    HttpPut put = new HttpPut(
            am.getBaseUrl() + RULES_URL + "/" + tenant.getTenantId() + "/" + currRule.getRuleId());
    if (am.isEnableAuth()) {
        put.addHeader(BapiLoginDAO.X_SUBJECT_TOKEN, ub.getToken());
        put.addHeader(BapiLoginDAO.HMAC, ub.getHmac());
    }
    StringEntity entity = new StringEntity(RuleSerializer.serializeRuleToJSONString(currRule, false),
            ContentType.APPLICATION_JSON);
    put.setEntity(entity);
    CloseableHttpResponse resp = client.execute(put);
    String result = EntityUtils.toString(resp.getEntity());
    return Short.parseShort(result);
}

From source file:com.oneops.antenna.senders.generic.HTTPMsgService.java

/**
 * Posts the message to http endpoint//from  ww w  .  j a v  a  2s . co  m
 *
 * @param msg the notification message
 * @param sub URL subscriber
 * @return <code>true</code> if response code is 200, else return <code>false</code>
 */
@Override
public boolean postMessage(NotificationMessage msg, BasicSubscriber sub) {
    URLSubscriber urlSub = (URLSubscriber) sub;
    boolean isHpom = urlSub.hasHpomXfmr();

    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost req = new HttpPost(urlSub.getUrl());
    req.setEntity(new StringEntity(gson.toJson(msg), ContentType.APPLICATION_JSON));

    int timeout = urlSub.getTimeout();
    req.setConfig(RequestConfig.custom().setSocketTimeout(timeout > 0 ? timeout : 2000).build());
    String userName = urlSub.getUserName();
    if (userName != null && StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(urlSub.getPassword())) {
        String auth = userName + ":" + urlSub.getPassword();
        req.addHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.encodeBase64(auth.getBytes())));
    }

    try (CloseableHttpResponse res = httpClient.execute(req)) {
        if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            countOK(isHpom);
            return true;
        } else {
            logger.warn(isHpom ? "HPOM"
                    : "HTTP" + " message post response code: " + res.getStatusLine().getStatusCode()
                            + " for URL sink: " + urlSub.getName());
        }
    } catch (IOException ex) {
        logger.error(isHpom ? "HPOM" : "HTTP" + " message post failed." + ex.getMessage());
    }

    countErr(isHpom);
    return false;
}

From source file:org.skfiy.typhon.rnsd.service.handler.AppleRechargingHandler.java

@Override
public RechargingBO handle(JSONObject json) throws TradeValidatedException {
    String uri;/*from www  .  ja v a  2s . c o  m*/
    if ("Sandbox".equalsIgnoreCase(json.getString("environment"))) {
        uri = SANDBOX_URL;
    } else {
        uri = VERIFY_URL;
    }

    CloseableHttpClient hc = HC_BUILDER.build();
    HttpPost post = new HttpPost(uri);

    List<NameValuePair> nvps = new ArrayList<>();

    String receiptStr = json.getString("data");
    Matcher m = P.matcher(receiptStr);
    m.find();

    String signature = m.group(2).replaceAll(" ", "+");
    receiptStr = receiptStr.replace(m.group(2), signature);

    String receiptData = org.skfiy.typhon.rnsd.Base64.encodeBytes(receiptStr.getBytes());
    JSONObject receiptJson = new JSONObject();
    receiptJson.put("receipt-data", receiptData);

    try {

        post.setEntity(new StringEntity(receiptJson.toJSONString(), ContentType.APPLICATION_JSON));
        CloseableHttpResponse resp = hc.execute(post);

        String str = EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
        JSONObject result = JSON.parseObject(str);

        if (result.getIntValue("status") != 0) {
            throw new TradeValidatedException("success", "no verify");
        }

        JSONObject receipt = result.getJSONObject("receipt");

        // result
        Recharging recharging = new Recharging();
        recharging.setTradeId(receipt.getString("transaction_id"));
        recharging.setPlatform(Platform.apple.getLabel());

        String callbackInfo = StringUtils.newStringUtf8(Base64.decodeBase64(json.getString("callbackInfo")));
        JSONObject extra = JSON.parseObject(callbackInfo);

        recharging.setUid(extra.getString("uid"));
        recharging.setRegion(extra.getString("region"));
        recharging.setGoods(extra.getString("goods"));

        LOG.debug("{}", extra);

        recharging.setAmount(extra.getInteger("goods"));
        recharging.setCreationTime(System.currentTimeMillis() / 1000);
        recharging.setChannel(Platform.apple.getLabel());

        return (new RechargingBO(recharging, "success"));
    } catch (Exception ex) {
        throw new TradeValidatedException("success", ex.getMessage());
    } finally {
        try {
            hc.close();
        } catch (IOException ex) {
        }
    }
}

From source file:com.flipkart.flux.client.runtime.FluxRuntimeConnectorHttpImpl.java

private CloseableHttpResponse postOverHttp(Object dataToPost, String pathSuffix) {
    CloseableHttpResponse httpResponse = null;
    HttpPost httpPostRequest;/* w w  w.ja  v a2s .  com*/
    httpPostRequest = new HttpPost(fluxEndpoint + pathSuffix);
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {
        objectMapper.writeValue(byteArrayOutputStream, dataToPost);
        httpPostRequest.setEntity(
                new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.APPLICATION_JSON));
        httpResponse = closeableHttpClient.execute(httpPostRequest);
        final int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode >= Response.Status.OK.getStatusCode()
                && statusCode < Response.Status.MOVED_PERMANENTLY.getStatusCode()) {
            // all is well, TODO write a trace level log
        } else {
            // TODO: log status line here
            throw new RuntimeCommunicationException("Did not receive a valid response from Flux core");
        }
    } catch (IOException e) {
        // TODO log exception here
        e.printStackTrace();
        throw new RuntimeCommunicationException("Could not communicate with Flux runtime");
    }
    return httpResponse;
}

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

/**
 * this method creates an contact in salesforce.com and returns that contact id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap /*from   w  w w. ja  va 2 s .co m*/
 */
private Map<String, String> create() {
    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_CREATE_CONTACT_URL = args.get(INSTANCE_URL) + SALESFORCE_CONTACT_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(S_LASTNAME, args.get(LASTNAME));

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

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

From source file:org.craftercms.studio.impl.v1.deployment.PreviewDeployerImpl.java

@EventListener(EVENT_PREVIEW_SYNC)
public void onPreviewSync(PreviewEventContext context) {
    String site = context.getSite();
    String requestUrl = getDeployTargetUrl(site);
    HttpPost postRequest = new HttpPost(requestUrl);

    if (context.isWaitTillDeploymentIsDone()) {
        String requestBody = getDeployTargetRequestBody(true);
        HttpEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
        postRequest.setEntity(requestEntity);
    }//  ww  w  .  ja v  a 2  s  . c  o m

    // TODO: DB: add all required params to post method
    try {
        CloseableHttpResponse response = httpClient.execute(postRequest);
        HttpStatus httpStatus = HttpStatus.valueOf(response.getStatusLine().getStatusCode());
        if (!httpStatus.is2xxSuccessful()) {
            logger.error("Preview sync request for site " + site + " returned status " + httpStatus + " ("
                    + httpStatus.getReasonPhrase() + ")");
        }
    } catch (IOException e) {
        logger.error("Error while sending preview sync request for site " + site, e);
    } finally {
        postRequest.releaseConnection();
    }
}