Search in sources :

Example 16 with NamedXContentRegistry

use of org.opensearch.common.xcontent.NamedXContentRegistry in project anomaly-detection by opensearch-project.

the class TestHelpers method randomFeatureQuery.

public static SearchSourceBuilder randomFeatureQuery() throws IOException {
    String query = "{\"query\":{\"match\":{\"user\":{\"query\":\"kimchy\",\"operator\":\"OR\",\"prefix_length\":0," + "\"max_expansions\":50,\"fuzzy_transpositions\":true,\"lenient\":false,\"zero_terms_query\":\"NONE\"," + "\"auto_generate_synonyms_phrase_query\":true,\"boost\":1}}}}";
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    SearchModule searchModule = new SearchModule(Settings.EMPTY, false, Collections.emptyList());
    XContentParser parser = XContentType.JSON.xContent().createParser(new NamedXContentRegistry(searchModule.getNamedXContents()), LoggingDeprecationHandler.INSTANCE, query);
    searchSourceBuilder.parseXContent(parser);
    return searchSourceBuilder;
}
Also used : SearchModule(org.opensearch.search.SearchModule) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) XContentParser(org.opensearch.common.xcontent.XContentParser) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder)

Example 17 with NamedXContentRegistry

use of org.opensearch.common.xcontent.NamedXContentRegistry in project anomaly-detection by opensearch-project.

the class ParseUtils method getDetector.

/**
 * If filterByEnabled is true, get detector and check if the user has permissions to access the detector,
 * then execute function; otherwise, get detector and execute function
 * @param requestUser user from request
 * @param detectorId detector id
 * @param listener action listener
 * @param function consumer function
 * @param client client
 * @param clusterService cluster service
 * @param xContentRegistry XContent registry
 * @param filterByBackendRole filter by backend role or not
 */
