APISonar


org.elasticsearch.common.xcontent.XContentType.JSON

> org > elasticsearch > common > xcontent > XContentType > JSON
org APIs elasticsearch APIs common APIs xcontent APIs XContentType APIs JSON APIs

Example 1
public void testEmptyPipeline() throws IOException {
        final String json = Strings.toString(MonitoringTemplateUtils.emptyPipeline(XContentType.JSON));

        // ensure the description contains the API version
        assertThat(json, containsString("Monitoring API version " + MonitoringTemplateUtils.TEMPLATE_VERSION));
        assertThat(json, containsString("\"processors\":[]"));
        assertThat(json, containsString("\"version\":" + LAST_UPDATED_VERSION));
    }
Example 2
private String compileParams(XContentType contentType) {
        if (contentType == XContentType.JSON) {
            return "application/json";
        } else {
            return "text/plain";
        }
    }
Example 3
private RoleMapperExpression parse(String json) throws IOException {
        return new ExpressionParser().parse("rules", new XContentSource(new BytesArray(json),
                XContentType.JSON));
    }
Example 4
public void testPreventCreateTimeInjection() throws IOException {
        String json = "{"
            + " \"create_time\" : 123456789 },"
            + " \"source\" : {\"index\":\"src\"},"
            + " \"dest\" : {\"index\": \"dest\"},"
            + "}";

        try (XContentParser parser =
                 XContentFactory.xContent(XContentType.JSON).createParser(
                     xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json)) {
            Exception e = expectThrows(IllegalArgumentException.class, () -> DataFrameAnalyticsConfig.STRICT_PARSER.apply(parser, null));
            assertThat(e.getMessage(), containsString("unknown field [create_time], parser not found"));
        }
    }
Example 5
private void indexTest(String projectUuid, String fileUuid, String testName, String uuid) throws IOException {
    String json = IOUtils.toString(getClass().getResource(format("%s/%s_%s_%s.json", getClass().getSimpleName(), projectUuid, fileUuid, testName)));
    es.client().prepareIndex(INDEX_TYPE_TEST)
      .setId(uuid)
      .setRouting(projectUuid)
      .setSource(json, XContentType.JSON)
      .setRefreshPolicy(REFRESH_IMMEDIATE)
      .get();
  }
