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.easarrive.aws.client.cloudsearch.AmazonCloudSearchClient.java

/**
 * Execute a search and return result.//from w ww.  j  av a 2  s  . c om
 *
 * @param query search query to be executed.
 * @return result of the search.
 * @throws AmazonCloudSearchRequestException
 * @throws IllegalStateException
 * @throws AmazonCloudSearchInternalServerException
 */
public AmazonCloudSearchResult search(AmazonCloudSearchQuery query) throws IllegalStateException,
        AmazonCloudSearchRequestException, AmazonCloudSearchInternalServerException {
    if (this.getSearchEndpoint() == null || this.getSearchEndpoint().trim().length() < 1) {
        throw new AmazonCloudSearchRequestException("URI is null.");
    }
    AmazonCloudSearchResult result = null;
    String responseBody = null;
    try {
        Response response = Request
                .Get("https://" + this.getSearchEndpoint() + "/2013-01-01/search?" + query.build())
                .useExpectContinue().version(HttpVersion.HTTP_1_1)
                .addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType())
                .addHeader("Accept", ContentType.APPLICATION_JSON.getMimeType()).execute();

        HttpResponse resp = response.returnResponse();
        int statusCode = resp.getStatusLine().getStatusCode();
        int statusType = statusCode / 100;
        if (statusType == 4) {
            throw new AmazonCloudSearchRequestException(statusCode + "", responseBody);
        } else if (statusType == 5) {
            throw new AmazonCloudSearchInternalServerException(
                    "Internal Server Error. Please try again as this might be a transient error condition.");
        }

        responseBody = inputStreamToString(resp.getEntity().getContent());
        result = Jackson.fromJsonString(responseBody, AmazonCloudSearchResult.class);
    } catch (ClientProtocolException e) {
        throw new AmazonCloudSearchInternalServerException(e);
    } catch (IOException e) {
        throw new AmazonCloudSearchInternalServerException(e);
    } catch (Exception e) {
        throw new AmazonCloudSearchInternalServerException(e);
    }

    return result;
}

From source file:com.epam.reportportal.service.ReportPortalErrorHandlerTest.java

@Test(expected = GeneralReportPortalException.class)
public void handle_error_code() throws Exception {
    //  given://from  w  w  w .  j a  v  a2  s. co m
    LinkedListMultimap<String, String> invalidHeaders = LinkedListMultimap.create();
    invalidHeaders.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());

    Response<ByteSource> invalidResponse = createFakeResponse(500, invalidHeaders);

    //  when:
    reportPortalErrorHandler.handle(invalidResponse);
}

From source file:com.enitalk.controllers.youtube.BotAware.java

public void sendMessages(ArrayNode msg) throws IOException, ExecutionException {
    String auth = botAuth();// ww  w.  j  ava2  s  .  c  om
    String tagResponse = Request.Post(env.getProperty("bot.sendMessage"))
            .addHeader("Authorization", "Bearer " + auth)
            .bodyString(msg.toString(), ContentType.APPLICATION_JSON).socketTimeout(20000).connectTimeout(5000)
            .execute().returnContent().asString();

    logger.info("SendMsg sent to a bot {}, response {}", msg, tagResponse);
}

From source file:org.kitodo.data.index.elasticsearch.type.UserType.java

@SuppressWarnings("unchecked")
@Override//from   w w w  . jav  a 2s  .  c om
public HttpEntity createDocument(User user) {

    LinkedHashMap<String, String> orderedUserMap = new LinkedHashMap<>();
    orderedUserMap.put("name", user.getName());
    orderedUserMap.put("surname", user.getSurname());
    orderedUserMap.put("login", user.getLogin());
    orderedUserMap.put("ldapLogin", user.getLdapLogin());
    orderedUserMap.put("active", String.valueOf(user.isActive()));
    orderedUserMap.put("location", user.getLocation());
    orderedUserMap.put("metadataLanguage", user.getMetadataLanguage());
    String ldapGroup = user.getLdapGroup() != null ? user.getLdapGroup().getId().toString() : "null";
    orderedUserMap.put("ldapGroup", ldapGroup);

    JSONObject userObject = new JSONObject(orderedUserMap);

    JSONArray userGroups = new JSONArray();
    List<UserGroup> userUserGroups = user.getUserGroups();
    for (UserGroup userGroup : userUserGroups) {
        JSONObject userGroupObject = new JSONObject();
        userGroupObject.put("id", userGroup.getId().toString());
        userGroups.add(userGroupObject);
    }
    userObject.put("userGroups", userGroups);

    JSONArray properties = new JSONArray();
    List<UserProperty> userProperties = user.getProperties();
    for (UserProperty property : userProperties) {
        JSONObject propertyObject = new JSONObject();
        propertyObject.put("title", property.getTitle());
        propertyObject.put("value", property.getValue());
        properties.add(propertyObject);
    }
    userObject.put("properties", properties);

    return new NStringEntity(userObject.toJSONString(), ContentType.APPLICATION_JSON);
}