public static void getDetector(User requestUser, String detectorId, ActionListener listener, Consumer<AnomalyDetector> function, Client client, ClusterService clusterService, NamedXContentRegistry xContentRegistry, boolean filterByBackendRole) {
    if (clusterService.state().metadata().indices().containsKey(AnomalyDetector.ANOMALY_DETECTORS_INDEX)) {
        GetRequest request = new GetRequest(AnomalyDetector.ANOMALY_DETECTORS_INDEX).id(detectorId);
        client.get(request, ActionListener.wrap(response -> onGetAdResponse(response, requestUser, detectorId, listener, function, xContentRegistry, filterByBackendRole), exception -> {
            logger.error("Failed to get anomaly detector: " + detectorId, exception);
            listener.onFailure(exception);
        }));
    } else {
        listener.onFailure(new IndexNotFoundException(AnomalyDetector.ANOMALY_DETECTORS_INDEX));
    }
}
Also used : Max(org.opensearch.search.aggregations.metrics.Max) ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) BaseAggregationBuilder(org.opensearch.search.aggregations.BaseAggregationBuilder) FAIL_TO_GET_USER_INFO(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_GET_USER_INFO) FAIL_TO_FIND_DETECTOR_MSG(org.opensearch.ad.constant.CommonErrorMessages.FAIL_TO_FIND_DETECTOR_MSG) PipelineAggregationBuilder(org.opensearch.search.aggregations.PipelineAggregationBuilder) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) XContentParser(org.opensearch.common.xcontent.XContentParser) AggregationBuilder(org.opensearch.search.aggregations.AggregationBuilder) Matcher(java.util.regex.Matcher) DateHistogramValuesSourceBuilder(org.opensearch.search.aggregations.bucket.composite.DateHistogramValuesSourceBuilder) Map(java.util.Map) ActionListener(org.opensearch.action.ActionListener) DateRangeAggregationBuilder(org.opensearch.search.aggregations.bucket.range.DateRangeAggregationBuilder) GetResponse(org.opensearch.action.get.GetResponse) ParsingException(org.opensearch.common.ParsingException) NestedQueryBuilder(org.opensearch.index.query.NestedQueryBuilder) Client(org.opensearch.client.Client) Collection(java.util.Collection) Feature(org.opensearch.ad.model.Feature) QUERY_PARAM_PERIOD_END(org.opensearch.ad.model.AnomalyDetector.QUERY_PARAM_PERIOD_END) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Set(java.util.Set) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) Instant(java.time.Instant) ScoreMode(org.apache.lucene.search.join.ScoreMode) Objects(java.util.Objects) NO_PERMISSION_TO_ACCESS_DETECTOR(org.opensearch.ad.constant.CommonErrorMessages.NO_PERMISSION_TO_ACCESS_DETECTOR) List(java.util.List) Logger(org.apache.logging.log4j.Logger) QueryBuilder(org.opensearch.index.query.QueryBuilder) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) Entry(java.util.Map.Entry) DATE_HISTOGRAM(org.opensearch.ad.constant.CommonName.DATE_HISTOGRAM) Optional(java.util.Optional) TermsQueryBuilder(org.opensearch.index.query.TermsQueryBuilder) FEATURE_AGGS(org.opensearch.ad.constant.CommonName.FEATURE_AGGS) XContentType(org.opensearch.common.xcontent.XContentType) BoolQueryBuilder(org.opensearch.index.query.BoolQueryBuilder) ConfigConstants(org.opensearch.commons.ConfigConstants) AggregatorFactories(org.opensearch.search.aggregations.AggregatorFactories) FeatureData(org.opensearch.ad.model.FeatureData) DoubleArrayList(com.carrotsearch.hppc.DoubleArrayList) DateHistogramInterval(org.opensearch.search.aggregations.bucket.histogram.DateHistogramInterval) ArrayList(java.util.ArrayList) CompositeAggregationBuilder(org.opensearch.search.aggregations.bucket.composite.CompositeAggregationBuilder) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) EPOCH_MILLIS_FORMAT(org.opensearch.ad.constant.CommonName.EPOCH_MILLIS_FORMAT) AnomalyDetector(org.opensearch.ad.model.AnomalyDetector) SearchResponse(org.opensearch.action.search.SearchResponse) MAX_BATCH_TASK_PIECE_SIZE(org.opensearch.ad.settings.AnomalyDetectorSettings.MAX_BATCH_TASK_PIECE_SIZE) GetAnomalyDetectorResponse(org.opensearch.ad.transport.GetAnomalyDetectorResponse) QueryBuilders(org.opensearch.index.query.QueryBuilders) CommonName(org.opensearch.ad.constant.CommonName) RangeQueryBuilder(org.opensearch.index.query.RangeQueryBuilder) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) GetRequest(org.opensearch.action.get.GetRequest) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) IOException(java.io.IOException) Consumer(java.util.function.Consumer) CompositeValuesSourceBuilder(org.opensearch.search.aggregations.bucket.composite.CompositeValuesSourceBuilder) VALID_AGG_NAME(org.opensearch.search.aggregations.AggregatorFactories.VALID_AGG_NAME) Entity(org.opensearch.ad.model.Entity) AggregationBuilders.dateRange(org.opensearch.search.aggregations.AggregationBuilders.dateRange) User(org.opensearch.commons.authuser.User) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) LogManager(org.apache.logging.log4j.LogManager) QUERY_PARAM_PERIOD_START(org.opensearch.ad.model.AnomalyDetector.QUERY_PARAM_PERIOD_START) GetRequest(org.opensearch.action.get.GetRequest) IndexNotFoundException(org.opensearch.index.IndexNotFoundException)

Example 18 with NamedXContentRegistry

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

the class MetadataIndexTemplateServiceTests method testDefinedTimestampMappingIsAddedForDataStreamTemplates.