Example 6
public void indexSingle(String index, String id, String json) throws IOException {
        IndexRequest request = new IndexRequest(index, getDefaultTypeName(), id);
        request.source(json, XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }
Example 7
public void testUseOfFieldLevelSecurityThrowsException() throws Exception {
        String json = "{ \"index\":[ "
                + "{"
                + " \"names\": [ \"employees\" ], "
                + " \"privileges\" : [ \"read\", \"write\" ] ,"
                + " \"field_security\": { \"grant\": [ \"name\", \"department\", \"title\" ] }"
                + "} ] }";

        final HasPrivilegesRequestBuilder builder = new HasPrivilegesRequestBuilder(mock(Client.class));
        final ElasticsearchParseException parseException = expectThrows(ElasticsearchParseException.class,
                () -> builder.source("elastic", new BytesArray(json.getBytes(StandardCharsets.UTF_8)), XContentType.JSON)
        );
        assertThat(parseException.getMessage(), containsString("[field_security]"));
    }
Example 8
private Tuple<String, String> monitoringPipeline(final String pipelineId) {
        final XContentType json = XContentType.JSON;

        return new Tuple<>(MonitoringTemplateUtils.pipelineName(pipelineId),
                Strings.toString(MonitoringTemplateUtils.loadPipeline(pipelineId, json)));
    }
Example 9
public void testBulkAllowExplicitIndex() throws Exception {
        String bulkAction1 = copyToStringFromClasspath("/org/elasticsearch/action/bulk/simple-bulk.json");
        Exception ex = expectThrows(Exception.class,
            () -> new BulkRequest().add(
                new BytesArray(bulkAction1.getBytes(StandardCharsets.UTF_8)), null, false, XContentType.JSON));
        assertEquals("explicit index in bulk is not allowed", ex.getMessage());

        String bulkAction = copyToStringFromClasspath("/org/elasticsearch/action/bulk/simple-bulk5.json");
        new BulkRequest().add(new BytesArray(bulkAction.getBytes(StandardCharsets.UTF_8)), "test", false, XContentType.JSON);
    }
Example 10
protected Map<String, Object> toLazy(ToXContent parsedObject) throws Exception {
        BytesReference bytes = XContentHelper.toXContent(parsedObject, XContentType.JSON, false);
        try(XContentParser parser = XContentHelper.createParser(xContentRegistry(),
            DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
            bytes,
            XContentType.JSON)) {
            return parser.mapOrdered();
        }
    }
Example 11
public void testInvalidEmail() throws IOException {
        final String json = "{\n" +
                "    \"roles\": [\n" +
                "      \"kibana4\"\n" +
                "    ],\n" +
                "    \"full_name\": \"Kibana User\",\n" +
                "    \"email\": [ \"kibana@elastic.co\" ],\n" +
                "    \"metadata\": {}\n" +
                "}";

        PutUserRequestBuilder builder = new PutUserRequestBuilder(mock(Client.class));
        ElasticsearchParseException e = expectThrows(ElasticsearchParseException.class,
            () -> builder.source("kibana4", new BytesArray(json.getBytes(StandardCharsets.UTF_8)), XContentType.JSON, Hasher.BCRYPT));
        assertThat(e.getMessage(), containsString("expected field [email] to be of type string"));
    }
Example 12
private Object[][] parse(String bulk_args) throws Exception {
        SQLRequestParseContext context = new SQLRequestParseContext();
        String json = "{\"bulk_args\":" + bulk_args + "}";
        XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(
            xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json);
        parser.nextToken();
        parser.nextToken();
        parser.nextToken();
        SQLBulkArgsParseElement bulkArgsParseElement = new SQLBulkArgsParseElement();
        bulkArgsParseElement.parse(parser, context);
        return context.bulkArgs();

    }
Example 13
private void createTestIndex(String indexName) throws Exception {
        assertAcked(client().admin().indices().prepareCreate(indexName).get());
        indexRandom(true,
                client().prepareIndex(indexName, "doc", "1").setSource("{\"foo\":\"bar1-1\"}", XContentType.JSON),
                client().prepareIndex(indexName, "doc", "2").setSource("{\"foo\":\"baz1-1\"}", XContentType.JSON)
        );
        ensureYellow(indexName);
    }
Example 14
public void testParseModelMemoryLimitGivenLessThanOneMBString() throws IOException {
        String json = "{\"model_memory_limit\":\"1000Kb\"}";
        XContentParser parser = XContentFactory.xContent(XContentType.JSON)
                .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json);
        XContentParseException e = expectThrows(XContentParseException.class, () -> AnalysisLimits.STRICT_PARSER.apply(parser, null));
        assertThat(ExceptionsHelper.detailedMessage(e), containsString("model_memory_limit must be at least 1 MiB. Value = 0"));
    }
Example 15
public void testDeleteWithWhere() throws Exception {
        String fqn = getFqn("test");
        createIndex(fqn);
        ensureYellow();
        client().prepareIndex(fqn, "default", "id1").setSource("{}", XContentType.JSON).execute().actionGet();
        client().prepareIndex(fqn, "default", "id2").setSource("{}", XContentType.JSON).execute().actionGet();
        client().prepareIndex(fqn, "default", "id3").setSource("{}", XContentType.JSON).execute().actionGet();
        refresh();
        execute("delete from test where \"_id\" = 'id1'");
        assertEquals(1, response.rowCount());
        refresh();
        execute("select \"_id\" from test");
        assertEquals(2, response.rowCount());
    }
Example 16
public static Map<String, Object> responseToData(ToXContentObject response, ToXContent.Params params) throws IOException {
        return XContentHelper.convertToMap(XContentHelper.toXContent(response, XContentType.JSON, params, false), false,
            XContentType.JSON).v2();
    }
