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.n52.youngs.test.SpatialSearchIT.java

@Test
public void spatialQueryEnvelopeSearch() throws Exception {
    String endpoint = "http://localhost:9200/" + mapping.getIndex() + "/" + mapping.getType()
            + "/_search?pretty";

    String bboxCoveringTwoRecordsQuery = "{" + "    \"query\":{" + "        \"filtered\":{"
            + "            \"query\":{" + "                \"match_all\":{" + "                }"
            + "            }," + "            \"filter\":{" + "                \"geo_shape\":{"
            + "                    \"location\":{" + "                        \"shape\":{"
            + "                            \"type\":\"envelope\","
            + "                            \"coordinates\":[" + "                                ["
            + "                                    52.0," + "                                    -5.0"
            + "                                ]," + "                                ["
            + "                                    40.0," + "                                    6.5"
            + "                                ]" + "                            ]"
            + "                        }" + "                    }" + "                }" + "            }"
            + "        }" + "    }" + "}";

    String searchWithEnvelopeResponse = Request.Post(endpoint)
            .bodyString(bboxCoveringTwoRecordsQuery, ContentType.APPLICATION_JSON).execute().returnContent()
            .asString();//ww  w .j av a 2 s  .  com
    assertThat("correct number of records found", searchWithEnvelopeResponse, hasJsonPath("hits.total", is(2)));
    assertThat("ids are contained", searchWithEnvelopeResponse,
            allOf(not(containsString("urn:uuid:1ef30a8b-876d-4828-9246-c37ab4510bbd")),
                    containsString("urn:uuid:9a669547-b69b-469f-a11f-2d875366bbdc"),
                    containsString("urn:uuid:94bc9c83-97f6-4b40-9eb8-a8e8787a5c63")));
}

From source file:tools.devnull.boteco.client.rest.impl.DefaultRestConfiguration.java

public ContentTypeSelector with(Object object) {
    return new ContentTypeSelector() {
        @Override//from  w  w  w  .jav  a2s.  com
        public RestConfiguration asJson() {
            return as(gsonBuilder.create().toJson(object), ContentType.APPLICATION_JSON);
        }

        @Override
        public RestConfiguration asPlainText() {
            return as(object.toString(), ContentType.TEXT_PLAIN);
        }

        @Override
        public RestConfiguration asFormUrlEncoded() {
            List<BasicNameValuePair> pairs;
            if (object instanceof Map) {
                pairs = ((Set<Map.Entry>) ((Map) object).entrySet()).stream().map(
                        entry -> new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()))
                        .collect(Collectors.toList());
            } else {
                pairs = elements().in(object).stream()
                        .map(el -> new BasicNameValuePair(el.name(), el.value().toString()))
                        .collect(Collectors.toList());
            }
            return setEntity(new UrlEncodedFormEntity(pairs, Charset.defaultCharset()));
        }

        private RestConfiguration as(String content, ContentType contentType) {
            return setEntity(new StringEntity(content, contentType));
        }

        private RestConfiguration setEntity(HttpEntity entity) {
            if (DefaultRestConfiguration.this.request instanceof HttpEntityEnclosingRequest) {
                ((HttpEntityEnclosingRequest) DefaultRestConfiguration.this.request).setEntity(entity);
            } else {
                throw new BotException("This request doesn't allow entities");
            }
            return DefaultRestConfiguration.this;
        }

    };
}

From source file:org.phenotips.security.authorization.remote.internal.RemoteAuthorizationModule.java

private byte remoteCheck(String right, String username, String internalId, String externalId) {
    HttpPost method = new HttpPost(this.remoteServiceURL);

    JSONObject payload = new JSONObject();
    payload.element("access", right);
    payload.element("username", username);
    payload.element("patient-id", internalId);
    payload.element("patient-eid", externalId);
    method.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
    CloseableHttpResponse response = null;
    try {/*from   w  ww  . j  ava2 s. c o m*/
        response = this.client.execute(method);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            cacheResponse(getCacheKey(username, right, internalId), Boolean.TRUE, response);
            return GRANTED;
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
            cacheResponse(getCacheKey(username, right, internalId), Boolean.FALSE, response);
            return DENIED;
        }
    } catch (IOException ex) {
        this.logger.warn("Failed to communicate with the authorization server: {}", ex.getMessage(), ex);
        return ERROR;
    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                // Just ignore, this shouldn't happen
            }
        }
    }
    return UNKNWON;
}

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

@Test
public void testHttpPostUrl() throws TransportException, IOException {
    byte[] respPayload = "{}".getBytes(StandardCharsets.UTF_8);
    byte[] payload = "foo".getBytes();
    String url = "https://localhost:443/foo";

    HttpClient client = getMockClientWithResponse(respPayload, ContentType.APPLICATION_JSON, HttpStatus.SC_OK,
            false);//w ww. j  a va 2 s .com
    HttpTransport transport = spy(new HttpTransport(client, url, false, 1, 1));
    transport.sendBatch(payload);

    ArgumentCaptor<HttpPost> captor = ArgumentCaptor.forClass(HttpPost.class);
    verify(client, times(1)).execute(captor.capture());

    assertEquals(url, captor.getValue().getURI().toString());
}

From source file:be.fedict.dcat.datagovbe.Drupal.java

/**
 * Prepare a POST or PUT action.//w ww. j a  va  2  s  . c  o m
 * 
 * @param method POST or PUT
 * @param relpath relative path
 * @return 
 */
