Search in sources :

Example 21 with XContent

use of org.opensearch.common.xcontent.XContent in project OpenSearch by opensearch-project.

the class RepositoryDataTests method testIndexThatReferencesAnUnknownSnapshot.

public void testIndexThatReferencesAnUnknownSnapshot() throws IOException {
    final XContent xContent = randomFrom(XContentType.values()).xContent();
    final RepositoryData repositoryData = generateRandomRepoData();
    XContentBuilder builder = XContentBuilder.builder(xContent);
    repositoryData.snapshotsToXContent(builder, Version.CURRENT);
    RepositoryData parsedRepositoryData;
    try (XContentParser xParser = createParser(builder)) {
        parsedRepositoryData = RepositoryData.snapshotsFromXContent(xParser, repositoryData.getGenId(), randomBoolean());
    }
    assertEquals(repositoryData, parsedRepositoryData);
    Map<String, SnapshotId> snapshotIds = new HashMap<>();
    Map<String, SnapshotState> snapshotStates = new HashMap<>();
    Map<String, Version> snapshotVersions = new HashMap<>();
    for (SnapshotId snapshotId : parsedRepositoryData.getSnapshotIds()) {
        snapshotIds.put(snapshotId.getUUID(), snapshotId);
        snapshotStates.put(snapshotId.getUUID(), parsedRepositoryData.getSnapshotState(snapshotId));
        snapshotVersions.put(snapshotId.getUUID(), parsedRepositoryData.getVersion(snapshotId));
    }
    final IndexId corruptedIndexId = randomFrom(parsedRepositoryData.getIndices().values());
    Map<IndexId, List<SnapshotId>> indexSnapshots = new HashMap<>();
    final ShardGenerations.Builder shardGenBuilder = ShardGenerations.builder();
    for (Map.Entry<String, IndexId> snapshottedIndex : parsedRepositoryData.getIndices().entrySet()) {
        IndexId indexId = snapshottedIndex.getValue();
        List<SnapshotId> snapshotsIds = new ArrayList<>(parsedRepositoryData.getSnapshots(indexId));
        if (corruptedIndexId.equals(indexId)) {
            snapshotsIds.add(new SnapshotId("_uuid", "_does_not_exist"));
        }
        indexSnapshots.put(indexId, snapshotsIds);
        final int shardCount = randomIntBetween(1, 10);
        for (int i = 0; i < shardCount; ++i) {
            shardGenBuilder.put(indexId, i, UUIDs.randomBase64UUID(random()));
        }
    }
    assertNotNull(corruptedIndexId);
    RepositoryData corruptedRepositoryData = new RepositoryData(parsedRepositoryData.getGenId(), snapshotIds, snapshotStates, snapshotVersions, indexSnapshots, shardGenBuilder.build(), IndexMetaDataGenerations.EMPTY);
    final XContentBuilder corruptedBuilder = XContentBuilder.builder(xContent);
    corruptedRepositoryData.snapshotsToXContent(corruptedBuilder, Version.CURRENT);
    try (XContentParser xParser = createParser(corruptedBuilder)) {
        OpenSearchParseException e = expectThrows(OpenSearchParseException.class, () -> RepositoryData.snapshotsFromXContent(xParser, corruptedRepositoryData.getGenId(), randomBoolean()));
        assertThat(e.getMessage(), equalTo("Detected a corrupted repository, index " + corruptedIndexId + " references an unknown " + "snapshot uuid [_does_not_exist]"));
    }
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SnapshotId(org.opensearch.snapshots.SnapshotId) SnapshotState(org.opensearch.snapshots.SnapshotState) OpenSearchParseException(org.opensearch.OpenSearchParseException) Version(org.opensearch.Version) XContent(org.opensearch.common.xcontent.XContent) JsonXContent(org.opensearch.common.xcontent.json.JsonXContent) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 22 with XContent

use of org.opensearch.common.xcontent.XContent in project OpenSearch by opensearch-project.

the class AggregationsTests method parseAndAssert.

/**
 * Test that parsing works for a randomly created Aggregations object with a
 * randomized aggregation tree. The test randomly chooses an
 * {@link XContentType}, randomizes the order of the {@link XContent} fields
 * and randomly sets the `humanReadable` flag when rendering the
 * {@link XContent}.
 *
 * @param addRandomFields
 *            if set, this will also add random {@link XContent} fields to
 *            tests that the parsers are lenient to future additions to rest
 *            responses
 */
private void parseAndAssert(boolean addRandomFields) throws IOException {
    XContentType xContentType = randomFrom(XContentType.values());
    final ToXContent.Params params = new ToXContent.MapParams(singletonMap(RestSearchAction.TYPED_KEYS_PARAM, "true"));
    Aggregations aggregations = createTestInstance();
    BytesReference originalBytes = toShuffledXContent(aggregations, xContentType, params, randomBoolean());
    BytesReference mutated;
    if (addRandomFields) {
        /*
             * - don't insert into the root object because it should only contain the named aggregations to test
             *
             * - don't insert into the "meta" object, because we pass on everything we find there
             *
             * - we don't want to directly insert anything random into "buckets"  objects, they are used with
             * "keyed" aggregations and contain named bucket objects. Any new named object on this level should
             * also be a bucket and be parsed as such.
             *
             * - we cannot insert randomly into VALUE or VALUES objects e.g. in Percentiles, the keys need to be numeric there
             *
             * - we cannot insert into ExtendedMatrixStats "covariance" or "correlation" fields, their syntax is strict
             *
             * - we cannot insert random values in top_hits, as all unknown fields
             * on a root level of SearchHit are interpreted as meta-fields and will be kept
             *
             * - exclude "key", it can be an array of objects and we need strict values
             */
        Predicate<String> excludes = path -> (path.isEmpty() || path.endsWith("aggregations") || path.endsWith(Aggregation.CommonFields.META.getPreferredName()) || path.endsWith(Aggregation.CommonFields.BUCKETS.getPreferredName()) || path.endsWith(CommonFields.VALUES.getPreferredName()) || path.endsWith("covariance") || path.endsWith("correlation") || path.contains(CommonFields.VALUE.getPreferredName()) || path.endsWith(CommonFields.KEY.getPreferredName())) || path.contains("top_hits");
        mutated = insertRandomFields(xContentType, originalBytes, excludes, random());
    } else {
        mutated = originalBytes;
    }
    try (XContentParser parser = createParser(xContentType.xContent(), mutated)) {
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken());
        assertEquals(Aggregations.AGGREGATIONS_FIELD, parser.currentName());
        assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken());
        Aggregations parsedAggregations = Aggregations.fromXContent(parser);
        BytesReference parsedBytes = XContentHelper.toXContent(parsedAggregations, xContentType, randomBoolean());
        OpenSearchAssertions.assertToXContentEquivalent(originalBytes, parsedBytes, xContentType);
    }
}
Also used : ToXContent(org.opensearch.common.xcontent.ToXContent) BytesReference(org.opensearch.common.bytes.BytesReference) InternalAggregationTestCase(org.opensearch.test.InternalAggregationTestCase) XContentTestUtils.insertRandomFields(org.opensearch.test.XContentTestUtils.insertRandomFields) InternalDateRangeTests(org.opensearch.search.aggregations.bucket.range.InternalDateRangeTests) ToXContent(org.opensearch.common.xcontent.ToXContent) InternalDateHistogramTests(org.opensearch.search.aggregations.bucket.histogram.InternalDateHistogramTests) InternalGeoBoundsTests(org.opensearch.search.aggregations.metrics.InternalGeoBoundsTests) InternalExtendedStatsTests(org.opensearch.search.aggregations.metrics.InternalExtendedStatsTests) InternalTDigestPercentilesTests(org.opensearch.search.aggregations.metrics.InternalTDigestPercentilesTests) InternalStatsBucketTests(org.opensearch.search.aggregations.metrics.InternalStatsBucketTests) XContentParser(org.opensearch.common.xcontent.XContentParser) InternalMissingTests(org.opensearch.search.aggregations.bucket.missing.InternalMissingTests) InternalFilterTests(org.opensearch.search.aggregations.bucket.filter.InternalFilterTests) InternalTDigestPercentilesRanksTests(org.opensearch.search.aggregations.metrics.InternalTDigestPercentilesRanksTests) After(org.junit.After) XContentFactory(org.opensearch.common.xcontent.XContentFactory) GeoHashGridTests(org.opensearch.search.aggregations.bucket.geogrid.GeoHashGridTests) InternalMedianAbsoluteDeviationTests(org.opensearch.search.aggregations.metrics.InternalMedianAbsoluteDeviationTests) InternalReverseNestedTests(org.opensearch.search.aggregations.bucket.nested.InternalReverseNestedTests) InternalHDRPercentilesRanksTests(org.opensearch.search.aggregations.metrics.InternalHDRPercentilesRanksTests) InternalMultiBucketAggregationTestCase(org.opensearch.test.InternalMultiBucketAggregationTestCase) ParsingException(org.opensearch.common.ParsingException) InternalHistogramTests(org.opensearch.search.aggregations.bucket.histogram.InternalHistogramTests) Predicate(java.util.function.Predicate) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Set(java.util.Set) Collectors(java.util.stream.Collectors) InternalWeightedAvgTests(org.opensearch.search.aggregations.metrics.InternalWeightedAvgTests) InternalVariableWidthHistogramTests(org.opensearch.search.aggregations.bucket.histogram.InternalVariableWidthHistogramTests) OpenSearchAssertions(org.opensearch.test.hamcrest.OpenSearchAssertions) StringTermsTests(org.opensearch.search.aggregations.bucket.terms.StringTermsTests) InternalCardinalityTests(org.opensearch.search.aggregations.metrics.InternalCardinalityTests) List(java.util.List) InternalCompositeTests(org.opensearch.search.aggregations.bucket.composite.InternalCompositeTests) XContentType(org.opensearch.common.xcontent.XContentType) InternalTopHitsTests(org.opensearch.search.aggregations.metrics.InternalTopHitsTests) InternalBucketMetricValueTests(org.opensearch.search.aggregations.pipeline.InternalBucketMetricValueTests) InternalAdjacencyMatrixTests(org.opensearch.search.aggregations.bucket.adjacency.InternalAdjacencyMatrixTests) LongTermsTests(org.opensearch.search.aggregations.bucket.terms.LongTermsTests) StringRareTermsTests(org.opensearch.search.aggregations.bucket.terms.StringRareTermsTests) InternalGeoCentroidTests(org.opensearch.search.aggregations.metrics.InternalGeoCentroidTests) BytesReference(org.opensearch.common.bytes.BytesReference) GeoTileGridTests(org.opensearch.search.aggregations.bucket.geogrid.GeoTileGridTests) InternalSamplerTests(org.opensearch.search.aggregations.bucket.sampler.InternalSamplerTests) InternalNestedTests(org.opensearch.search.aggregations.bucket.nested.InternalNestedTests) InternalRangeTests(org.opensearch.search.aggregations.bucket.range.InternalRangeTests) InternalFiltersTests(org.opensearch.search.aggregations.bucket.filter.InternalFiltersTests) InternalPercentilesBucketTests(org.opensearch.search.aggregations.pipeline.InternalPercentilesBucketTests) CommonFields(org.opensearch.search.aggregations.Aggregation.CommonFields) InternalValueCountTests(org.opensearch.search.aggregations.metrics.InternalValueCountTests) ArrayList(java.util.ArrayList) RestSearchAction(org.opensearch.rest.action.search.RestSearchAction) InternalHDRPercentilesTests(org.opensearch.search.aggregations.metrics.InternalHDRPercentilesTests) InternalExtendedStatsBucketTests(org.opensearch.search.aggregations.pipeline.InternalExtendedStatsBucketTests) InternalBinaryRangeTests(org.opensearch.search.aggregations.bucket.range.InternalBinaryRangeTests) InternalAvgTests(org.opensearch.search.aggregations.metrics.InternalAvgTests) LongRareTermsTests(org.opensearch.search.aggregations.bucket.terms.LongRareTermsTests) InternalSimpleValueTests(org.opensearch.search.aggregations.pipeline.InternalSimpleValueTests) Collections.singletonMap(java.util.Collections.singletonMap) InternalGlobalTests(org.opensearch.search.aggregations.bucket.global.InternalGlobalTests) Before(org.junit.Before) SignificantStringTermsTests(org.opensearch.search.aggregations.bucket.terms.SignificantStringTermsTests) InternalMinTests(org.opensearch.search.aggregations.metrics.InternalMinTests) InternalSumTests(org.opensearch.search.aggregations.metrics.InternalSumTests) InternalMaxTests(org.opensearch.search.aggregations.metrics.InternalMaxTests) IOException(java.io.IOException) InternalStatsTests(org.opensearch.search.aggregations.metrics.InternalStatsTests) XContent(org.opensearch.common.xcontent.XContent) InternalAutoDateHistogramTests(org.opensearch.search.aggregations.bucket.histogram.InternalAutoDateHistogramTests) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentHelper(org.opensearch.common.xcontent.XContentHelper) DoubleTermsTests(org.opensearch.search.aggregations.bucket.terms.DoubleTermsTests) InternalDerivativeTests(org.opensearch.search.aggregations.pipeline.InternalDerivativeTests) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) SignificantLongTermsTests(org.opensearch.search.aggregations.bucket.terms.SignificantLongTermsTests) InternalScriptedMetricTests(org.opensearch.search.aggregations.metrics.InternalScriptedMetricTests) Collections(java.util.Collections) InternalGeoDistanceTests(org.opensearch.search.aggregations.bucket.range.InternalGeoDistanceTests) XContentType(org.opensearch.common.xcontent.XContentType) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 23 with XContent

