org.elasticsearch.common.xcontent.DeprecationHandler Java Examples

The following examples show how to use org.elasticsearch.common.xcontent.DeprecationHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Job.java    From zentity with Apache License 2.0 6 votes vote down vote up
/**
 * Submit a search query to Elasticsearch.
 *
 * @param indexName The name of the index to search.
 * @param query     The query to search.
 * @return The search response returned by Elasticsearch.
 * @throws IOException
 */
private SearchResponse search(String indexName, String query) throws IOException {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.emptyList());
    try (XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(new NamedXContentRegistry(searchModule
            .getNamedXContents()), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, query)) {
        searchSourceBuilder.parseXContent(parser);
    }
    SearchRequestBuilder searchRequestBuilder = new SearchRequestBuilder(client, SearchAction.INSTANCE);
    searchRequestBuilder.setIndices(indexName).setSource(searchSourceBuilder);
    if (this.searchAllowPartialSearchResults != null)
        searchRequestBuilder.setAllowPartialSearchResults(this.searchAllowPartialSearchResults);
    if (this.searchBatchedReduceSize != null)
        searchRequestBuilder.setBatchedReduceSize(this.searchBatchedReduceSize);
    if (this.searchMaxConcurrentShardRequests != null)
        searchRequestBuilder.setMaxConcurrentShardRequests(this.searchMaxConcurrentShardRequests);
    if (this.searchPreFilterShardSize != null)
        searchRequestBuilder.setPreFilterShardSize(this.searchPreFilterShardSize);
    if (this.searchPreference != null)
        searchRequestBuilder.setPreference(this.searchPreference);
    if (this.searchRequestCache != null)
        searchRequestBuilder.setRequestCache(this.searchRequestCache);
    if (this.maxTimePerQuery != null)
        searchRequestBuilder.setTimeout(TimeValue.parseTimeValue(this.maxTimePerQuery, "timeout"));
    return searchRequestBuilder.execute().actionGet();
}
 
Example #2
Source File: SampleIndexTestCase.java    From elasticsearch-carrot2 with Apache License 2.0 6 votes vote down vote up
protected static Map<String, Object> checkHttpResponse(HttpResponse response) throws IOException {
   byte[] responseBytes = response.getEntity().getContent().readAllBytes();
   String responseString = new String(responseBytes, StandardCharsets.UTF_8);

   String responseDescription =
       "HTTP response status: " + response.getStatusLine().toString() + ", " +
           "HTTP body: " + responseString;

   Assertions.assertThat(response.getStatusLine().getStatusCode())
       .describedAs(responseDescription)
       .isEqualTo(HttpStatus.SC_OK);

   try (XContentParser parser = XContentHelper.createParser(
       NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
       new BytesArray(responseBytes),
       XContentType.fromMediaTypeOrFormat(response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue()))) {
      Map<String, Object> map = parser.map();
      Assertions.assertThat(map)
          .describedAs(responseDescription)
          .doesNotContainKey("error");
      return map;
   }
}
 
Example #3
Source File: UsersMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testUsersMetaDataWithoutAttributesToXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();

    UsersMetaData users = new UsersMetaData(UserDefinitions.SINGLE_USER_ONLY);
    users.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        Strings.toString(builder));
    parser.nextToken(); // start object
    UsersMetaData users2 = UsersMetaData.fromXContent(parser);
    assertEquals(users, users2);

    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #4
Source File: ParseField.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Does {@code fieldName} match this field?
 * @param fieldName
 *            the field name to match against this {@link ParseField}
 * @param deprecationHandler called if {@code fieldName} is deprecated
 * @return true if <code>fieldName</code> matches any of the acceptable
 *         names for this {@link ParseField}.
 */
public boolean match(String fieldName, DeprecationHandler deprecationHandler) {
    Objects.requireNonNull(fieldName, "fieldName cannot be null");
    // if this parse field has not been completely deprecated then try to
    // match the preferred name
    if (allReplacedWith == null && fieldName.equals(name)) {
        return true;
    }
    // Now try to match against one of the deprecated names. Note that if
    // the parse field is entirely deprecated (allReplacedWith != null) all
    // fields will be in the deprecatedNames array
    for (String depName : deprecatedNames) {
        if (fieldName.equals(depName)) {
            if (allReplacedWith == null) {
                deprecationHandler.usedDeprecatedName(fieldName, name);
            } else {
                deprecationHandler.usedDeprecatedField(fieldName, allReplacedWith);
            }
            return true;
        }
    }
    return false;
}
 