private Request prepare(String method, String relpath) {
    String u = this.url.toString() + relpath;

    Request r = method.equals(Drupal.POST) ? Request.Post(u) : Request.Put(u);

    r.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()).setHeader(Drupal.X_TOKEN,
            token);

    if (proxy != null) {
        r.viaProxy(proxy);
    }
    return r;
}

From source file:org.elasticsearch.test.rest.yaml.ClientYamlTestClient.java

private static boolean sendBodyAsSourceParam(List<String> supportedMethods, String contentType) {
    if (supportedMethods.contains(HttpGet.METHOD_NAME)) {
        if (contentType.startsWith(ContentType.APPLICATION_JSON.getMimeType())
                || contentType.startsWith(YAML_CONTENT_TYPE.getMimeType())) {
            return RandomizedTest.rarely();
        }/*  ww w  .  j a  va 2 s  .  com*/
    }
    return false;
}

From source file:org.modeshape.jcr.index.elasticsearch.client.EsClient.java

/**
 * Deletes all documents./*from   ww w.j av  a 2 s  .c o m*/
 *
 * @param name index name
 * @param type index type.
 * @throws IOException
 */
public void deleteAll(String name, String type) throws IOException {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost method = new HttpPost(String.format("http://%s:%d/%s/%s", host, port, name, type));
    try {
        EsRequest query = new EsRequest();
        query.put("query", new MatchAllQuery().build());
        StringEntity requestEntity = new StringEntity(query.toString(), ContentType.APPLICATION_JSON);
        method.setEntity(requestEntity);
        method.setHeader(" X-HTTP-Method-Override", "DELETE");
        CloseableHttpResponse resp = client.execute(method);
        int status = resp.getStatusLine().getStatusCode();
        if (status != HttpStatus.SC_OK) {
            throw new IOException(resp.getStatusLine().getReasonPhrase());
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:ai.grakn.engine.controller.GraqlController.java

/**
 * Handle any {@link Exception} that are thrown by the server. Configures and returns
 * the correct JSON response with the given status.
 *
 * @param exception exception thrown by the server
 * @param response response to the client
 *//*from   ww w. j a v a 2  s .c o m*/
private static void handleError(int status, Exception exception, Response response) {
    LOG.error("REST error", exception);
    response.status(status);
    response.body(Json.object("exception", exception.getMessage()).toString());
    response.type(ContentType.APPLICATION_JSON.getMimeType());
}

From source file:org.elasticsearch.xpack.ml.integration.MlJobIT.java

private Response createFarequoteJob(String jobId) throws IOException {
    String job = "{\n" + "    \"description\":\"Analysis of response time by airline\",\n"
            + "    \"analysis_config\" : {\n" + "        \"bucket_span\": \"3600s\",\n"
            + "        \"detectors\" :[{\"function\":\"metric\",\"field_name\":\"responsetime\",\"by_field_name\":\"airline\"}]\n"
            + "    },\n" + "    \"data_description\" : {\n" + "        \"field_delimiter\":\",\",\n"
            + "        " + "\"time_field\":\"time\",\n" + "        \"time_format\":\"yyyy-MM-dd HH:mm:ssX\"\n"
            + "    }\n" + "}";

    return client().performRequest("put", MachineLearning.BASE_PATH + "anomaly_detectors/" + jobId,
            Collections.emptyMap(), new StringEntity(job, ContentType.APPLICATION_JSON));
}

From source file:org.phenotips.ontology.internal.GeneNomenclature.java

@Override
public Set<OntologyTerm> search(Map<String, ?> fieldValues, Map<String, String> queryOptions) {
    try {// w  w w .j  a v  a 2 s .  c  o  m
        HttpGet method = new HttpGet(
                searchServiceURL + URLEncoder.encode(generateQuery(fieldValues), Consts.UTF_8.name()));
        method.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType());
        try (CloseableHttpResponse httpResponse = this.client.execute(method)) {
            String response = IOUtils.toString(httpResponse.getEntity().getContent(), Consts.UTF_8);
            JSONObject responseJSON = (JSONObject) JSONSerializer.toJSON(response);
            JSONArray docs = responseJSON.getJSONObject(RESPONSE_KEY).getJSONArray(DATA_KEY);
            if (docs.size() >= 1) {
                Set<OntologyTerm> result = new LinkedHashSet<>();
                // The remote service doesn't offer any query control, manually select the right range
                int start = 0;
                if (queryOptions.containsKey(CommonParams.START)
                        && StringUtils.isNumeric(queryOptions.get(CommonParams.START))) {
                    start = Math.max(0, Integer.parseInt(queryOptions.get(CommonParams.START)));
                }
                int end = docs.size();
                if (queryOptions.containsKey(CommonParams.ROWS)
                        && StringUtils.isNumeric(queryOptions.get(CommonParams.ROWS))) {
                    end = Math.min(end, start + Integer.parseInt(queryOptions.get(CommonParams.ROWS)));
                }

                for (int i = start; i < end; ++i) {
                    result.add(new JSONOntologyTerm(docs.getJSONObject(i), this));
                }
                return result;
                // This is too slow, for the moment only return summaries
                // return getTerms(ids);
            }
        } catch (IOException ex) {
            this.logger.warn("Failed to search gene names: {}", ex.getMessage());
        }
    } catch (UnsupportedEncodingException ex) {
        // This will not happen, UTF-8 is always available
    }
    return Collections.emptySet();
}