use of org.opensearch.common.xcontent.XContent in project OpenSearch by opensearch-project.

the class AbstractFilteringTestCase method testRawField.

public void testRawField() throws Exception {
    final Builder expectedRawField = builder -> builder.startObject().field("foo", 0).startObject("raw").field("content", "hello world!").endObject().endObject();
    final Builder expectedRawFieldFiltered = builder -> builder.startObject().field("foo", 0).endObject();
    final Builder expectedRawFieldNotFiltered = builder -> builder.startObject().startObject("raw").field("content", "hello world!").endObject().endObject();
    Builder sampleWithRaw = builder -> {
        BytesReference raw = BytesReference.bytes(XContentBuilder.builder(builder.contentType().xContent()).startObject().field("content", "hello world!").endObject());
        return builder.startObject().field("foo", 0).rawField("raw", raw.streamInput()).endObject();
    };
    // Test method: rawField(String fieldName, BytesReference content)
    testFilter(expectedRawField, sampleWithRaw, emptySet(), emptySet());
    testFilter(expectedRawFieldFiltered, sampleWithRaw, singleton("f*"), emptySet());
    testFilter(expectedRawFieldFiltered, sampleWithRaw, emptySet(), singleton("r*"));
    testFilter(expectedRawFieldNotFiltered, sampleWithRaw, singleton("r*"), emptySet());
    testFilter(expectedRawFieldNotFiltered, sampleWithRaw, emptySet(), singleton("f*"));
    sampleWithRaw = builder -> {
        BytesReference raw = BytesReference.bytes(XContentBuilder.builder(builder.contentType().xContent()).startObject().field("content", "hello world!").endObject());
        return builder.startObject().field("foo", 0).rawField("raw", raw.streamInput()).endObject();
    };
    // Test method: rawField(String fieldName, InputStream content)
    testFilter(expectedRawField, sampleWithRaw, emptySet(), emptySet());
    testFilter(expectedRawFieldFiltered, sampleWithRaw, singleton("f*"), emptySet());
    testFilter(expectedRawFieldFiltered, sampleWithRaw, emptySet(), singleton("r*"));
    testFilter(expectedRawFieldNotFiltered, sampleWithRaw, singleton("r*"), emptySet());
    testFilter(expectedRawFieldNotFiltered, sampleWithRaw, emptySet(), singleton("f*"));
}
Also used : XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) Sets(org.opensearch.common.util.set.Sets) BytesReference(org.opensearch.common.bytes.BytesReference) Collections.emptySet(java.util.Collections.emptySet) Collections.singleton(java.util.Collections.singleton) CheckedFunction(org.opensearch.common.CheckedFunction) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Set(java.util.Set) IOException(java.io.IOException) XContent(org.opensearch.common.xcontent.XContent) BytesReference(org.opensearch.common.bytes.BytesReference) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder)

Aggregations

XContent (org.opensearch.common.xcontent.XContent)23 XContentParser (org.opensearch.common.xcontent.XContentParser)19 ToXContent (org.opensearch.common.xcontent.ToXContent)16 BytesReference (org.opensearch.common.bytes.BytesReference)12 XContentBuilder (org.opensearch.common.xcontent.XContentBuilder)10 IOException (java.io.IOException)7 RoutingMissingException (org.opensearch.action.RoutingMissingException)4 ParsingException (org.opensearch.common.ParsingException)4 XContentType (org.opensearch.common.xcontent.XContentType)4 DeleteRequest (org.opensearch.action.delete.DeleteRequest)3 IndexRequest (org.opensearch.action.index.IndexRequest)3 UpdateRequest (org.opensearch.action.update.UpdateRequest)3 ArrayList (java.util.ArrayList)2 List (java.util.List)2 Set (java.util.Set)2 NByteArrayEntity (org.apache.http.nio.entity.NByteArrayEntity)2 DocWriteRequest (org.opensearch.action.DocWriteRequest)2 ClusterHealthRequest (org.opensearch.action.admin.cluster.health.ClusterHealthRequest)2 DeleteStoredScriptRequest (org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest)2 GetStoredScriptRequest (org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest)2