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.linkedin.pinot.common.utils.FileUploadUtils.java

public static int sendSegmentJson(final String host, final String port, final JSONObject segmentJson) {
    PostMethod postMethod = null;//from  ww w  .jav  a2s  . c o  m
    try {
        RequestEntity requestEntity = new StringRequestEntity(segmentJson.toString(),
                ContentType.APPLICATION_JSON.getMimeType(), ContentType.APPLICATION_JSON.getCharset().name());
        postMethod = new PostMethod("http://" + host + ":" + port + "/" + SEGMENTS_PATH);
        postMethod.setRequestEntity(requestEntity);
        postMethod.setRequestHeader(UPLOAD_TYPE, FileUploadType.JSON.toString());
        int statusCode = FILE_UPLOAD_HTTP_CLIENT.executeMethod(postMethod);
        if (statusCode >= 400) {
            String errorString = "POST Status Code: " + statusCode + "\n";
            if (postMethod.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + postMethod.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return statusCode;
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending json: {}", segmentJson.toString(), e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}

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

/**
 * This method updates a lead in salesforce.com and returns a success message with updated lead id.
 * This method gets input from a MAP(contains json data) and returns a MAp.
 * @param outMap //from  w ww.jav a2 s . c om
 */
private Map<String, String> update() {

    Map<String, String> outMap = new HashMap<>();
    final String SALESFORCE_UPDATE_LEAD_URL = args.get(INSTANCE_URL) + SALESFORCE_LEAD_URL + args.get(ID);

    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_COMPANY, args.get(COMPANY));
    userAttrMap.put(S_LASTNAME, args.get(LASTNAME));

    TransportTools tst = new TransportTools(SALESFORCE_UPDATE_LEAD_URL, null, header);
    Gson obj = new GsonBuilder().setPrettyPrinting().create();
    tst.setContentType(ContentType.APPLICATION_JSON, obj.toJson(userAttrMap));
    try {
        TransportMachinery.patch(tst);
        outMap.put(OUTPUT, UPDATE_STRING + args.get(ID));

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

From source file:com.effektif.adapter.service.AbstractAdapterService.java

@Override
public List<ItemReference> findItems(String adapterId, FindItemsRequest findItemsRequest) {
    List<ItemReference> items = null;
    Adapter adapter = getAdapter(adapterId);
    if (adapter != null) {
        try {/*from   w w w .  j a v a 2s. com*/
            CloseableHttpClient httpClient = HttpClients.createDefault();

            HttpPost request = new HttpPost(adapter.url + "/items");
            String requestEntityJsonString = jsonMapper.write(findItemsRequest);
            request.setEntity(new StringEntity(requestEntityJsonString, ContentType.APPLICATION_JSON));
            CloseableHttpResponse response = httpClient.execute(request);

            AdapterStatus adapterStatus = null;
            int status = response.getStatusLine().getStatusCode();
            if (200 != status) {
                log.error("findItems of adapter " + adapterId + " failed with http response code "
                        + response.getStatusLine().toString());
                adapterStatus = AdapterStatus.ERROR;
            }

            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                try {
                    InputStream inputStream = httpEntity.getContent();
                    InputStreamReader reader = new InputStreamReader(inputStream);
                    items = jsonMapper.read(reader, new GenericType(List.class, ItemReference.class));
                    log.debug("Parsed adapter data source find items");
                } catch (Exception e) {
                    log.error("Problem while parsing the adapter activity execute response: " + e.getMessage(),
                            e);
                }
            }

            //        AdapterLog adapterLog = new AdapterLog(executeRequest, executeResponse);
            //        updateAdapterExecution(adapterStatus, adapterLog);

        } catch (IOException e) {
            log.error("Problem while connecting to adapter: " + e.getMessage(), e);
        }
    }
    return items;
}

From source file:org.biokoframework.system.services.push.impl.SendPushCommand.java

private void sendBroadcastPush(String message, boolean production) throws NotificationFailureException {
    try {/*from  ww  w. jav  a  2s. c o  m*/

        Fields fields = new Fields();
        fields.put(AbstractPushNotificationService.APP_TOKEN, fAppToken);
        fields.put(AbstractPushNotificationService.APP_SECRET, fAppSecret);
        fields.put(AbstractPushNotificationService.MESSAGE, message);
        fields.put(IPushNotificationService.PRODUCTION, production);

        HttpClient client = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(fPusherdrilloUrl + AbstractPushNotificationService.SEND_BROADCAST_MESSAGE);
        post.setEntity(new StringEntity(fields.toJSONString(), ContentType.APPLICATION_JSON));

        post.completed();

        HttpResponse response = client.execute(post);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new NotificationFailureException(EntityUtils.toString(response.getEntity()));
        }

    } catch (NotificationFailureException exception) {
        throw exception;
    } catch (Exception exception) {
        throw new NotificationFailureException(exception);
    }
}

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

/**
 * {@inheritDoc}//from w  w w. ja va2 s.c om
 */
@Override
final public JsonNode execute(Request request, Object bodyObject, Integer msTimeOut, int... expectedCodes)
        throws IOException {
    if (logger.isDebugEnabled())
        logger.debug(request.toString());
    if (msTimeOut == null)
        msTimeOut = this.timeout;
    request = setBodyString(request, bodyObject);
    return executor
            .execute(request.connectTimeout(msTimeOut).socketTimeout(msTimeOut).addHeader("accept",
                    ContentType.APPLICATION_JSON.toString()))
            .handleResponse(
                    new JsonHttpResponseHandler.JsonTreeResponse(ContentType.APPLICATION_JSON, expectedCodes));
}

From source file:com.omertron.bgg.tools.HttpTools.java

/**
 * POST content to the URL with the specified body
 *
 * @param url URL to use in the request/*from  w ww.j av a  2  s  .  c  o m*/
 * @param jsonBody Body to use in the request
 * @return String content
 * @throws BggException Custom exception containing failure code
 */
public String postRequest(final URL url, final String jsonBody) throws BggException {
    try {
        HttpPost httpPost = new HttpPost(url.toURI());
        httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
        httpPost.addHeader(HttpHeaders.ACCEPT, APPLICATION_JSON);
        StringEntity params = new StringEntity(jsonBody, ContentType.APPLICATION_JSON);
        httpPost.setEntity(params);

        return validateResponse(DigestedResponseReader.postContent(httpClient, httpPost, CHARSET), url);
    } catch (URISyntaxException | IOException ex) {
        throw new BggException(ApiExceptionType.CONNECTION_ERROR, null, url, ex);
    }
}

From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.swift.SwiftToken.java

private DownloadItem keystoneRequest(HttpDownloader httpDownloader, String authUrl, String username,
        String tenantName, String password) throws JSONException, URISyntaxException, ClientProtocolException,
        UnsupportedEncodingException, IOException, IllegalStateException, SearchLibException {
    JSONObject jsonPasswordCredentials = new JSONObject();
    jsonPasswordCredentials.put("username", username);
    jsonPasswordCredentials.put("password", password);
    JSONObject jsonAuth = new JSONObject();
    jsonAuth.put("passwordCredentials", jsonPasswordCredentials);
    jsonAuth.put("tenantName", tenantName);
    JSONObject json = new JSONObject();
    json.put("auth", jsonAuth);
    URI uri = new URI(authUrl + "/tokens");
    List<Header> headers = new ArrayList<Header>(1);
    headers.add(new BasicHeader("Accept", "application/json"));
    return httpDownloader.post(uri, null, headers, null,
            new StringEntity(json.toString(), ContentType.APPLICATION_JSON));
}

From source file:monasca.persister.repository.influxdb.InfluxV9RepoWriter.java

protected int write(final InfluxPoint[] influxPointArry, String id) throws RepoException {

    HttpPost request = new HttpPost(this.influxUrl);

    request.addHeader("Content-Type", "application/json");
    request.addHeader("Authorization", this.baseAuthHeader);

    InfluxWrite influxWrite = new InfluxWrite(this.influxName, this.influxRetentionPolicy, influxPointArry,
            new HashMap<String, String>());

    String jsonBody = getJsonBody(influxWrite);

    if (this.gzip) {

        logger.debug("[{}]: gzip set to true. sending gzip msg", id);

        HttpEntity requestEntity = EntityBuilder.create().setText(jsonBody)
                .setContentType(ContentType.APPLICATION_JSON).setContentEncoding("UTF-8").gzipCompress()
                .build();/*ww w .j  a  v a 2s  .  co m*/

        request.setEntity(requestEntity);

        request.addHeader("Content-Encoding", "gzip");

    } else {

        logger.debug("[{}]: gzip set to false. sending non-gzip msg", id);

        StringEntity stringEntity = new StringEntity(jsonBody, "UTF-8");

        request.setEntity(stringEntity);

    }

    try {

        logger.debug("[{}]: sending {} points to influxdb {} at {}", id, influxPointArry.length,
                this.influxName, this.influxUrl);

        HttpResponse response = null;

        try {

            response = this.httpClient.execute(request);

        } catch (IOException e) {

            throw new RepoException("failed to execute http request", e);
        }

        int rc = response.getStatusLine().getStatusCode();

        if (rc != HttpStatus.SC_OK && rc != HttpStatus.SC_NO_CONTENT) {

            logger.error("[{}]: failed to send data to influxdb {} at {}: {}", id, this.influxName,
                    this.influxUrl, String.valueOf(rc));

            HttpEntity responseEntity = response.getEntity();

            String responseString = null;

            try {

                responseString = EntityUtils.toString(responseEntity, "UTF-8");

            } catch (IOException e) {

                throw new RepoException("failed to read http response for non ok return code " + rc, e);

            }

            logger.error("[{}]: http response: {}", id, responseString);

            throw new RepoException(
                    "failed to execute http request to influxdb " + rc + " - " + responseString);

        } else {

            logger.debug("[{}]: successfully sent {} points to influxdb {} at {}", id, influxPointArry.length,
                    this.influxName, this.influxUrl);

            return influxPointArry.length;

        }

    } finally {

        request.releaseConnection();

    }
}