Example #5
Source File: SampleIndexTestCase.java    From elasticsearch-carrot2 with Apache License 2.0 6 votes vote down vote up
/**
 * Roundtrip to/from JSON.
 */
protected static void checkJsonSerialization(ClusteringActionResponse result) throws IOException {
   XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint();
   builder.startObject();
   result.toXContent(builder, ToXContent.EMPTY_PARAMS);
   builder.endObject();
   String json = Strings.toString(builder);

   try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY,
       DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json)) {
      Map<String, Object> mapAndClose = parser.map();
      Assertions.assertThat(mapAndClose)
          .as("json-result")
          .containsKey(Fields.CLUSTERS);
   }
}
 
Example #6
Source File: UsersMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testUsersMetaDataToXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();

    UsersMetaData users = new UsersMetaData(UserDefinitions.DUMMY_USERS);
    users.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        Strings.toString(builder));
    parser.nextToken(); // start object
    UsersMetaData users2 = UsersMetaData.fromXContent(parser);
    assertEquals(users, users2);

    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #7
Source File: LicenseKeyTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testLicenceKeyToXContent() throws IOException {
    LicenseKey licenseKey = createLicenseKey();
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();
    licenseKey.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken(); // start object
    LicenseKey licenseKey2 = LicenseKey.fromXContent(parser);
    assertEquals(licenseKey, licenseKey2);
    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #8
Source File: UsersPrivilegesMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();

    usersPrivilegesMetaData.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        Strings.toString(builder)
    );
    parser.nextToken(); // start object
    UsersPrivilegesMetaData usersPrivilegesMetaData2 = UsersPrivilegesMetaData.fromXContent(parser);
    assertEquals(usersPrivilegesMetaData, usersPrivilegesMetaData2);

    // a metadata custom must consume its surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #9
Source File: SQLTransportExecutor.java    From crate with Apache License 2.0 6 votes vote down vote up
private static Object jsonToObject(String json) {
    try {
        if (json != null) {
            byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
            XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
                NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, bytes);
            if (bytes.length >= 1 && bytes[0] == '[') {
                parser.nextToken();
                return parser.list();
            } else {
                return parser.mapOrdered();
            }
        } else {
            return null;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #10
Source File: UserDefinedFunctionsMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testUserDefinedFunctionToXContentWithEmptyMetadata() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();
    UserDefinedFunctionsMetaData functions = UserDefinedFunctionsMetaData.of();
    functions.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken(); // enter START_OBJECT
    UserDefinedFunctionsMetaData functions2 = UserDefinedFunctionsMetaData.fromXContent(parser);
    assertEquals(functions, functions2);
}
 
Example #11
Source File: LicenseKeyTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testLicenceKeyFromXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();
    builder.startObject(LicenseKey.WRITEABLE_TYPE)
        .field("license_key", LICENSE_KEY)
        .endObject();
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken(); // start object
    LicenseKey licenseKey2 = LicenseKey.fromXContent(parser);
    assertEquals(createLicenseKey(), licenseKey2);
    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #12
Source File: Setting.java    From crate with Apache License 2.0 6 votes vote down vote up
private static List<String> parseableStringToList(String parsableString) {
    // fromXContent doesn't use named xcontent or deprecation.
    try (XContentParser xContentParser = XContentType.JSON.xContent()
            .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, parsableString)) {
        XContentParser.Token token = xContentParser.nextToken();
        if (token != XContentParser.Token.START_ARRAY) {
            throw new IllegalArgumentException("expected START_ARRAY but got " + token);
        }
        ArrayList<String> list = new ArrayList<>();
        while ((token = xContentParser.nextToken()) != XContentParser.Token.END_ARRAY) {
            if (token != XContentParser.Token.VALUE_STRING) {
                throw new IllegalArgumentException("expected VALUE_STRING but got " + token);
            }
            list.add(xContentParser.text());
        }
        return list;
    } catch (IOException e) {
        throw new IllegalArgumentException("failed to parse array", e);
    }
}
 
Example #13
Source File: SQLRequestParser.java    From crate with Apache License 2.0 6 votes vote down vote up
public static SQLRequestParseContext parseSource(BytesReference source) throws IOException {
    if (source.length() == 0) {
        throw new SQLParseException("Missing request body");
    }
    XContentParser parser = null;
    try {
        SQLRequestParseContext parseContext = new SQLRequestParseContext();
        parser = XContentFactory.xContent(XContentType.JSON).createParser(
            NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.toBytes(source));
        parse(parseContext, parser);
        validate(parseContext);
        return parseContext;
    } catch (Exception e) {
        String sSource = "_na_";
        try {
            sSource = XContentHelper.convertToJson(source, XContentType.JSON);
        } catch (Throwable e1) {
            // ignore
        }
        throw new SQLParseException("Failed to parse source [" + sSource + "]", e);
    } finally {
        if (parser != null) {
            parser.close();
        }
    }
}
 