From source file:com.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry,
        String accessToken) throws IOException, UnsupportedRequestVerbException {

    if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) {
        throw new UnsupportedRequestVerbException();
    }//  w w  w  . jav a 2s . co  m
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request;

        switch (verb) {
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        default:
            throw new RuntimeException("RequestVerb not implemented: " + verb);
        }

        ((HttpEntityEnclosingRequestBase) request)
                .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));

        request.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, json, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String url = BASE_URL + method;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());
    conn.addRequestProperty("Content-Type", "application/json");

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(json.toString());
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, json, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:org.kitodo.data.index.elasticsearch.type.ProcessType.java

@SuppressWarnings("unchecked")
@Override/* w  ww .  j av  a2  s .  c  o m*/
public HttpEntity createDocument(Process process) {

    LinkedHashMap<String, String> orderedProcessMap = new LinkedHashMap<>();
    orderedProcessMap.put("name", process.getTitle());
    orderedProcessMap.put("outputName", process.getOutputName());
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String creationDate = process.getCreationDate() != null ? dateFormat.format(process.getCreationDate())
            : null;
    orderedProcessMap.put("creationDate", creationDate);
    orderedProcessMap.put("wikiField", process.getWikiField());
    String project = process.getProject() != null ? process.getProject().getId().toString() : "null";
    orderedProcessMap.put("project", project);
    String ruleset = process.getRuleset() != null ? process.getRuleset().getId().toString() : "null";
    orderedProcessMap.put("ruleset", ruleset);
    String ldapGroup = process.getDocket() != null ? process.getDocket().getId().toString() : "null";
    orderedProcessMap.put("ldapGroup", ldapGroup);

    JSONObject processObject = new JSONObject(orderedProcessMap);

    JSONArray properties = new JSONArray();
    List<ProcessProperty> processProperties = process.getProperties();
    for (ProcessProperty property : processProperties) {
        JSONObject propertyObject = new JSONObject();
        propertyObject.put("title", property.getTitle());
        propertyObject.put("value", property.getValue());
        properties.add(propertyObject);
    }
    processObject.put("properties", properties);

    return new NStringEntity(processObject.toJSONString(), ContentType.APPLICATION_JSON);
}

From source file:com.twosigma.beakerx.AutotranslationServiceImpl.java

@Override
public String update(String name, String json) {
    try {//from w  w  w.ja  v  a2  s. c  om
        String reply = Request.Post(LOCALHOST + this.context.getPort() + AUTOTRANSLTION)
                .addHeader(AUTHORIZATION, auth())
                .bodyString(createBody(name, json), ContentType.APPLICATION_JSON).execute().returnContent()
                .asString();
        if (!reply.equals("ok")) {
            throw new RuntimeException(reply);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return json;
}

From source file:com.nextdoor.bender.ipc.es.ElasticSearchTransporterTest.java

@Test
public void testOkResponse() throws TransportException, IOException {
    byte[] respPayload = "{\"errors\":false}".getBytes(StandardCharsets.UTF_8);
    byte[] payload = "foo".getBytes();

    HttpClient client = getMockClientWithResponse(respPayload, ContentType.APPLICATION_JSON, HttpStatus.SC_OK);
    ElasticSearchTransport transport = new ElasticSearchTransport(client, false);

    transport.sendBatch(payload);/*from   w w w  .  j  a  v  a 2 s.  co  m*/
}

From source file:org.talend.dataprep.api.service.command.preparation.PreparationGetContent.java

/**
 * @param id the preparation id.//w w w  . ja v  a  2  s  . c o  m
 * @param version the preparation version.
 * @param from where to read the data from.
 */
private PreparationGetContent(String id, String version, ExportParameters.SourceType from) {
    super(PREPARATION_GROUP);
    this.id = id;
    this.version = version;
    execute(() -> {
        try {
            ExportParameters parameters = new ExportParameters();
            parameters.setPreparationId(this.id);
            parameters.setStepId(this.version);
            parameters.setExportType("JSON");
            parameters.setFrom(from);

            final String parametersAsString = objectMapper.writerFor(ExportParameters.class)
                    .writeValueAsString(parameters);
            final HttpPost post = new HttpPost(transformationServiceUrl + "/apply");
            post.setEntity(new StringEntity(parametersAsString, ContentType.APPLICATION_JSON));
            return post;
        } catch (Exception e) {
            throw new TDPException(APIErrorCodes.UNABLE_TO_RETRIEVE_PREPARATION_CONTENT, e);
        }
    });
    on(HttpStatus.OK).then(pipeStream());
}