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.smoketest.SmokeTestWatcherWithSecurityIT.java

@Before
public void startWatcher() throws Exception {
    StringEntity entity = new StringEntity("{ \"value\" : \"15\" }", ContentType.APPLICATION_JSON);
    assertOK(adminClient().performRequest("PUT", "my_test_index/doc/1",
            Collections.singletonMap("refresh", "true"), entity));

    // delete the watcher history to not clutter with entries from other test
    adminClient().performRequest("DELETE", ".watcher-history-*", Collections.emptyMap());

    // create one document in this index, so we can test in the YAML tests, that the index cannot be accessed
    Response resp = adminClient().performRequest("PUT", "/index_not_allowed_to_read/doc/1",
            Collections.emptyMap(), new StringEntity("{\"foo\":\"bar\"}", ContentType.APPLICATION_JSON));
    assertThat(resp.getStatusLine().getStatusCode(), is(201));

    assertBusy(() -> {/*from   w  w w .ja  v  a 2s  . co  m*/
        try {
            Response statsResponse = adminClient().performRequest("GET", "_xpack/watcher/stats");
            ObjectPath objectPath = ObjectPath.createFromResponse(statsResponse);
            String state = objectPath.evaluate("stats.0.watcher_state");

            switch (state) {
            case "stopped":
                Response startResponse = adminClient().performRequest("POST", "_xpack/watcher/_start");
                assertOK(startResponse);
                String body = EntityUtils.toString(startResponse.getEntity());
                assertThat(body, containsString("\"acknowledged\":true"));
                break;
            case "stopping":
                throw new AssertionError("waiting until stopping state reached stopped state to start again");
            case "starting":
                throw new AssertionError("waiting until starting state reached started state");
            case "started":
                // all good here, we are done
                break;
            default:
                throw new AssertionError("unknown state[" + state + "]");
            }
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    });

    assertBusy(() -> {
        for (String template : WatcherIndexTemplateRegistryField.TEMPLATE_NAMES) {
            assertOK(adminClient().performRequest("HEAD", "_template/" + template));
        }
    });
}

From source file:biz.dfch.activiti.wrapper.service.ActivitiService.java

public void invokeProcess(ProcessMetadata processMetadata) {

    LOG.info("Sending request to start process at activity server '" + activitiUri + "'");

    try {/*ww  w .  ja  va2 s.  c o  m*/
        String response = Request.Post(getRequestUri()).setHeader("Authorization", createBasicAuth())
                .bodyString(objectMapper.writeValueAsString(createBody(processMetadata)),
                        ContentType.APPLICATION_JSON)
                .execute().returnContent().asString();
        LOG.info("Got response from activiti engine: " + objectMapper.writeValueAsString(response));
    } catch (IOException e) {
        throw new ActivityException("Exception occured while sending request to Activiti", e);
    }
}

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

/**
 * Used to create {@code zips} index and insert zip data in bulk.
 * @throws Exception when instance setup failed
 *///from   w w w .jav  a  2 s  .  c  om
@BeforeClass
public static void setupInstance() throws Exception {
    // hardcoded mapping definition
    final String mapping = String.format(Locale.ROOT,
            "{'mappings':{'%s':{'properties':"
                    + "{'city':{'type':'keyword'},'state':{'type':'keyword'},'pop':{'type':'long'}}" + "}}}",
            ZIPS).replace('\'', '"');

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

    // load records from file
    final List<String> bulk = new ArrayList<>();
    Resources.readLines(ElasticSearchAdapterTest.class.getResource("/zips-mini.json"), StandardCharsets.UTF_8,
            new LineProcessor<Void>() {
                @Override
                public boolean processLine(String line) throws IOException {
                    bulk.add("{\"index\": {} }"); // index/type will be derived from _bulk URI
                    line = line.replaceAll("_id", "id"); // _id is a reserved attribute in ES
                    bulk.add(line);
                    return true;
                }

                @Override
                public Void getResult() {
                    return null;
                }
            });

    if (bulk.isEmpty()) {
        throw new IllegalStateException("No records to index. Empty file ?");
    }

    final String uri = String.format(Locale.ROOT, "/%s/%s/_bulk?refresh", ZIPS, ZIPS);
    Response response = NODE.restClient().performRequest("POST", uri, Collections.emptyMap(),
            new StringEntity(String.join("\n", bulk) + "\n", ContentType.APPLICATION_JSON));

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        final String error = EntityUtils.toString(response.getEntity());
        final String message = String.format(Locale.ROOT,
                "Couldn't bulk insert %d elements into %s (%s/%s). Error was %s\n%s\n", bulk.size(), ZIPS,
                response.getHost(), response.getRequestLine(), response.getStatusLine(), error);

        throw new IllegalStateException(message);
    }

}