Example #14
Source File: XContentTestUtilsTests.java    From crate with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void testInsertIntoXContent() throws IOException {
    XContentBuilder builder = JsonXContent.contentBuilder();
    builder.startObject();
    builder.endObject();
    builder = XContentTestUtils.insertIntoXContent(XContentType.JSON.xContent(), BytesReference.bytes(builder),
            Collections.singletonList(""), () -> "inn.er1", () -> new HashMap<>());
    builder = XContentTestUtils.insertIntoXContent(XContentType.JSON.xContent(), BytesReference.bytes(builder),
            Collections.singletonList(""), () -> "field1", () -> "value1");
    builder = XContentTestUtils.insertIntoXContent(XContentType.JSON.xContent(), BytesReference.bytes(builder),
            Collections.singletonList("inn\\.er1"), () -> "inner2", () -> new HashMap<>());
    builder = XContentTestUtils.insertIntoXContent(XContentType.JSON.xContent(), BytesReference.bytes(builder),
            Collections.singletonList("inn\\.er1"), () -> "field2", () -> "value2");
    try (XContentParser parser = XContentHelper.createParser(NamedXContentRegistry.EMPTY,
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.bytes(builder), builder.contentType())) {
        Map<String, Object> map = parser.map();
        assertEquals(2, map.size());
        assertEquals("value1", map.get("field1"));
        assertThat(map.get("inn.er1"), instanceOf(Map.class));
        Map<String, Object> innerMap = (Map<String, Object>) map.get("inn.er1");
        assertEquals(2, innerMap.size());
        assertEquals("value2", innerMap.get("field2"));
        assertThat(innerMap.get("inner2"), instanceOf(Map.class));
        assertEquals(0, ((Map<String, Object>) innerMap.get("inner2")).size());
    }
}
 
Example #15
Source File: ElasticsearchAssertions.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the provided {@link BytesReference}s created through
 * {@link org.elasticsearch.common.xcontent.ToXContent#toXContent(XContentBuilder, ToXContent.Params)} hold the same content.
 * The comparison is done by parsing both into a map and comparing those two, so that keys ordering doesn't matter.
 * Also binary values (byte[]) are properly compared through arrays comparisons.
 */
public static void assertToXContentEquivalent(BytesReference expected, BytesReference actual, XContentType xContentType)
        throws IOException {
    //we tried comparing byte per byte, but that didn't fly for a couple of reasons:
    //1) whenever anything goes through a map while parsing, ordering is not preserved, which is perfectly ok
    //2) Jackson SMILE parser parses floats as double, which then get printed out as double (with double precision)
    //Note that byte[] holding binary values need special treatment as they need to be properly compared item per item.
    Map<String, Object> actualMap = null;
    Map<String, Object> expectedMap = null;
    try (XContentParser actualParser = xContentType.xContent()
            .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, actual.streamInput())) {
        actualMap = actualParser.map();
        try (XContentParser expectedParser = xContentType.xContent()
                .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, expected.streamInput())) {
            expectedMap = expectedParser.map();
            try {
                assertMapEquals(expectedMap, actualMap);
            } catch (AssertionError error) {
                NotEqualMessageBuilder message = new NotEqualMessageBuilder();
                message.compareMaps(actualMap, expectedMap);
                throw new AssertionError("Error when comparing xContent.\n" + message.toString(), error);
            }
        }
    }
}
 
Example #16
Source File: ViewsMetaDataTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testViewsMetaDataToXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // reflects the logic used to process custom metadata in the cluster state
    builder.startObject();

    ViewsMetaData views = createMetaData();
    views.toXContent(builder, ToXContent.EMPTY_PARAMS);
    builder.endObject();

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken(); // start object
    ViewsMetaData views2 = ViewsMetaData.fromXContent(parser);
    assertEquals(views, views2);

    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #17
Source File: PartitionedTableIntegrationTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
@UseRandomizedSchema(random = false)
public void testAlterTableAddColumnOnPartitionedTableWithoutPartitions() throws Exception {
    execute("create table t (id int primary key, date timestamp with time zone primary key) " +
            "partitioned by (date) " +
            "clustered into 1 shards " +
            "with (number_of_replicas=0)");
    ensureYellow();

    execute("alter table t add column name string");
    execute("alter table t add column ft_name string index using fulltext");
    ensureYellow();

    execute("select * from t");
    assertThat(Arrays.asList(response.cols()), Matchers.containsInAnyOrder("date", "ft_name", "id", "name"));

    GetIndexTemplatesResponse templatesResponse = client().admin().indices().getTemplates(new GetIndexTemplatesRequest(".partitioned.t.")).actionGet();
    IndexTemplateMetaData metaData = templatesResponse.getIndexTemplates().get(0);
    String mappingSource = metaData.mappings().get(DEFAULT_MAPPING_TYPE).toString();
    Map mapping = (Map) XContentFactory.xContent(mappingSource)
        .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, mappingSource)
        .map()
        .get(DEFAULT_MAPPING_TYPE);
    assertNotNull(((Map) mapping.get("properties")).get("name"));
    assertNotNull(((Map) mapping.get("properties")).get("ft_name"));
}
 
Example #18
Source File: JsonXContentGenerator.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public void writeRawField(String name, InputStream content, XContentType contentType) throws IOException {
    if (mayWriteRawData(contentType) == false) {
        // EMPTY is safe here because we never call namedObject when writing raw data
        try (XContentParser parser = XContentFactory.xContent(contentType)
                // It's okay to pass the throwing deprecation handler
                // because we should not be writing raw fields when
                // generating JSON
                .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, content)) {
            parser.nextToken();
            writeFieldName(name);
            copyCurrentStructure(parser);
        }
    } else {
        writeStartRaw(name);
        flush();
        copyStream(content, os);
        writeEndRaw();
    }
}
 
Example #19
Source File: ObjectType.java    From crate with Apache License 2.0 5 votes vote down vote up
private static Map<String,Object> mapFromJSONString(String value) {
    try {
        XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
            NamedXContentRegistry.EMPTY,
            DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
            value
        );
        return parser.map();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #20
Source File: FromRawInsertSource.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, Object> generateSourceAndCheckConstraints(Object[] values) throws IOException {
    return JsonXContent.JSON_XCONTENT.createParser(
        NamedXContentRegistry.EMPTY,
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        new BytesArray(((String) values[0])).array()
    ).map();
}
 
Example #21
Source File: DDLClusterStateHelpers.java    From crate with Apache License 2.0 5 votes vote down vote up
private static Map<String, Object> parseMapping(String mappingSource) {
    try (XContentParser parser = JsonXContent.JSON_XCONTENT
        .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, mappingSource)) {
        return parser.map();
    } catch (IOException e) {
        throw new ElasticsearchException("failed to parse mapping");
    }
}
 
Example #22
Source File: TransportCreatePartitionsAction.java    From crate with Apache License 2.0 5 votes vote down vote up
private Map<String, Object> parseMapping(String mappingSource) throws Exception {
    try (XContentParser parser = XContentFactory.xContent(XContentType.JSON)
        .createParser(xContentRegistry, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, mappingSource)) {
        return parser.map();
    } catch (IOException e) {
        throw new ElasticsearchException("failed to parse mapping", e);
    }
}
 
Example #23
Source File: ObjectPath.java    From crate with Apache License 2.0 5 votes vote down vote up
public static ObjectPath createFromXContent(XContent xContent, BytesReference input) throws IOException {
    try (XContentParser parser = xContent
            .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, input.streamInput())) {
        if (parser.nextToken() == XContentParser.Token.START_ARRAY) {
            return new ObjectPath(parser.listOrderedMap());
        }
        return new ObjectPath(parser.mapOrdered());
    }
}
 
Example #24
Source File: LicenseConverter.java    From crate with Apache License 2.0 5 votes vote down vote up
static LicenseData fromJson(byte[] jsonBytes, int version) throws IOException {
    try (XContentParser parser = XContentFactory.xContent(XContentType.JSON)
        .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, jsonBytes)) {
        XContentParser.Token token;
        long expiryDate = UNLIMITED_EXPIRY_DATE_IN_MS;
        String issuedTo = null;
        int maxNumberOfNodes = -1;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                String currentFieldName = parser.currentName();
                parser.nextToken();
                if (currentFieldName.equals(EXPIRY_DATE_IN_MS)) {
                    expiryDate = parser.longValue();
                } else if (currentFieldName.equals(ISSUED_TO)) {
                    issuedTo = parser.text();
                } else if (currentFieldName.equals(MAX_NUMBER_OF_NODES)) {
                    maxNumberOfNodes = parser.intValue();
                }
            }
        }
        if (maxNumberOfNodes == -1) {
            if (version == 1) {
                maxNumberOfNodes = MAX_NODES_FOR_V1_LICENSES;
            } else if (version == 2) {
                throw new IllegalStateException("LicenseKey v2 should have a valid value for " +
                                                MAX_NUMBER_OF_NODES);
            }
        }
        return new LicenseData(expiryDate, issuedTo, maxNumberOfNodes);
    }
}
 