Example 17
private void putAuditIndexMappings(String index, String mappings, ActionListener<Void> listener) {
        client.admin().indices().preparePutMapping(index)
                .setType(DOC_TYPE)
                .setSource(mappings, XContentType.JSON)
                .execute(ActionListener.wrap((response) -> {
                    if (response.isAcknowledged()) {
                        listener.onResponse(null);
                    } else {
                        listener.onFailure(new IllegalStateException("failed to put mappings for audit logging index [" + index + "]"));
                    }
                },
                listener::onFailure));
    }
Example 18
private static void prepareDogsIndex() {
        String dataMapping = "{  \"dog\": {" +
                " \"properties\": {\n" +
                "          \"dog_name\": {\n" +
                "            \"type\": \"text\",\n" +
                "            \"fielddata\": true\n" +
                "          }"+
                "       }"+
                "   }" +
                "}";
        client.admin().indices().preparePutMapping(TEST_INDEX_DOG).setType("dog").setSource(dataMapping, XContentType.JSON).execute().actionGet();
    }
Example 19
public void testFromByteArray() {
        String jobId = randomAlphaOfLength(10);
        PostDataRequest request = new PostDataRequest(jobId,
            XContentType.JSON,
            "{\"others\":{\"foo\":100}}".getBytes(StandardCharsets.UTF_8));

        assertEquals("{\"others\":{\"foo\":100}}", request.getContent().utf8ToString());
        assertEquals(XContentType.JSON, request.getXContentType());
        assertEquals(jobId, request.getJobId());
    }
Example 20
public void testWithPasswordHashThatsNotReallyAHash() throws IOException {
        final Hasher systemHasher = Hasher.PBKDF2;
        final String json = "{\n" +
            "    \"password_hash\": \"not-a-hash\"," +
            "    \"roles\": []\n" +
            "}";

        PutUserRequestBuilder builder = new PutUserRequestBuilder(mock(Client.class));
        final IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> {
            builder.source("hash_user", new BytesArray(json.getBytes(StandardCharsets.UTF_8)), XContentType.JSON, systemHasher).request();
        });
        assertThat(ex.getMessage(), containsString(Hasher.NOOP.name()));
        assertThat(ex.getMessage(), containsString(systemHasher.name()));
    }
Example 21
private static String mapToJson(Map<String, Object> mapping) throws IOException {
        if (mapping.isEmpty()) {
            return null;
        }
        XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
        builder.map(mapping);
        return XContentHelper.convertToJson(BytesReference.bytes(builder), false, false, XContentType.JSON);
    }
Example 22
private static void preparePhrasesIndex() {
        String dataMapping = "{  \"phrase\": {" +
                " \"properties\": {\n" +
                "          \"phrase\": {\n" +
                "            \"type\": \"text\",\n" +
                "            \"store\": true\n" +
                "          }" +
                "       }"+
                "   }" +
                "}";
        client.admin().indices().preparePutMapping(TEST_INDEX_PHRASE).setType("phrase").setSource(dataMapping, XContentType.JSON).execute().actionGet();
    }
Example 23
public PutWatchRequestBuilder setSource(WatchSourceBuilder source) {
        request.setSource(source.buildAsBytes(XContentType.JSON), XContentType.JSON);
        return this;
    }
Example 24
private static void assertToXContentAsJson(ToXContent e, String expectedJson) throws IOException {
        BytesReference actual = XContentHelper.toXContent(e, XContentType.JSON, randomBoolean());
        assertToXContentEquivalent(new BytesArray(expectedJson), actual, XContentType.JSON);
    }
Example 25
public void testParseRequest_InvalidCreateSetting() throws IOException {
        Job.Builder jobConfiguration = buildJobBuilder(jobId, null);
        jobConfiguration.setFinishedTime(new Date());
        BytesReference bytes = XContentHelper.toXContent(jobConfiguration, XContentType.JSON, false);
        XContentParser parser = createParser(XContentType.JSON.xContent(), bytes);
        expectThrows(IllegalArgumentException.class, () -> Request.parseRequest(jobId, parser));
    }