From source file:org.elasticsearch.client.sniff.ElasticsearchNodesSnifferParseTests.java

private void checkFile(String file, Node... expected) throws IOException {
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(file);
    if (in == null) {
        throw new IllegalArgumentException("Couldn't find [" + file + "]");
    }/* w w  w  . java2  s.c o  m*/
    try {
        HttpEntity entity = new InputStreamEntity(in, ContentType.APPLICATION_JSON);
        List<Node> nodes = ElasticsearchNodesSniffer.readHosts(entity, Scheme.HTTP, new JsonFactory());
        /*
         * Use these assertions because the error messages are nicer
         * than hasItems and we know the results are in order because
         * that is how we generated the file.
         */
        assertThat(nodes, hasSize(expected.length));
        for (int i = 0; i < expected.length; i++) {
            assertEquals(expected[i], nodes.get(i));
        }
    } finally {
        in.close();
    }
}

From source file:com.github.woki.payments.adyen.action.Endpoint.java

private static Request createPost(APService service, ClientConfig config, Object request) {
    Request retval = Post(config.getEndpointPort(service));
    // configure conn timeout
    retval.connectTimeout(config.getConnectionTimeout());
    // configure socket timeout
    retval.socketTimeout(config.getSocketTimeout());
    // add json//  w  ww .j  av  a2 s  . c  o  m
    retval.addHeader("Content-Type", "application/json");
    retval.addHeader("Accept", "application/json");
    for (Map.Entry<String, String> entry : config.getExtraParameters().entrySet()) {
        retval.addHeader(entry.getKey(), entry.getValue());
    }
    // add content
    String bodyString;
    try {
        bodyString = MAPPER.writeValueAsString(encrypt(config, request));
    } catch (Exception e) {
        throw new RuntimeException("CSE/JSON serialization error", e);
    }
    retval.bodyString(bodyString, ContentType.APPLICATION_JSON);
    if (config.hasProxy()) {
        retval.viaProxy(config.getProxyHost());
    }
    return retval;
}

From source file:org.surfnet.cruncher.integration.CruncherClientTestIntegration.java

@BeforeClass
public static void beforeClass() throws Exception {
    oauth2AuthServer = new LocalTestServer(null, null);
    oauth2AuthServer.start();/*from   w w  w.j  av a2s .c  o  m*/
    oauth2AuthServer.register("/oauth2/token", new HttpRequestHandler() {
        @Override
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            response.setEntity(new StringEntity(answer, ContentType.APPLICATION_JSON));
            response.setStatusCode(200);
        }

    });
    String apisOAuth2AuthorizationUrl = String.format("http://%s:%d/oauth2/token",
            oauth2AuthServer.getServiceAddress().getHostName(), oauth2AuthServer.getServiceAddress().getPort());
    cruncherClient = new CruncherClient(cruncherBaseLocation);
    ClientCredentialsClient oauthClient = new ClientCredentialsClient();
    oauthClient.setClientKey("key");
    oauthClient.setClientSecret("secret");
    oauthClient.setOauthAuthorizationUrl(apisOAuth2AuthorizationUrl);
    cruncherClient.setOauthClient(oauthClient);
}

From source file:org.elasticsearch.client.ResponseExceptionTests.java