Example #25
Source File: JsonType.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
Object decodeUTF8Text(byte[] bytes) {
    try {
        XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
            NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, bytes);
        if (bytes.length > 1 && bytes[0] == '[') {
            parser.nextToken();
            return parser.list();
        }
        return parser.map();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #26
Source File: TestingHelpers.java    From crate with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> jsonMap(String json) {
    try {
        return JsonXContent.JSON_XCONTENT.createParser(
            NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, json).map();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #27
Source File: UserDefinedFunctionsMetaDataTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testDataTypeStreaming() throws Exception {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    var type = new ArrayType<>(new ArrayType<>(DataTypes.STRING));
    UserDefinedFunctionMetaData.DataTypeXContent.toXContent(type, builder, ToXContent.EMPTY_PARAMS);
    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(), DeprecationHandler.THROW_UNSUPPORTED_OPERATION, BytesReference.toBytes(BytesReference.bytes(builder)));
    parser.nextToken();  // enter START_OBJECT
    ArrayType type2 = (ArrayType) UserDefinedFunctionMetaData.DataTypeXContent.fromXContent(parser);
    assertTrue(type.equals(type2));
}
 
Example #28
Source File: SQLBulkArgsParseElementTest.java    From crate with Apache License 2.0 5 votes vote down vote up
private List<List<Object>> parse(String bulkArgs) throws Exception {
    SQLRequestParseContext context = new SQLRequestParseContext();
    String json = "{\"bulk_args\":" + bulkArgs + "}";
    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 #29
Source File: UsersMetaDataTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testUsersMetaDataFromLegacyXContent() throws IOException {
    XContentBuilder builder = XContentFactory.jsonBuilder();

    // Generate legacy (v1) XContent of UsersMetaData
    // { "users": [ "Ford", "Arthur" ] }
    builder.startObject();
    builder.startArray("users");
    builder.value("Ford");
    builder.value("Arthur");
    builder.endArray();
    builder.endObject();

    HashMap<String, SecureHash> expectedUsers = new HashMap<>();
    expectedUsers.put("Ford", null);
    expectedUsers.put("Arthur", null);

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        xContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        Strings.toString(builder));
    parser.nextToken(); // start object
    UsersMetaData users = UsersMetaData.fromXContent(parser);
    assertEquals(users, new UsersMetaData(expectedUsers));

    // a metadata custom must consume the surrounded END_OBJECT token, no token must be left
    assertThat(parser.nextToken(), nullValue());
}
 
Example #30
Source File: CustomMetaDataTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testAllMetaDataXContentRoundtrip() throws IOException {
    MetaData metaData = MetaData.builder()
        .putCustom(UsersMetaData.TYPE,
            new UsersMetaData(UserDefinitions.DUMMY_USERS))
        .putCustom(UserDefinedFunctionsMetaData.TYPE,
            UserDefinedFunctionsMetaDataTest.DUMMY_UDF_META_DATA)
        .putCustom(UsersPrivilegesMetaData.TYPE,
            UsersPrivilegesMetaDataTest.createMetaData())
        .putCustom(ViewsMetaData.TYPE,
            ViewsMetaDataTest.createMetaData())
        .generateClusterUuidIfNeeded()
        .version(1L)
        .build();

    String xContent = xContentFromMetaData(metaData);

    XContentParser parser = JsonXContent.JSON_XCONTENT.createParser(
        getNamedXContentRegistry(),
        DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
        xContent
    );

    MetaData restoredMetaData = MetaData.FORMAT.fromXContent(parser);
    boolean isEqual = MetaData.isGlobalStateEquals(restoredMetaData, metaData);
    if (!isEqual) {
        assertEquals("meta-data must be equal", xContent, xContentFromMetaData(restoredMetaData));
    }
    assertTrue(isEqual);
    assertThat(parser.currentToken(), is(XContentParser.Token.END_OBJECT));
}