public void testDefinedTimestampMappingIsAddedForDataStreamTemplates() throws Exception {
    final MetadataIndexTemplateService service = getMetadataIndexTemplateService();
    ClusterState state = ClusterState.EMPTY_STATE;
    ComponentTemplate ct1 = new ComponentTemplate(new Template(null, new CompressedXContent("{\n" + "      \"properties\": {\n" + "        \"field1\": {\n" + "          \"type\": \"keyword\"\n" + "        }\n" + "      }\n" + "    }"), null), null, null);
    state = service.addComponentTemplate(state, true, "ct1", ct1);
    {
        ComposableIndexTemplate it = new ComposableIndexTemplate(org.opensearch.common.collect.List.of("logs*"), new Template(null, new CompressedXContent("{\n" + "    \"properties\": {\n" + "      \"field2\": {\n" + "        \"type\": \"integer\"\n" + "      }\n" + "    }\n" + "  }"), null), org.opensearch.common.collect.List.of("ct1"), 0L, 1L, null, new ComposableIndexTemplate.DataStreamTemplate());
        state = service.addIndexTemplateV2(state, true, "logs-data-stream-template", it);
        List<CompressedXContent> mappings = MetadataIndexTemplateService.collectMappings(state, "logs-data-stream-template", DataStream.getDefaultBackingIndexName("logs", 1L));
        assertNotNull(mappings);
        assertThat(mappings.size(), equalTo(4));
        List<Map<String, Object>> parsedMappings = mappings.stream().map(m -> {
            try {
                return MapperService.parseMapping(new NamedXContentRegistry(org.opensearch.common.collect.List.of()), m.string());
            } catch (Exception e) {
                logger.error(e);
                fail("failed to parse mappings: " + m.string());
                return null;
            }
        }).collect(Collectors.toList());
        Map<String, Object> firstParsedMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of(TIMESTAMP_FIELD.getName(), org.opensearch.common.collect.Map.of("type", "date"))));
        assertThat(parsedMappings.get(0), equalTo(firstParsedMapping));
        Map<String, Object> secondMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of("field1", org.opensearch.common.collect.Map.of("type", "keyword"))));
        assertThat(parsedMappings.get(1), equalTo(secondMapping));
        Map<String, Object> thirdMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of("field2", org.opensearch.common.collect.Map.of("type", "integer"))));
        assertThat(parsedMappings.get(2), equalTo(thirdMapping));
    }
    {
        // indices matched by templates without the data stream field defined don't get the default @timestamp mapping
        ComposableIndexTemplate it = new ComposableIndexTemplate(org.opensearch.common.collect.List.of("timeseries*"), new Template(null, new CompressedXContent("{\n" + "    \"properties\": {\n" + "      \"field2\": {\n" + "        \"type\": \"integer\"\n" + "      }\n" + "    }\n" + "  }"), null), org.opensearch.common.collect.List.of("ct1"), 0L, 1L, null, null);
        state = service.addIndexTemplateV2(state, true, "timeseries-template", it);
        List<CompressedXContent> mappings = MetadataIndexTemplateService.collectMappings(state, "timeseries-template", "timeseries");
        assertNotNull(mappings);
        assertThat(mappings.size(), equalTo(2));
        List<Map<String, Object>> parsedMappings = mappings.stream().map(m -> {
            try {
                return MapperService.parseMapping(new NamedXContentRegistry(org.opensearch.common.collect.List.of()), m.string());
            } catch (Exception e) {
                logger.error(e);
                fail("failed to parse mappings: " + m.string());
                return null;
            }
        }).collect(Collectors.toList());
        Map<String, Object> firstMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of("field1", org.opensearch.common.collect.Map.of("type", "keyword"))));
        assertThat(parsedMappings.get(0), equalTo(firstMapping));
        Map<String, Object> secondMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of("field2", org.opensearch.common.collect.Map.of("type", "integer"))));
        assertThat(parsedMappings.get(1), equalTo(secondMapping));
        // a default @timestamp mapping will not be added if the matching template doesn't have the data stream field configured, even
        // if the index name matches that of a data stream backing index
        mappings = MetadataIndexTemplateService.collectMappings(state, "timeseries-template", DataStream.getDefaultBackingIndexName("timeseries", 1L));
        assertNotNull(mappings);
        assertThat(mappings.size(), equalTo(2));
        parsedMappings = mappings.stream().map(m -> {
            try {
                return MapperService.parseMapping(new NamedXContentRegistry(org.opensearch.common.collect.List.of()), m.string());
            } catch (Exception e) {
                logger.error(e);
                fail("failed to parse mappings: " + m.string());
                return null;
            }
        }).collect(Collectors.toList());
        firstMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of("field1", org.opensearch.common.collect.Map.of("type", "keyword"))));
        assertThat(parsedMappings.get(0), equalTo(firstMapping));
        secondMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of("field2", org.opensearch.common.collect.Map.of("type", "integer"))));
        assertThat(parsedMappings.get(1), equalTo(secondMapping));
    }
}
Also used : Arrays(java.util.Arrays) OpenSearchSingleNodeTestCase(org.opensearch.test.OpenSearchSingleNodeTestCase) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) TIMESTAMP_FIELD(org.opensearch.index.mapper.DataStreamFieldMapper.Defaults.TIMESTAMP_FIELD) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) Collections.singletonList(java.util.Collections.singletonList) XContentParser(org.opensearch.common.xcontent.XContentParser) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) MapperService(org.opensearch.index.mapper.MapperService) Alias(org.opensearch.action.admin.indices.alias.Alias) Settings.builder(org.opensearch.common.settings.Settings.builder) Map(java.util.Map) XContentFactory(org.opensearch.common.xcontent.XContentFactory) ActionListener(org.opensearch.action.ActionListener) TimeValue(org.opensearch.common.unit.TimeValue) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Index(org.opensearch.index.Index) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) IndicesService(org.opensearch.indices.IndicesService) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) PutRequest(org.opensearch.cluster.metadata.MetadataIndexTemplateService.PutRequest) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ShardLimitValidatorTests.createTestShardLimitService(org.opensearch.indices.ShardLimitValidatorTests.createTestShardLimitService) Matchers.contains(org.hamcrest.Matchers.contains) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.is(org.hamcrest.Matchers.is) IndexTemplateMissingException(org.opensearch.indices.IndexTemplateMissingException) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) CompressedXContent(org.opensearch.common.compress.CompressedXContent) CoreMatchers.not(org.hamcrest.CoreMatchers.not) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Matchers.matchesRegex(org.hamcrest.Matchers.matchesRegex) ClusterState(org.opensearch.cluster.ClusterState) Environment(org.opensearch.env.Environment) Matchers.empty(org.hamcrest.Matchers.empty) IOException(java.io.IOException) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) TimeUnit(java.util.concurrent.TimeUnit) SystemIndices(org.opensearch.indices.SystemIndices) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) InvalidIndexTemplateException(org.opensearch.indices.InvalidIndexTemplateException) CoreMatchers.containsStringIgnoringCase(org.hamcrest.CoreMatchers.containsStringIgnoringCase) Collections(java.util.Collections) ClusterState(org.opensearch.cluster.ClusterState) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) IndexTemplateMissingException(org.opensearch.indices.IndexTemplateMissingException) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) IOException(java.io.IOException) InvalidIndexTemplateException(org.opensearch.indices.InvalidIndexTemplateException) CompressedXContent(org.opensearch.common.compress.CompressedXContent) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) ArrayList(java.util.ArrayList) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) Map(java.util.Map) HashMap(java.util.HashMap)