public void testResponseException() throws IOException {
    ProtocolVersion protocolVersion = new ProtocolVersion("http", 1, 1);
    StatusLine statusLine = new BasicStatusLine(protocolVersion, 500, "Internal Server Error");
    HttpResponse httpResponse = new BasicHttpResponse(statusLine);

    String responseBody = "{\"error\":{\"root_cause\": {}}}";
    boolean hasBody = getRandom().nextBoolean();
    if (hasBody) {
        HttpEntity entity;/*  w  ww  . j a v a  2  s. co m*/
        if (getRandom().nextBoolean()) {
            entity = new StringEntity(responseBody, ContentType.APPLICATION_JSON);
        } else {
            //test a non repeatable entity
            entity = new InputStreamEntity(
                    new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8)),
                    ContentType.APPLICATION_JSON);
        }
        httpResponse.setEntity(entity);
    }

    RequestLine requestLine = new BasicRequestLine("GET", "/", protocolVersion);
    HttpHost httpHost = new HttpHost("localhost", 9200);
    Response response = new Response(requestLine, httpHost, httpResponse);
    ResponseException responseException = new ResponseException(response);

    assertSame(response, responseException.getResponse());
    if (hasBody) {
        assertEquals(responseBody, EntityUtils.toString(responseException.getResponse().getEntity()));
    } else {
        assertNull(responseException.getResponse().getEntity());
    }

    String message = response.getRequestLine().getMethod() + " " + response.getHost()
            + response.getRequestLine().getUri() + ": " + response.getStatusLine().toString();
    if (hasBody) {
        message += "\n" + responseBody;
    }
    assertEquals(message, responseException.getMessage());
}

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

@SuppressWarnings("unchecked")
@Override/*from   ww w  . jav  a2s  .  c o  m*/
public HttpEntity createDocument(Process process) {

    JSONObject processObject = new JSONObject();
    processObject.put("title", process.getTitle());
    processObject.put("outputName", process.getOutputName());
    String creationDate = process.getCreationDate() != null ? formatDate(process.getCreationDate()) : null;
    processObject.put("creationDate", creationDate);
    processObject.put("wikiField", process.getWikiField());
    processObject.put("sortHelperStatus", process.getSortHelperStatus());
    processObject.put("sortHelperImages", process.getSortHelperImages());
    processObject.put("processBaseUri", process.getProcessBaseUri());
    processObject.put("template", process.isTemplate());
    Integer project = process.getProject() != null ? process.getProject().getId() : null;
    processObject.put("project", project);
    Integer ruleset = process.getRuleset() != null ? process.getRuleset().getId() : null;
    processObject.put("ruleset", ruleset);
    Integer docket = process.getDocket() != null ? process.getDocket().getId() : null;
    processObject.put("docket", docket);
    processObject.put("batches", addObjectRelation(process.getBatches()));
    processObject.put("workpieces", addObjectRelation(process.getWorkpieces()));
    processObject.put("tasks", addObjectRelation(process.getTasks()));
    processObject.put("properties", addObjectRelation(process.getProperties()));

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

From source file:org.biokoframework.http.fields.impl.JsonFieldsParserTest.java

public void simpleParsing() throws Exception {
    JsonFieldsParser parser = new JsonFieldsParser();

    MockRequest request = new MockRequest("POST", "/something", "{\"some\":\"thing\",  \"and\": 3}");
    request.setContentType(ContentType.APPLICATION_JSON.toString());

    Fields expected = new Fields("some", "thing", "and", 3L);

    assertThat(parser.parse(request), is(equalTo(expected)));
}

From source file:fi.okm.mpass.shibboleth.profile.impl.AbstractRestResponseAction.java

/**
 * Push common REST/JSON settings to {@link HttpServletResponse}.
 *//*from   w  w  w  .j  a v  a  2s.  c o m*/
protected void pushHttpResponseProperties() {
    final HttpServletResponse httpResponse = getHttpServletResponse();
    HttpServletSupport.addNoCacheHeaders(httpResponse);
    HttpServletSupport.setUTF8Encoding(httpResponse);
    HttpServletSupport.setContentType(httpResponse, ContentType.APPLICATION_JSON.toString());
}