Example 19 with NamedXContentRegistry

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

the class MetadataIndexTemplateServiceTests method testUserDefinedMappingTakesPrecedenceOverDefault.

public void testUserDefinedMappingTakesPrecedenceOverDefault() throws Exception {
    final MetadataIndexTemplateService service = getMetadataIndexTemplateService();
    ClusterState state = ClusterState.EMPTY_STATE;
    {
        // user defines a @timestamp mapping as part of a component template
        ComponentTemplate ct1 = new ComponentTemplate(new Template(null, new CompressedXContent("{\n" + "      \"properties\": {\n" + "        \"@timestamp\": {\n" + "          \"type\": \"date_nanos\"\n" + "        }\n" + "      }\n" + "    }"), null), null, null);
        state = service.addComponentTemplate(state, true, "ct1", ct1);
        ComposableIndexTemplate it = new ComposableIndexTemplate(org.opensearch.common.collect.List.of("logs*"), null, org.opensearch.common.collect.List.of("ct1"), 0L, 1L, null, new ComposableIndexTemplate.DataStreamTemplate());
        state = service.addIndexTemplateV2(state, true, "logs-template", it);
        List<CompressedXContent> mappings = MetadataIndexTemplateService.collectMappings(state, "logs-template", DataStream.getDefaultBackingIndexName("logs", 1L));
        assertNotNull(mappings);
        assertThat(mappings.size(), equalTo(3));
        List<Map<String, Object>> parsedMappings = mappings.stream().map(m -> {
            try {
                return MapperService.parseMapping(new NamedXContentRegistry(org.opensearch.common.collect.List.of()), m.string());
            } catch (Exception e) {
                logger.error(e);
                fail("failed to parse mappings: " + m.string());
                return null;
            }
        }).collect(Collectors.toList());
        Map<String, Object> firstMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of(TIMESTAMP_FIELD.getName(), org.opensearch.common.collect.Map.of("type", "date"))));
        assertThat(parsedMappings.get(0), equalTo(firstMapping));
        Map<String, Object> secondMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of(TIMESTAMP_FIELD.getName(), org.opensearch.common.collect.Map.of("type", "date_nanos"))));
        assertThat(parsedMappings.get(1), equalTo(secondMapping));
    }
    {
        // user defines a @timestamp mapping as part of a composable index template
        Template template = new Template(null, new CompressedXContent("{\n" + "      \"properties\": {\n" + "        \"@timestamp\": {\n" + "          \"type\": \"date_nanos\"\n" + "        }\n" + "      }\n" + "    }"), null);
        ComposableIndexTemplate it = new ComposableIndexTemplate(org.opensearch.common.collect.List.of("timeseries*"), template, null, 0L, 1L, null, new ComposableIndexTemplate.DataStreamTemplate());
        state = service.addIndexTemplateV2(state, true, "timeseries-template", it);
        List<CompressedXContent> mappings = MetadataIndexTemplateService.collectMappings(state, "timeseries-template", DataStream.getDefaultBackingIndexName("timeseries-template", 1L));
        assertNotNull(mappings);
        assertThat(mappings.size(), equalTo(3));
        List<Map<String, Object>> parsedMappings = mappings.stream().map(m -> {
            try {
                return MapperService.parseMapping(new NamedXContentRegistry(org.opensearch.common.collect.List.of()), m.string());
            } catch (Exception e) {
                logger.error(e);
                fail("failed to parse mappings: " + m.string());
                return null;
            }
        }).collect(Collectors.toList());
        Map<String, Object> firstMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of(TIMESTAMP_FIELD.getName(), org.opensearch.common.collect.Map.of("type", "date"))));
        assertThat(parsedMappings.get(0), equalTo(firstMapping));
        Map<String, Object> secondMapping = org.opensearch.common.collect.Map.of("_doc", org.opensearch.common.collect.Map.of("properties", org.opensearch.common.collect.Map.of(TIMESTAMP_FIELD.getName(), org.opensearch.common.collect.Map.of("type", "date_nanos"))));
        assertThat(parsedMappings.get(1), equalTo(secondMapping));
    }
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) IndexTemplateMissingException(org.opensearch.indices.IndexTemplateMissingException) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) IOException(java.io.IOException) InvalidIndexTemplateException(org.opensearch.indices.InvalidIndexTemplateException) CompressedXContent(org.opensearch.common.compress.CompressedXContent) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) ArrayList(java.util.ArrayList) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) Map(java.util.Map) HashMap(java.util.HashMap)

Example 20 with NamedXContentRegistry

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

the class MetadataIndexTemplateServiceTests method assertTemplatesEqual.

@SuppressWarnings("unchecked")
public static void assertTemplatesEqual(ComposableIndexTemplate actual, ComposableIndexTemplate expected) {
    ComposableIndexTemplate actualNoTemplate = new ComposableIndexTemplate(actual.indexPatterns(), null, actual.composedOf(), actual.priority(), actual.version(), actual.metadata(), actual.getDataStreamTemplate());
    ComposableIndexTemplate expectedNoTemplate = new ComposableIndexTemplate(expected.indexPatterns(), null, expected.composedOf(), expected.priority(), expected.version(), expected.metadata(), expected.getDataStreamTemplate());
    assertThat(actualNoTemplate, equalTo(expectedNoTemplate));
    Template actualTemplate = actual.template();
    Template expectedTemplate = expected.template();
    assertThat("expected both templates to have either a template or no template", Objects.nonNull(actualTemplate), equalTo(Objects.nonNull(expectedTemplate)));
    if (actualTemplate != null) {
        assertThat(actualTemplate.settings(), equalTo(expectedTemplate.settings()));
        assertThat(actualTemplate.aliases(), equalTo(expectedTemplate.aliases()));
        assertThat("expected both templates to have either mappings or no mappings", Objects.nonNull(actualTemplate.mappings()), equalTo(Objects.nonNull(expectedTemplate.mappings())));
        if (actualTemplate.mappings() != null) {
            Map<String, Object> actualMappings;
            Map<String, Object> expectedMappings;
            try (XContentParser parser = XContentType.JSON.xContent().createParser(new NamedXContentRegistry(Collections.emptyList()), LoggingDeprecationHandler.INSTANCE, actualTemplate.mappings().string())) {
                actualMappings = parser.map();
            } catch (IOException e) {
                throw new AssertionError(e);
            }
            try (XContentParser parser = XContentType.JSON.xContent().createParser(new NamedXContentRegistry(Collections.emptyList()), LoggingDeprecationHandler.INSTANCE, expectedTemplate.mappings().string())) {
                expectedMappings = parser.map();
            } catch (IOException e) {
                throw new AssertionError(e);
            }
            if (actualMappings.size() == 1 && actualMappings.containsKey(MapperService.SINGLE_MAPPING_NAME)) {
                actualMappings = (Map<String, Object>) actualMappings.get(MapperService.SINGLE_MAPPING_NAME);
            }
            if (expectedMappings.size() == 1 && expectedMappings.containsKey(MapperService.SINGLE_MAPPING_NAME)) {
                expectedMappings = (Map<String, Object>) expectedMappings.get(MapperService.SINGLE_MAPPING_NAME);
            }
            assertThat(actualMappings, equalTo(expectedMappings));
        }
    }
}
Also used : CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) IOException(java.io.IOException) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) XContentParser(org.opensearch.common.xcontent.XContentParser)

Aggregations

NamedXContentRegistry (org.opensearch.common.xcontent.NamedXContentRegistry)32 SearchModule (org.opensearch.search.SearchModule)16 NamedWriteableRegistry (org.opensearch.common.io.stream.NamedWriteableRegistry)13 XContentParser (org.opensearch.common.xcontent.XContentParser)11 ArrayList (java.util.ArrayList)10 Map (java.util.Map)10 BeforeClass (org.junit.BeforeClass)10 Settings (org.opensearch.common.settings.Settings)10 IOException (java.io.IOException)9 HashMap (java.util.HashMap)9 List (java.util.List)8 ClusterService (org.opensearch.cluster.service.ClusterService)7 HashSet (java.util.HashSet)6 Set (java.util.Set)6 ActionListener (org.opensearch.action.ActionListener)6 ClusterState (org.opensearch.cluster.ClusterState)5 Arrays (java.util.Arrays)4 Collections (java.util.Collections)4 Collections.singletonList (java.util.Collections.singletonList)4 Objects (java.util.Objects)4