From bd52fb446635a5cb3571a6ca54a2084ea440f267 Mon Sep 17 00:00:00 2001 From: Nick Knize Date: Wed, 9 Aug 2023 15:10:55 -0500 Subject: [PATCH] [Refactor] From XContentType.JSON to MediaTypeRegistry.JSON (#9156) This commit rote refactors nearly all instances and usages of the XContentType.JSON singleton instance defined in the :libs:opensearch-x-content library to the MediaTypeRegistry.JSON singleton instance defined in :libs:opensearch-core. This decouples the server and test implementations from the x-content library such that foundation classes can be further refactored from the :server module to the :opensearch-core library without requiring a strict dependency on the x-content library. This keeps opensearch-core library loosely coupled with the remaining :libs:opensearch-* libraries such that serverless and cloud-native implementations can selective import only the libraries needed for implementation. Signed-off-by: Nicholas Walter Knize Signed-off-by: Kaushal Kumar --- .../opensearch/client/RequestConverters.java | 22 +++-- .../indices/GetFieldMappingsResponse.java | 4 +- .../indices/PutIndexTemplateRequest.java | 8 +- .../client/slm/SnapshotLifecyclePolicy.java | 4 +- .../slm/SnapshotLifecyclePolicyMetadata.java | 4 +- .../client/slm/SnapshotLifecycleStats.java | 4 +- .../slm/SnapshotRetentionConfiguration.java | 4 +- .../forbidden/rest-high-level-signatures.txt | 2 +- .../opensearch/client/BulkProcessorIT.java | 16 ++-- .../client/BulkProcessorRetryIT.java | 4 +- .../BulkRequestWithGlobalParametersIT.java | 30 +++---- .../opensearch/client/ClusterClientIT.java | 4 +- .../java/org/opensearch/client/CrudIT.java | 57 ++++++------ .../CustomRestHighLevelClientTests.java | 6 +- .../opensearch/client/IndicesClientIT.java | 10 +-- .../client/IndicesRequestConvertersTests.java | 4 +- .../client/IngestRequestConvertersTests.java | 6 +- ...OpenSearchRestHighLevelClientTestCase.java | 3 +- .../java/org/opensearch/client/ReindexIT.java | 26 +++--- .../client/RequestConvertersTests.java | 87 +++++++++--------- .../client/RestHighLevelClientTests.java | 2 +- .../java/org/opensearch/client/SearchIT.java | 4 +- .../org/opensearch/client/SnapshotIT.java | 4 +- .../opensearch/client/StoredScriptsIT.java | 32 +++++-- .../java/org/opensearch/client/TasksIT.java | 6 +- .../opensearch/client/UpdateByQueryIT.java | 16 ++-- .../documentation/CRUDDocumentationIT.java | 24 ++--- .../ClusterClientDocumentationIT.java | 4 +- .../IndicesClientDocumentationIT.java | 27 +++--- .../IngestClientDocumentationIT.java | 10 +-- .../documentation/SearchDocumentationIT.java | 50 ++++++----- .../SnapshotClientDocumentationIT.java | 6 +- .../StoredScriptsDocumentationIT.java | 20 +++-- .../GetIndexTemplatesResponseTests.java | 4 +- .../opensearch/test/rest/NodeRestUsageIT.java | 9 +- .../core/xcontent/MapXContentParser.java | 8 +- .../core/xcontent/XContentHelper.java | 53 +++++++++++ .../core/xcontent/XContentParser.java | 4 +- ...ultShardOperationFailedExceptionTests.java | 9 +- .../common/xcontent/ObjectParserTests.java | 9 +- .../ingest/common/IngestRestartIT.java | 14 +-- .../ingest/common/ScriptProcessor.java | 4 +- .../ingest/common/JsonProcessorTests.java | 4 +- .../geoip/GeoIpProcessorNonIngestNodeIT.java | 4 +- .../script/expression/StoredExpressionIT.java | 6 +- .../script/mustache/SearchTemplateIT.java | 52 ++++++----- .../mustache/CustomMustacheFactory.java | 4 +- .../mustache/MultiSearchTemplateResponse.java | 4 +- .../mustache/SearchTemplateResponse.java | 5 +- .../TransportSearchTemplateAction.java | 5 +- .../MultiSearchTemplateRequestTests.java | 18 ++-- .../mustache/SearchTemplateResponseTests.java | 2 +- .../action/PainlessExecuteApiTests.java | 10 +-- .../index/mapper/BWCTemplateTests.java | 8 +- .../RankFeatureMetaFieldMapperTests.java | 3 +- .../mapper/ScaledFloatFieldMapperTests.java | 20 ++--- .../SearchAsYouTypeFieldMapperTests.java | 6 +- .../mapper/ParentJoinFieldMapperTests.java | 38 +++++--- .../percolator/PercolatorQuerySearchIT.java | 83 +++++++++-------- .../percolator/PercolateQueryBuilder.java | 10 +-- .../PercolateQueryBuilderTests.java | 10 +-- .../PercolateWithNestedQueryBuilderTests.java | 10 ++- .../PercolatorFieldMapperTests.java | 36 ++++---- .../PercolatorQuerySearchTests.java | 14 +-- .../index/rankeval/RankEvalResponse.java | 4 +- .../index/rankeval/RankEvalSpec.java | 4 +- .../index/rankeval/RatedDocument.java | 4 +- .../index/rankeval/RatedRequest.java | 4 +- .../rankeval/TransportRankEvalAction.java | 4 +- .../DiscountedCumulativeGainTests.java | 4 +- .../index/rankeval/EvalQueryQualityTests.java | 2 +- .../index/rankeval/RankEvalResponseTests.java | 4 +- .../reindex/AsyncBulkByScrollActionTests.java | 4 +- .../opensearch/index/reindex/CancelTests.java | 6 +- .../index/reindex/RestReindexActionTests.java | 6 +- .../common/SearchPipelineCommonIT.java | 4 +- .../common/FilterQueryRequestProcessor.java | 4 +- .../common/ScriptRequestProcessor.java | 4 +- .../ICUCollationKeywordFieldMapperIT.java | 70 ++++++++++----- .../plugin/correlation/utils/IndexUtils.java | 6 +- .../query/CorrelationQueryBuilderTests.java | 4 +- .../index/mapper/size/SizeMappingIT.java | 4 +- .../index/mapper/size/SizeMappingTests.java | 8 +- .../repositories/gcs/TestUtils.java | 4 +- .../upgrades/FullClusterRestartIT.java | 5 +- .../java/org/opensearch/search/CCSDuelIT.java | 14 +-- .../org/opensearch/upgrades/RecoveryIT.java | 3 +- .../http/SearchRestCancellationIT.java | 15 ++-- .../cluster/node/tasks/AbstractTasksIT.java | 4 +- .../admin/cluster/node/tasks/TasksIT.java | 8 +- .../admin/indices/create/CloneIndexIT.java | 6 +- .../admin/indices/create/ShrinkIndexIT.java | 24 ++--- .../admin/indices/create/SplitIndexIT.java | 12 +-- .../datastream/DataStreamTestCase.java | 4 +- .../indices/datastream/DataStreamUsageIT.java | 11 ++- .../action/bulk/BulkIntegrationIT.java | 12 +-- .../bulk/BulkProcessorClusterSettingsIT.java | 8 +- .../action/bulk/BulkWithUpdatesIT.java | 26 +++--- .../action/ingest/AsyncIngestProcessorIT.java | 6 +- .../support/WaitActiveShardCountIT.java | 12 +-- .../opensearch/aliases/IndexAliasesIT.java | 89 ++++++++++--------- .../opensearch/cluster/SimpleDataNodesIT.java | 9 +- .../cluster/routing/PrimaryAllocationIT.java | 4 +- .../ClusterDisruptionCleanSettingsIT.java | 4 +- .../discovery/ClusterDisruptionIT.java | 12 ++- .../discovery/ClusterManagerDisruptionIT.java | 8 +- .../document/DocumentActionsIT.java | 4 +- .../org/opensearch/document/ShardInfoIT.java | 12 +-- .../java/org/opensearch/get/GetActionIT.java | 16 ++-- .../org/opensearch/index/FinalPipelineIT.java | 46 +++++++--- .../index/IndexRequestBuilderIT.java | 10 +-- .../index/engine/MaxDocsLimitIT.java | 4 +- .../index/seqno/GlobalCheckpointSyncIT.java | 10 +-- .../shard/GlobalCheckpointListenersIT.java | 4 +- .../opensearch/index/shard/IndexShardIT.java | 46 +++++----- .../opensearch/index/shard/SearchIdleIT.java | 12 +-- ...DateMathIndexExpressionsIntegrationIT.java | 14 +-- .../mapping/UpdateMappingIntegrationIT.java | 16 ++-- .../indices/recovery/IndexRecoveryIT.java | 23 ++--- .../indices/stats/IndexStatsIT.java | 9 +- .../template/SimpleIndexTemplateIT.java | 18 ++-- .../org/opensearch/ingest/IngestClientIT.java | 36 ++++---- ...gestProcessorNotInstalledOnAllNodesIT.java | 8 +- .../org/opensearch/mget/SimpleMgetIT.java | 4 +- .../org/opensearch/recovery/RelocationIT.java | 8 +- .../opensearch/recovery/SimpleRecoveryIT.java | 6 +- .../remotestore/PrimaryTermValidationIT.java | 4 +- .../RemoteStoreBackpressureIT.java | 4 +- .../opensearch/script/StoredScriptsIT.java | 13 ++- .../search/SearchCancellationIT.java | 6 +- .../search/aggregations/bucket/NestedIT.java | 6 +- .../SignificantTermsSignificanceScoreIT.java | 4 +- .../bucket/TermsShardMinDocCountIT.java | 8 +- .../metrics/ScriptedMetricIT.java | 10 +-- .../aggregations/pipeline/BucketScriptIT.java | 4 +- .../pipeline/BucketSelectorIT.java | 4 +- .../aggregations/pipeline/MaxBucketIT.java | 6 +- .../fetch/subphase/MatchedQueriesIT.java | 8 +- .../search/fields/SearchFieldsIT.java | 16 ++-- .../opensearch/search/geo/GeoFilterIT.java | 10 +-- .../search/geo/GeoShapeIntegrationIT.java | 10 +-- .../geo/LegacyGeoShapeIntegrationIT.java | 4 +- .../search/msearch/MultiSearchIT.java | 4 +- .../search/nested/SimpleNestedIT.java | 10 +-- .../search/preference/SearchPreferenceIT.java | 4 +- .../search/query/QueryStringIT.java | 8 +- .../search/query/SearchQueryIT.java | 6 +- .../search/query/SimpleQueryStringIT.java | 22 ++--- .../search/simple/SimpleSearchIT.java | 28 +++--- .../opensearch/search/sort/FieldSortIT.java | 12 +-- .../SnapshotCustomPluginStateIT.java | 6 +- .../cluster/health/ClusterHealthResponse.java | 4 +- .../tasks/cancel/CancelTasksResponse.java | 4 +- .../node/tasks/get/GetTaskResponse.java | 4 +- .../node/tasks/list/ListTasksResponse.java | 4 +- .../restore/RestoreRemoteStoreRequest.java | 4 +- .../stats/RemoteStoreStatsResponse.java | 4 +- .../put/PutRepositoryRequest.java | 8 +- .../verify/VerifyRepositoryResponse.java | 4 +- .../settings/ClusterGetSettingsResponse.java | 4 +- .../ClusterUpdateSettingsRequest.java | 10 +-- .../snapshots/clone/CloneSnapshotRequest.java | 4 +- .../create/CreateSnapshotRequest.java | 3 +- .../snapshots/get/GetSnapshotsResponse.java | 4 +- .../restore/RestoreSnapshotRequest.java | 3 +- .../snapshots/status/SnapshotStats.java | 4 +- .../snapshots/status/SnapshotStatus.java | 4 +- .../admin/cluster/stats/AnalysisStats.java | 4 +- .../admin/cluster/stats/MappingStats.java | 4 +- .../storedscripts/PutStoredScriptRequest.java | 6 +- .../PutStoredScriptRequestBuilder.java | 6 +- .../indices/alias/IndicesAliasesRequest.java | 5 +- .../admin/indices/analyze/AnalyzeAction.java | 4 +- .../indices/close/CloseIndexResponse.java | 10 +-- .../indices/create/CreateIndexRequest.java | 2 +- .../create/CreateIndexRequestBuilder.java | 12 +-- .../admin/indices/get/GetIndexResponse.java | 4 +- .../mapping/get/GetFieldMappingsResponse.java | 6 +- .../mapping/get/GetMappingsResponse.java | 4 +- .../TransportGetFieldMappingsIndexAction.java | 6 +- .../mapping/put/PutMappingRequest.java | 9 +- .../mapping/put/PutMappingRequestBuilder.java | 6 +- .../readonly/AddIndexBlockResponse.java | 10 +-- .../indices/recovery/RecoveryResponse.java | 4 +- .../SegmentReplicationStatsResponse.java | 4 +- .../admin/indices/rollover/RolloverInfo.java | 4 +- .../settings/put/UpdateSettingsRequest.java | 9 +- .../indices/stats/IndicesStatsResponse.java | 4 +- .../template/put/PutIndexTemplateRequest.java | 12 +-- .../put/PutIndexTemplateRequestBuilder.java | 19 ++-- .../action/bulk/BulkItemRequest.java | 4 +- .../action/bulk/BulkItemResponse.java | 4 +- .../opensearch/action/bulk/BulkProcessor.java | 11 +-- .../action/bulk/BulkRequestParser.java | 3 +- .../action/fieldcaps/FieldCapabilities.java | 4 +- .../fieldcaps/FieldCapabilitiesResponse.java | 4 +- .../opensearch/action/get/GetResponse.java | 4 +- .../action/get/MultiGetRequest.java | 4 +- .../action/index/IndexRequestBuilder.java | 28 +++--- .../action/index/IndexResponse.java | 4 +- .../action/ingest/GetPipelineResponse.java | 4 +- .../ingest/PutPipelineRequestBuilder.java | 6 +- .../SimulatePipelineRequestBuilder.java | 6 +- .../search/GetSearchPipelineResponse.java | 4 +- .../action/search/MultiSearchResponse.java | 4 +- .../action/search/SearchResponse.java | 4 +- .../support/replication/ReplicationTask.java | 4 +- .../action/update/UpdateHelper.java | 9 +- .../action/update/UpdateRequest.java | 41 +++++---- .../action/update/UpdateRequestBuilder.java | 40 ++++----- .../opensearch/client/ClusterAdminClient.java | 6 +- .../java/org/opensearch/client/Requests.java | 4 +- .../client/support/AbstractClient.java | 10 +-- .../cluster/RepositoryCleanupInProgress.java | 4 +- .../cluster/SnapshotsInProgress.java | 4 +- .../action/index/MappingUpdatedAction.java | 4 +- .../ClusterAwarenessAttributeValueHealth.java | 4 +- .../ClusterAwarenessAttributesHealth.java | 4 +- .../cluster/coordination/Coordinator.java | 14 +-- .../DecommissionAttributeMetadata.java | 4 +- .../cluster/health/ClusterShardHealth.java | 4 +- .../cluster/metadata/AliasMetadata.java | 3 +- .../cluster/metadata/ComponentTemplate.java | 4 +- .../metadata/ComponentTemplateMetadata.java | 4 +- .../metadata/ComposableIndexTemplate.java | 4 +- .../ComposableIndexTemplateMetadata.java | 4 +- .../cluster/metadata/DataStreamMetadata.java | 4 +- .../MetadataIndexTemplateService.java | 4 +- .../metadata/RepositoriesMetadata.java | 4 +- .../metadata/TemplateUpgradeService.java | 11 ++- .../metadata/WeightedRoutingMetadata.java | 4 +- .../command/AllocationCommands.java | 4 +- .../common/geo/builders/ShapeBuilder.java | 4 +- .../opensearch/common/settings/Setting.java | 8 +- .../opensearch/common/settings/Settings.java | 16 ++-- .../common/settings/SettingsModule.java | 4 +- .../xcontent/JsonToStringXContentParser.java | 8 +- .../common/xcontent/XContentHelper.java | 61 +++++-------- .../org/opensearch/index/get/GetResult.java | 4 +- .../mapper/AbstractGeometryFieldMapper.java | 4 +- .../index/mapper/DocumentMapper.java | 6 +- .../index/mapper/DocumentMapperParser.java | 4 +- .../index/mapper/GeoShapeParser.java | 4 +- .../index/mapper/MapperService.java | 8 +- .../index/mapper/RootObjectMapper.java | 4 +- .../index/query/AbstractQueryBuilder.java | 4 +- .../index/query/InnerHitBuilder.java | 4 +- .../index/query/MoreLikeThisQueryBuilder.java | 3 +- .../index/query/SpanNearQueryBuilder.java | 4 +- .../index/reindex/BulkByScrollTask.java | 6 +- .../index/reindex/ScrollableHitSource.java | 4 +- .../index/search/stats/SearchStats.java | 4 +- .../index/shard/PrimaryReplicaSyncer.java | 4 +- .../RemoveCorruptedShardDataCommand.java | 4 +- .../index/translog/TranslogStats.java | 4 +- .../opensearch/indices/IndicesService.java | 3 +- .../opensearch/ingest/ConfigurationUtils.java | 4 +- .../ingest/PipelineConfiguration.java | 3 +- .../PersistentTasksCustomMetadata.java | 6 +- .../PersistentTasksNodeService.java | 4 +- .../repositories/RepositoryCleanupResult.java | 4 +- .../repositories/RepositoryInfo.java | 4 +- .../repositories/RepositoryStatsSnapshot.java | 4 +- .../blobstore/BlobStoreRepository.java | 6 +- .../org/opensearch/rest/RestController.java | 3 +- .../java/org/opensearch/rest/RestRequest.java | 8 +- .../opensearch/rest/action/cat/RestTable.java | 4 +- .../java/org/opensearch/script/Script.java | 3 +- .../opensearch/script/StoredScriptSource.java | 4 +- .../java/org/opensearch/search/SearchHit.java | 6 +- .../aggregations/AggregationBuilder.java | 4 +- .../aggregations/AggregatorFactories.java | 4 +- .../search/aggregations/BucketOrder.java | 4 +- .../aggregations/InternalAggregation.java | 4 +- .../PipelineAggregationBuilder.java | 4 +- .../BaseMultiValuesSourceFieldConfig.java | 4 +- .../search/builder/SearchSourceBuilder.java | 6 +- .../highlight/AbstractHighlighterBuilder.java | 4 +- .../pipeline/PipelineConfiguration.java | 3 +- .../search/rescore/RescorerBuilder.java | 4 +- .../opensearch/search/slice/SliceBuilder.java | 4 +- .../opensearch/search/sort/SortBuilder.java | 4 +- .../opensearch/search/suggest/Suggest.java | 4 +- .../search/suggest/SuggestBuilder.java | 4 +- .../CompletionSuggestionBuilder.java | 10 +-- .../org/opensearch/snapshots/RestoreInfo.java | 4 +- .../org/opensearch/tasks/RawTaskStatus.java | 3 +- .../java/org/opensearch/tasks/TaskInfo.java | 4 +- .../opensearch/tasks/TaskResourceStats.java | 4 +- .../opensearch/tasks/TaskResourceUsage.java | 4 +- .../java/org/opensearch/tasks/TaskResult.java | 5 +- .../opensearch/tasks/TaskResultsService.java | 3 +- .../org/opensearch/tasks/TaskThreadUsage.java | 4 +- .../ExceptionSerializationTests.java | 6 +- .../opensearch/OpenSearchExceptionTests.java | 3 +- .../RenamedTimeoutRequestParameterTests.java | 4 +- .../node/tasks/TransportTasksActionTests.java | 5 +- .../RestoreRemoteStoreRequestTests.java | 4 +- .../ClusterUpdateSettingsRequestTests.java | 13 +-- ...ClusterPutWeightedRoutingRequestTests.java | 14 +-- .../create/CreateSnapshotRequestTests.java | 4 +- .../restore/RestoreSnapshotRequestTests.java | 4 +- .../cluster/stats/ClusterStatsNodesTests.java | 18 ++-- .../GetStoredScriptResponseTests.java | 4 +- .../PutStoredScriptRequestTests.java | 7 +- .../indices/alias/AliasActionsTests.java | 2 +- .../close/CloseIndexResponseTests.java | 5 +- .../CreateIndexRequestBuilderTests.java | 10 +-- .../create/CreateIndexRequestTests.java | 2 +- .../create/CreateIndexResponseTests.java | 6 +- .../forcemerge/RestForceMergeActionTests.java | 4 +- .../get/GetFieldMappingsResponseTests.java | 4 +- .../mapping/put/PutMappingRequestTests.java | 13 +-- .../rollover/RolloverRequestTests.java | 2 +- .../indices/shrink/ResizeRequestTests.java | 5 +- .../indices/shrink/ResizeResponseTests.java | 4 +- .../indices/stats/IndicesStatsTests.java | 4 +- .../put/PutIndexTemplateRequestTests.java | 4 +- .../query/ValidateQueryResponseTests.java | 4 +- .../action/bulk/BulkProcessorTests.java | 6 +- .../action/bulk/BulkRequestModifierTests.java | 4 +- .../action/bulk/BulkRequestParserTests.java | 40 ++++++--- .../action/bulk/BulkRequestTests.java | 38 ++++---- .../action/bulk/BulkResponseTests.java | 2 +- .../bulk/TransportBulkActionTookTests.java | 4 +- .../action/delete/DeleteResponseTests.java | 5 +- .../action/explain/ExplainResponseTests.java | 3 +- .../MergedFieldCapabilitiesResponseTests.java | 3 +- .../action/get/GetResponseTests.java | 9 +- .../get/TransportMultiGetActionTests.java | 6 +- .../index/IndexRequestBuilderTests.java | 6 +- .../action/index/IndexRequestTests.java | 20 ++--- .../action/index/IndexResponseTests.java | 5 +- .../ingest/PutPipelineRequestTests.java | 11 ++- .../ingest/SimulatePipelineRequestTests.java | 10 +-- .../search/MultiSearchRequestTests.java | 32 +++---- .../SearchPhaseExecutionExceptionTests.java | 3 +- .../action/search/SearchResponseTests.java | 9 +- .../search/ShardSearchFailureTests.java | 7 +- .../replication/ReplicationResponseTests.java | 7 +- .../termvectors/TermVectorsUnitTests.java | 10 +-- .../TransportMultiTermVectorsActionTests.java | 6 +- .../action/update/UpdateRequestTests.java | 11 +-- .../action/update/UpdateResponseTests.java | 31 +++---- .../client/AbstractClientHeadersTestCase.java | 4 +- .../cluster/metadata/IndexGraveyardTests.java | 4 +- .../cluster/metadata/IndexMetadataTests.java | 6 +- .../metadata/IndexTemplateMetadataTests.java | 14 +-- .../MetadataIndexTemplateServiceTests.java | 6 +- .../ClusterStateToStringTests.java | 4 +- .../common/geo/GeoJsonSerializationTests.java | 4 +- .../common/settings/SettingsTests.java | 13 +-- .../common/xcontent/XContentFactoryTests.java | 15 ++-- .../xcontent/XContentParserUtilsTests.java | 5 +- .../common/xcontent/XContentTypeTests.java | 19 ++-- .../builder/XContentBuilderTests.java | 50 +++++------ .../common/xcontent/cbor/JsonVsCborTests.java | 3 +- .../xcontent/smile/JsonVsSmileTests.java | 3 +- .../xcontent/support/XContentHelperTests.java | 5 +- .../support/XContentMapValuesTests.java | 2 +- .../rest/ExtensionRestRequestTests.java | 7 +- .../rest/ExtensionRestResponseTests.java | 4 +- .../RestInitializeExtensionActionTests.java | 10 +-- .../opensearch/index/IndexServiceTests.java | 20 +++-- .../index/IndexingSlowLogTests.java | 8 +- .../index/engine/InternalEngineTests.java | 4 +- .../fielddata/BinaryDVFieldDataTests.java | 10 +-- .../index/get/DocumentFieldTests.java | 18 ++-- .../opensearch/index/get/GetResultTests.java | 38 ++++---- .../mapper/CompletionFieldMapperTests.java | 4 +- .../mapper/DataStreamFieldMapperTests.java | 12 +-- .../index/mapper/DocumentParserTests.java | 10 +-- .../index/mapper/DynamicMappingTests.java | 20 ++--- .../mapper/FieldFilterMapperPluginTests.java | 4 +- .../mapper/FieldNamesFieldMapperTests.java | 8 +- .../mapper/FlatObjectFieldDataTests.java | 4 +- .../GenericStoreDynamicTemplateTests.java | 8 +- .../mapper/GeoShapeFieldMapperTests.java | 4 +- .../index/mapper/IdFieldMapperTests.java | 6 +- .../index/mapper/IndexFieldMapperTests.java | 4 +- .../index/mapper/IpRangeFieldMapperTests.java | 4 +- .../mapper/JavaMultiFieldMergeTests.java | 10 +-- .../LegacyGeoShapeFieldMapperTests.java | 14 +-- .../index/mapper/MultiFieldTests.java | 6 +- .../index/mapper/NestedObjectMapperTests.java | 36 ++++---- .../mapper/NestedPathFieldMapperTests.java | 4 +- .../mapper/NullValueObjectMappingTests.java | 8 +- .../index/mapper/NumberFieldMapperTests.java | 4 +- .../index/mapper/NumberFieldTypeTests.java | 4 +- .../index/mapper/ObjectMapperTests.java | 4 +- .../mapper/PathMatchDynamicTemplateTests.java | 8 +- .../index/mapper/RoutingFieldMapperTests.java | 6 +- .../index/mapper/SourceFieldMapperTests.java | 12 +-- .../mapper/StoredNumericValuesTests.java | 4 +- .../index/query/WrapperQueryBuilderTests.java | 5 +- .../IndexLevelReplicationTests.java | 36 ++++---- .../RecoveryDuringReplicationTests.java | 35 ++++---- .../index/shard/IndexShardTests.java | 22 ++--- .../shard/PrimaryReplicaSyncerTests.java | 6 +- .../index/shard/RefreshListenersTests.java | 13 ++- .../SegmentReplicationIndexShardTests.java | 10 +-- ...licationWithNodeToNodeIndexShardTests.java | 10 +-- .../index/shard/ShardGetServiceTests.java | 10 +-- .../snapshots/blobstore/FileInfoTests.java | 5 +- ...oteStoreShardShallowCopySnapshotTests.java | 5 +- .../index/translog/LocalTranslogTests.java | 4 +- .../translog/TranslogManagerTestCase.java | 4 +- .../IndexingMemoryControllerTests.java | 4 +- .../indices/IndicesRequestCacheTests.java | 16 ++-- ...alStorePeerRecoverySourceHandlerTests.java | 4 +- .../PeerRecoveryTargetServiceTests.java | 4 +- .../indices/recovery/RecoveryTests.java | 14 +-- .../OngoingSegmentReplicationsTests.java | 6 +- .../SegmentReplicationSourceHandlerTests.java | 4 +- .../ingest/IngestMetadataTests.java | 36 ++++---- .../opensearch/ingest/IngestServiceTests.java | 75 ++++++++-------- .../ingest/PipelineConfigurationTests.java | 11 +-- .../persistent/TestPersistentTasksPlugin.java | 4 +- .../repositories/RepositoryDataTests.java | 3 +- .../opensearch/rest/BaseRestHandlerTests.java | 6 +- .../opensearch/rest/RestControllerTests.java | 18 ++-- ...tClusterAddWeightedRoutingActionTests.java | 4 +- ...usterDeleteWeightedRoutingActionTests.java | 6 +- .../RestReloadSecureSettingsActionTests.java | 6 +- .../admin/indices/RestAnalyzeActionTests.java | 4 +- .../indices/RestGetAliasesActionTests.java | 15 ++-- .../indices/RestValidateQueryActionTests.java | 4 +- .../rest/action/cat/RestTableTests.java | 3 +- .../action/document/RestBulkActionTests.java | 4 +- .../action/document/RestIndexActionTests.java | 4 +- .../document/RestUpdateActionTests.java | 4 +- .../script/ScriptContextInfoTests.java | 8 +- .../script/ScriptMetadataTests.java | 48 ++++++---- .../opensearch/script/ScriptServiceTests.java | 12 ++- .../org/opensearch/script/ScriptTests.java | 8 +- .../script/StoredScriptSourceTests.java | 12 +-- .../opensearch/script/StoredScriptTests.java | 49 +++++----- .../org/opensearch/search/SearchHitTests.java | 32 +++---- .../opensearch/search/SearchHitsTests.java | 17 ++-- .../search/SearchSortValuesTests.java | 15 ++-- .../opensearch/search/geo/GeoQueryTests.java | 4 +- .../search/geo/GeoShapeQueryTests.java | 10 +-- .../pipeline/SearchPipelineServiceTests.java | 46 +++++----- .../pipeline/SearchPipelineStatsTests.java | 6 +- .../search/pit/RestDeletePitActionTests.java | 8 +- .../search/profile/ProfileResultTests.java | 2 +- .../SearchProfileShardResultsTests.java | 2 +- .../AggregationProfileShardResultTests.java | 7 +- .../profile/query/CollectorResultTests.java | 2 +- .../query/QueryProfileShardResultTests.java | 2 +- .../scroll/RestClearScrollActionTests.java | 6 +- .../scroll/RestSearchScrollActionTests.java | 6 +- .../searchafter/SearchAfterBuilderTests.java | 2 +- .../search/sort/SortValueTests.java | 4 +- .../CompletionSuggestionOptionTests.java | 5 +- .../search/suggest/SuggestTests.java | 5 +- .../search/suggest/SuggestionEntryTests.java | 9 +- .../search/suggest/SuggestionOptionTests.java | 5 +- .../search/suggest/SuggestionTests.java | 11 +-- .../suggest/TermSuggestionOptionTests.java | 5 +- .../CategoryContextMappingTests.java | 20 ++--- .../completion/GeoContextMappingTests.java | 10 +-- .../SharedSignificantTermsTestMethods.java | 6 +- .../threadpool/ThreadPoolStatsTests.java | 4 +- .../index/engine/EngineTestCase.java | 19 ++-- .../index/mapper/MapperServiceTestCase.java | 6 +- ...enSearchIndexLevelReplicationTestCase.java | 6 +- .../index/shard/IndexShardTestCase.java | 9 +- .../blobstore/BlobStoreTestUtil.java | 4 +- .../search/RandomSearchRequestGenerator.java | 4 +- .../aggregations/BaseAggregationTestCase.java | 4 +- ...ternalSingleBucketAggregationTestCase.java | 2 +- .../AbstractBroadcastResponseTestCase.java | 3 +- .../test/AbstractQueryTestCase.java | 17 ++-- .../test/AbstractSerializingTestCase.java | 3 +- .../test/AbstractXContentTestCase.java | 21 ++--- .../test/InternalAggregationTestCase.java | 2 +- .../test/OpenSearchIntegTestCase.java | 5 +- .../opensearch/test/OpenSearchTestCase.java | 6 +- .../org/opensearch/test/RandomObjects.java | 10 +-- .../test/hamcrest/OpenSearchAssertions.java | 7 +- .../test/rest/OpenSearchRestTestCase.java | 12 +-- .../yaml/ClientYamlTestExecutionContext.java | 6 +- .../rest/yaml/ClientYamlTestResponse.java | 3 +- .../OpenSearchClientYamlSuiteTestCase.java | 4 +- .../test/AbstractXContentTestCaseTests.java | 6 +- .../test/XContentTestUtilsTests.java | 16 ++-- 487 files changed, 2523 insertions(+), 2210 deletions(-) create mode 100644 libs/core/src/main/java/org/opensearch/core/xcontent/XContentHelper.java diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java index c48acfc5b6ece..6bc691a74a2c4 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java @@ -78,9 +78,9 @@ import org.opensearch.common.unit.TimeValue; import org.opensearch.core.common.util.CollectionUtils; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContent; @@ -119,7 +119,7 @@ * @opensearch.api */ final class RequestConverters { - static final XContentType REQUEST_BODY_CONTENT_TYPE = XContentType.JSON; + static final MediaType REQUEST_BODY_CONTENT_TYPE = MediaTypeRegistry.JSON; private RequestConverters() { // Contains only status utility methods @@ -177,7 +177,7 @@ static Request bulk(BulkRequest bulkRequest) throws IOException { } if (bulkContentType == null) { - bulkContentType = XContentType.JSON; + bulkContentType = MediaTypeRegistry.JSON; } final byte separator = bulkContentType.xContent().streamSeparator(); @@ -266,7 +266,12 @@ static Request bulk(BulkRequest bulkRequest) throws IOException { } } } else if (opType == DocWriteRequest.OpType.UPDATE) { - source = XContentHelper.toXContent((UpdateRequest) action, bulkContentType, ToXContent.EMPTY_PARAMS, false).toBytesRef(); + source = org.opensearch.core.xcontent.XContentHelper.toXContent( + (UpdateRequest) action, + bulkContentType, + ToXContent.EMPTY_PARAMS, + false + ).toBytesRef(); } if (source != null) { @@ -821,7 +826,8 @@ static HttpEntity createEntity(ToXContent toXContent, MediaType mediaType) throw } static HttpEntity createEntity(ToXContent toXContent, MediaType mediaType, ToXContent.Params toXContentParams) throws IOException { - BytesRef source = XContentHelper.toXContent(toXContent, mediaType, toXContentParams, false).toBytesRef(); + BytesRef source = org.opensearch.core.xcontent.XContentHelper.toXContent(toXContent, mediaType, toXContentParams, false) + .toBytesRef(); return new ByteArrayEntity(source.bytes, source.offset, source.length, createContentType(mediaType)); } @@ -868,12 +874,12 @@ static String endpoint(String[] indices, String endpoint, String type) { } /** - * Returns a {@link ContentType} from a given {@link XContentType}. + * Returns a {@link ContentType} from a given {@link MediaType}. * * @param mediaType the {@link MediaType} * @return the {@link ContentType} */ - @SuppressForbidden(reason = "Only allowed place to convert a XContentType to a ContentType") + @SuppressForbidden(reason = "Only allowed place to convert a MediaType to a ContentType") public static ContentType createContentType(final MediaType mediaType) { return ContentType.create(mediaType.mediaTypeWithoutParameters(), (Charset) null); } @@ -1252,7 +1258,7 @@ Params withWaitForEvents(Priority waitForEvents) { */ static MediaType enforceSameContentType(IndexRequest indexRequest, @Nullable MediaType mediaType) { MediaType requestContentType = indexRequest.getContentType(); - if (requestContentType != XContentType.JSON && requestContentType != XContentType.SMILE) { + if (requestContentType != MediaTypeRegistry.JSON && requestContentType != MediaTypeRegistry.fromFormat("smile")) { throw new IllegalArgumentException( "Unsupported content-type found for request with content-type [" + requestContentType diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java index 1359c68fc1311..4a298ac55999f 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java @@ -35,11 +35,11 @@ import org.opensearch.core.ParseField; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.Mapper; import java.io.IOException; @@ -150,7 +150,7 @@ public String fullName() { * Returns the mappings as a map. Note that the returned map has a single key which is always the field's {@link Mapper#name}. */ public Map sourceAsMap() { - return XContentHelper.convertToMap(source, true, XContentType.JSON).v2(); + return XContentHelper.convertToMap(source, true, MediaTypeRegistry.JSON).v2(); } // pkg-private for testing diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutIndexTemplateRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutIndexTemplateRequest.java index 09dbbd63b9479..ed5db741ea6f1 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutIndexTemplateRequest.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutIndexTemplateRequest.java @@ -217,10 +217,10 @@ public Settings settings() { * Adds mapping that will be added when the index gets created. * * @param source The mapping source - * @param xContentType The type of content contained within the source + * @param mediaType The type of content contained within the source */ - public PutIndexTemplateRequest mapping(String source, XContentType xContentType) { - internalMapping(XContentHelper.convertToMap(new BytesArray(source), true, xContentType).v2()); + public PutIndexTemplateRequest mapping(String source, MediaType mediaType) { + internalMapping(XContentHelper.convertToMap(new BytesArray(source), true, mediaType).v2()); return this; } @@ -268,7 +268,7 @@ public PutIndexTemplateRequest mapping(Map source) { private PutIndexTemplateRequest internalMapping(Map source) { try { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder(); builder.map(source); MediaType mediaType = builder.contentType(); Objects.requireNonNull(mediaType); diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java index a6f8bfdee4d68..fd101c575b97a 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java @@ -33,10 +33,10 @@ package org.opensearch.client.slm; import org.opensearch.common.Nullable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -169,6 +169,6 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java index 0fcb6f7c6a29e..dd44d16f0d65e 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java @@ -33,10 +33,10 @@ package org.opensearch.client.slm; import org.opensearch.common.Nullable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -289,7 +289,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java index a2e43325ccd6f..476533d9c91ca 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java @@ -33,10 +33,10 @@ package org.opensearch.client.slm; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -188,7 +188,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } public static class SnapshotPolicyStats implements ToXContentFragment { diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java index 9982c0f2cef7d..3165b6bede19d 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java @@ -34,10 +34,10 @@ import org.opensearch.common.Nullable; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -151,6 +151,6 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/client/rest-high-level/src/main/resources/forbidden/rest-high-level-signatures.txt b/client/rest-high-level/src/main/resources/forbidden/rest-high-level-signatures.txt index e9e793aa9a783..42dde784147c7 100644 --- a/client/rest-high-level/src/main/resources/forbidden/rest-high-level-signatures.txt +++ b/client/rest-high-level/src/main/resources/forbidden/rest-high-level-signatures.txt @@ -14,7 +14,7 @@ # either express or implied. See the License for the specific # language governing permissions and limitations under the License. -@defaultMessage Use Request#createContentType(XContentType) to be sure to pass the right MIME type +@defaultMessage Use Request#createContentType(MediaType) to be sure to pass the right MIME type org.apache.hc.core5.http.ContentType#create(java.lang.String) org.apache.hc.core5.http.ContentType#create(java.lang.String,java.lang.String) org.apache.hc.core5.http.ContentType#create(java.lang.String,java.nio.charset.Charset) diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java index 2aeb47de150d6..077e1e5bf8aa5 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java @@ -42,12 +42,12 @@ import org.opensearch.action.get.MultiGetResponse; import org.opensearch.action.index.IndexRequest; import org.opensearch.action.search.SearchRequest; +import org.opensearch.common.unit.TimeValue; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.core.common.unit.ByteSizeValue; -import org.opensearch.common.unit.TimeValue; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.search.SearchHit; import org.hamcrest.Matcher; @@ -277,12 +277,12 @@ public void testBulkProcessorConcurrentRequestsReadOnlyIndex() throws Exception // let's make sure we get at least 1 item in the MultiGetRequest regardless of the randomising roulette if (randomBoolean() || multiGetRequest.getItems().size() == 0) { testDocs++; - processor.add(new IndexRequest("test").id(Integer.toString(testDocs)).source(XContentType.JSON, "field", "value")); + processor.add(new IndexRequest("test").id(Integer.toString(testDocs)).source(MediaTypeRegistry.JSON, "field", "value")); multiGetRequest.add("test", Integer.toString(testDocs)); } else { testReadOnlyDocs++; processor.add( - new IndexRequest("test-ro").id(Integer.toString(testReadOnlyDocs)).source(XContentType.JSON, "field", "value") + new IndexRequest("test-ro").id(Integer.toString(testReadOnlyDocs)).source(MediaTypeRegistry.JSON, "field", "value") ); } } @@ -333,9 +333,9 @@ public void testGlobalParametersAndSingleRequest() throws Exception { processor.add(new IndexRequest() // <1> - .source(XContentType.JSON, "user", "some user")); + .source(MediaTypeRegistry.JSON, "user", "some user")); processor.add(new IndexRequest("blogs").id("1") // <2> - .source(XContentType.JSON, "title", "some title")); + .source(MediaTypeRegistry.JSON, "title", "some title")); } // end::bulk-processor-mix-parameters latch.await(); @@ -399,11 +399,11 @@ private MultiGetRequest indexDocs(BulkProcessor processor, int numDocs, String l if (randomBoolean()) { processor.add( new IndexRequest(localIndex).id(Integer.toString(i)) - .source(XContentType.JSON, "field", randomRealisticUnicodeOfLengthBetween(1, 30)) + .source(MediaTypeRegistry.JSON, "field", randomRealisticUnicodeOfLengthBetween(1, 30)) ); } else { BytesArray data = bytesBulkRequest(localIndex, i); - processor.add(data, globalIndex, globalPipeline, XContentType.JSON); + processor.add(data, globalIndex, globalPipeline, MediaTypeRegistry.JSON); } multiGetRequest.add(localIndex, Integer.toString(i)); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java index 44bd085788203..b7f6328b3c88e 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java @@ -40,8 +40,8 @@ import org.opensearch.action.get.MultiGetRequest; import org.opensearch.action.index.IndexRequest; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.rest.RestStatus; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.transport.RemoteTransportException; import java.util.Collections; @@ -170,7 +170,7 @@ private static MultiGetRequest indexDocs(BulkProcessor processor, int numDocs) { for (int i = 1; i <= numDocs; i++) { processor.add( new IndexRequest(INDEX_NAME).id(Integer.toString(i)) - .source(XContentType.JSON, "field", randomRealisticUnicodeOfCodepointLengthBetween(1, 30)) + .source(MediaTypeRegistry.JSON, "field", randomRealisticUnicodeOfCodepointLengthBetween(1, 30)) ); multiGetRequest.add(INDEX_NAME, Integer.toString(i)); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java index 35fc9d88e316c..d392aa842fb35 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java @@ -36,7 +36,7 @@ import org.opensearch.action.bulk.BulkResponse; import org.opensearch.action.index.IndexRequest; import org.opensearch.action.search.SearchRequest; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.search.SearchHit; import java.io.IOException; @@ -59,8 +59,8 @@ public void testGlobalPipelineOnBulkRequest() throws IOException { createFieldAddingPipleine("xyz", "fieldNameXYZ", "valueXYZ"); BulkRequest request = new BulkRequest(); - request.add(new IndexRequest("test").id("1").source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest("test").id("2").source(XContentType.JSON, "field", "bulk2")); + request.add(new IndexRequest("test").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1")); + request.add(new IndexRequest("test").id("2").source(MediaTypeRegistry.JSON, "field", "bulk2")); request.pipeline("xyz"); bulk(request); @@ -76,8 +76,8 @@ public void testPipelineOnRequestOverridesGlobalPipeline() throws IOException { BulkRequest request = new BulkRequest(); request.pipeline("globalId"); - request.add(new IndexRequest("test").id("1").source(XContentType.JSON, "field", "bulk1").setPipeline("perIndexId")); - request.add(new IndexRequest("test").id("2").source(XContentType.JSON, "field", "bulk2").setPipeline("perIndexId")); + request.add(new IndexRequest("test").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1").setPipeline("perIndexId")); + request.add(new IndexRequest("test").id("2").source(MediaTypeRegistry.JSON, "field", "bulk2").setPipeline("perIndexId")); bulk(request); @@ -96,11 +96,11 @@ public void testMixPipelineOnRequestAndGlobal() throws IOException { request.pipeline("globalId"); request.add(new IndexRequest("test").id("1") - .source(XContentType.JSON, "field", "bulk1") + .source(MediaTypeRegistry.JSON, "field", "bulk1") .setPipeline("perIndexId")); // <1> request.add(new IndexRequest("test").id("2") - .source(XContentType.JSON, "field", "bulk2")); // <2> + .source(MediaTypeRegistry.JSON, "field", "bulk2")); // <2> // end::bulk-request-mix-pipeline bulk(request); @@ -116,8 +116,8 @@ public void testMixPipelineOnRequestAndGlobal() throws IOException { public void testGlobalIndex() throws IOException { BulkRequest request = new BulkRequest("global_index"); - request.add(new IndexRequest().id("1").source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest().id("2").source(XContentType.JSON, "field", "bulk2")); + request.add(new IndexRequest().id("1").source(MediaTypeRegistry.JSON, "field", "bulk1")); + request.add(new IndexRequest().id("2").source(MediaTypeRegistry.JSON, "field", "bulk2")); bulk(request); @@ -128,10 +128,10 @@ public void testGlobalIndex() throws IOException { @SuppressWarnings("unchecked") public void testIndexGlobalAndPerRequest() throws IOException { BulkRequest request = new BulkRequest("global_index"); - request.add(new IndexRequest("local_index").id("1").source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest("local_index").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1")); request.add( new IndexRequest().id("2") // will take global index - .source(XContentType.JSON, "field", "bulk2") + .source(MediaTypeRegistry.JSON, "field", "bulk2") ); bulk(request); @@ -143,8 +143,8 @@ public void testIndexGlobalAndPerRequest() throws IOException { public void testGlobalRouting() throws IOException { createIndexWithMultipleShards("index"); BulkRequest request = new BulkRequest((String) null); - request.add(new IndexRequest("index").id("1").source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest("index").id("2").source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest("index").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1")); + request.add(new IndexRequest("index").id("2").source(MediaTypeRegistry.JSON, "field", "bulk1")); request.routing("1"); bulk(request); @@ -158,8 +158,8 @@ public void testGlobalRouting() throws IOException { public void testMixLocalAndGlobalRouting() throws IOException { BulkRequest request = new BulkRequest((String) null); request.routing("globalRouting"); - request.add(new IndexRequest("index").id("1").source(XContentType.JSON, "field", "bulk1")); - request.add(new IndexRequest("index").id("2").routing("localRouting").source(XContentType.JSON, "field", "bulk1")); + request.add(new IndexRequest("index").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1")); + request.add(new IndexRequest("index").id("2").routing("localRouting").source(MediaTypeRegistry.JSON, "field", "bulk1")); bulk(request); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java index 3c7d988e3f01d..54cb15b9cb767 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java @@ -63,8 +63,8 @@ import org.opensearch.common.settings.Settings; import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.support.XContentMapValues; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.indices.recovery.RecoverySettings; import org.opensearch.core.rest.RestStatus; import org.opensearch.transport.RemoteClusterService; @@ -125,7 +125,7 @@ public void testClusterPutSettings() throws IOException { ClusterUpdateSettingsRequest resetRequest = new ClusterUpdateSettingsRequest(); resetRequest.transientSettings(Settings.builder().putNull(transientSettingKey)); - resetRequest.persistentSettings("{\"" + persistentSettingKey + "\": null }", XContentType.JSON); + resetRequest.persistentSettings("{\"" + persistentSettingKey + "\": null }", MediaTypeRegistry.JSON); ClusterUpdateSettingsResponse resetResponse = execute( resetRequest, diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java index cefe992b58c64..132be80efaab2 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java @@ -63,6 +63,8 @@ import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.common.xcontent.XContentType; @@ -202,7 +204,7 @@ public void testExists() throws IOException { assertFalse(execute(getRequest, highLevelClient()::exists, highLevelClient()::existsAsync)); } IndexRequest index = new IndexRequest("index").id("id"); - index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", XContentType.JSON); + index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", MediaTypeRegistry.JSON); index.setRefreshPolicy(RefreshPolicy.IMMEDIATE); highLevelClient().index(index, RequestOptions.DEFAULT); { @@ -227,7 +229,7 @@ public void testDeprecatedSourceExists() throws IOException { assertFalse(execute(getRequest, highLevelClient()::existsSource, highLevelClient()::existsSourceAsync)); } IndexRequest index = new IndexRequest("index").id("id"); - index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", XContentType.JSON); + index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", MediaTypeRegistry.JSON); index.setRefreshPolicy(RefreshPolicy.IMMEDIATE); highLevelClient().index(index, RequestOptions.DEFAULT); { @@ -250,7 +252,7 @@ public void testSourceExists() throws IOException { assertFalse(execute(getRequest, highLevelClient()::existsSource, highLevelClient()::existsSourceAsync)); } IndexRequest index = new IndexRequest("index").id("id"); - index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", XContentType.JSON); + index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", MediaTypeRegistry.JSON); index.setRefreshPolicy(RefreshPolicy.IMMEDIATE); highLevelClient().index(index, RequestOptions.DEFAULT); { @@ -274,9 +276,9 @@ public void testSourceDoesNotExist() throws IOException { RestStatus.OK, highLevelClient().bulk( new BulkRequest().add( - new IndexRequest(noSourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + new IndexRequest(noSourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(noSourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) + .add(new IndexRequest(noSourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON)) .setRefreshPolicy(RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -306,7 +308,7 @@ public void testGet() throws IOException { } IndexRequest index = new IndexRequest("index").id("id"); String document = "{\"field1\":\"value1\",\"field2\":\"value2\"}"; - index.source(document, XContentType.JSON); + index.source(document, MediaTypeRegistry.JSON); index.setRefreshPolicy(RefreshPolicy.IMMEDIATE); highLevelClient().index(index, RequestOptions.DEFAULT); { @@ -406,10 +408,10 @@ public void testMultiGet() throws IOException { BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(RefreshPolicy.IMMEDIATE); IndexRequest index = new IndexRequest("index").id("id1"); - index.source("{\"field\":\"value1\"}", XContentType.JSON); + index.source("{\"field\":\"value1\"}", MediaTypeRegistry.JSON); bulk.add(index); index = new IndexRequest("index").id("id2"); - index.source("{\"field\":\"value2\"}", XContentType.JSON); + index.source("{\"field\":\"value2\"}", MediaTypeRegistry.JSON); bulk.add(index); highLevelClient().bulk(bulk, RequestOptions.DEFAULT); { @@ -436,8 +438,8 @@ public void testMultiGet() throws IOException { public void testMultiGetWithIds() throws IOException { BulkRequest bulk = new BulkRequest(); bulk.setRefreshPolicy(RefreshPolicy.IMMEDIATE); - bulk.add(new IndexRequest("index").id("id1").source("{\"field\":\"value1\"}", XContentType.JSON)); - bulk.add(new IndexRequest("index").id("id2").source("{\"field\":\"value2\"}", XContentType.JSON)); + bulk.add(new IndexRequest("index").id("id1").source("{\"field\":\"value1\"}", MediaTypeRegistry.JSON)); + bulk.add(new IndexRequest("index").id("id2").source("{\"field\":\"value2\"}", MediaTypeRegistry.JSON)); MultiGetRequest multiGetRequest = new MultiGetRequest(); multiGetRequest.add("index", "id1"); @@ -457,7 +459,7 @@ public void testGetSource() throws IOException { } IndexRequest index = new IndexRequest("index").id("id"); String document = "{\"field1\":\"value1\",\"field2\":\"value2\"}"; - index.source(document, XContentType.JSON); + index.source(document, MediaTypeRegistry.JSON); index.setRefreshPolicy(RefreshPolicy.IMMEDIATE); highLevelClient().index(index, RequestOptions.DEFAULT); { @@ -815,7 +817,7 @@ public void testUpdate() throws IOException { { IllegalStateException exception = expectThrows(IllegalStateException.class, () -> { UpdateRequest updateRequest = new UpdateRequest("index", "id"); - updateRequest.doc(new IndexRequest().source(Collections.singletonMap("field", "doc"), XContentType.JSON)); + updateRequest.doc(new IndexRequest().source(Collections.singletonMap("field", "doc"), MediaTypeRegistry.JSON)); updateRequest.upsert(new IndexRequest().source(Collections.singletonMap("field", "upsert"), XContentType.YAML)); execute(updateRequest, highLevelClient()::update, highLevelClient()::updateAsync); }); @@ -827,7 +829,7 @@ public void testUpdate() throws IOException { { OpenSearchException exception = expectThrows(OpenSearchException.class, () -> { UpdateRequest updateRequest = new UpdateRequest("index", "require_alias").setRequireAlias(true); - updateRequest.doc(new IndexRequest().source(Collections.singletonMap("field", "doc"), XContentType.JSON)); + updateRequest.doc(new IndexRequest().source(Collections.singletonMap("field", "doc"), MediaTypeRegistry.JSON)); execute(updateRequest, highLevelClient()::update, highLevelClient()::updateAsync); }); assertEquals(RestStatus.NOT_FOUND, exception.status()); @@ -842,7 +844,7 @@ public void testBulk() throws IOException { int nbItems = randomIntBetween(10, 100); boolean[] errors = new boolean[nbItems]; - XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE); + MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE); BulkRequest bulkRequest = new BulkRequest(); for (int i = 0; i < nbItems; i++) { @@ -863,10 +865,10 @@ public void testBulk() throws IOException { } else { BytesReference source = BytesReference.bytes( - XContentBuilder.builder(xContentType.xContent()).startObject().field("id", i).endObject() + XContentBuilder.builder(mediaType.xContent()).startObject().field("id", i).endObject() ); if (opType == DocWriteRequest.OpType.INDEX) { - IndexRequest indexRequest = new IndexRequest("index").id(id).source(source, xContentType); + IndexRequest indexRequest = new IndexRequest("index").id(id).source(source, mediaType); if (erroneous) { indexRequest.setIfSeqNo(12L); indexRequest.setIfPrimaryTerm(12L); @@ -874,14 +876,14 @@ public void testBulk() throws IOException { bulkRequest.add(indexRequest); } else if (opType == DocWriteRequest.OpType.CREATE) { - IndexRequest createRequest = new IndexRequest("index").id(id).source(source, xContentType).create(true); + IndexRequest createRequest = new IndexRequest("index").id(id).source(source, mediaType).create(true); if (erroneous) { assertEquals(RestStatus.CREATED, highLevelClient().index(createRequest, RequestOptions.DEFAULT).status()); } bulkRequest.add(createRequest); } else if (opType == DocWriteRequest.OpType.UPDATE) { - UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(source, xContentType)); + UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(source, mediaType)); if (erroneous == false) { assertEquals( RestStatus.CREATED, @@ -905,7 +907,7 @@ public void testBulkProcessorIntegration() throws IOException { int nbItems = randomIntBetween(10, 100); boolean[] errors = new boolean[nbItems]; - XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE); + MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE); AtomicReference responseRef = new AtomicReference<>(); AtomicReference requestRef = new AtomicReference<>(); @@ -953,7 +955,7 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure) } else { if (opType == DocWriteRequest.OpType.INDEX) { - IndexRequest indexRequest = new IndexRequest("index").id(id).source(xContentType, "id", i); + IndexRequest indexRequest = new IndexRequest("index").id(id).source(mediaType, "id", i); if (erroneous) { indexRequest.setIfSeqNo(12L); indexRequest.setIfPrimaryTerm(12L); @@ -961,14 +963,14 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure) processor.add(indexRequest); } else if (opType == DocWriteRequest.OpType.CREATE) { - IndexRequest createRequest = new IndexRequest("index").id(id).source(xContentType, "id", i).create(true); + IndexRequest createRequest = new IndexRequest("index").id(id).source(mediaType, "id", i).create(true); if (erroneous) { assertEquals(RestStatus.CREATED, highLevelClient().index(createRequest, RequestOptions.DEFAULT).status()); } processor.add(createRequest); } else if (opType == DocWriteRequest.OpType.UPDATE) { - UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(xContentType, "id", i)); + UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(mediaType, "id", i)); if (erroneous == false) { assertEquals( RestStatus.CREATED, @@ -1106,9 +1108,12 @@ public void testTermvectors() throws IOException { RestStatus.OK, highLevelClient().bulk( new BulkRequest().add( - new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("field", "value1"), XContentType.JSON) + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("field", "value1"), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("field", "value2"), XContentType.JSON)) + .add( + new IndexRequest(sourceIndex).id("2") + .source(Collections.singletonMap("field", "value2"), MediaTypeRegistry.JSON) + ) .setRefreshPolicy(RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -1201,8 +1206,8 @@ public void testMultiTermvectors() throws IOException { assertEquals( RestStatus.OK, highLevelClient().bulk( - new BulkRequest().add(new IndexRequest(sourceIndex).id("1").source(doc1, XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("2").source(doc2, XContentType.JSON)) + new BulkRequest().add(new IndexRequest(sourceIndex).id("1").source(doc1, MediaTypeRegistry.JSON)) + .add(new IndexRequest(sourceIndex).id("2").source(doc2, MediaTypeRegistry.JSON)) .setRefreshPolicy(RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java index 972c96999945f..93eeee349db14 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java @@ -49,8 +49,8 @@ import org.opensearch.action.support.PlainActionFuture; import org.opensearch.cluster.ClusterName; import org.opensearch.common.SuppressForbidden; -import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; +import org.opensearch.core.xcontent.XContentHelper; import org.opensearch.test.OpenSearchTestCase; import org.junit.Before; @@ -174,7 +174,7 @@ private Response mockPerformRequest(Request request) throws IOException { when(mockResponse.getStatusLine()).thenReturn(new StatusLine(protocol, 200, "OK")); MainResponse response = new MainResponse(httpHeader.getValue(), Version.CURRENT, ClusterName.DEFAULT, "_na", Build.CURRENT); - BytesRef bytesRef = XContentHelper.toXContent(response, XContentType.JSON, false).toBytesRef(); + BytesRef bytesRef = XContentHelper.toXContent(response, MediaTypeRegistry.JSON, false).toBytesRef(); when(mockResponse.getEntity()).thenReturn(new ByteArrayEntity(bytesRef.bytes, ContentType.APPLICATION_JSON)); RequestLine requestLine = new RequestLine(HttpGet.METHOD_NAME, ENDPOINT, protocol); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesClientIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesClientIT.java index ea57f1857fbfb..1dda4f3db8138 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesClientIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesClientIT.java @@ -116,9 +116,9 @@ import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.common.xcontent.support.XContentMapValues; import org.opensearch.index.IndexSettings; @@ -1074,7 +1074,7 @@ public void testRollover() throws IOException { } { String mappings = "{\"properties\":{\"field2\":{\"type\":\"keyword\"}}}"; - rolloverRequest.getCreateIndexRequest().mapping(mappings, XContentType.JSON); + rolloverRequest.getCreateIndexRequest().mapping(mappings, MediaTypeRegistry.JSON); rolloverRequest.dryRun(false); rolloverRequest.addMaxIndexSizeCondition(new ByteSizeValue(1, ByteSizeUnit.MB)); RolloverResponse rolloverResponse = execute( @@ -1489,7 +1489,7 @@ public void testPutTemplate() throws Exception { .order(10) .create(randomBoolean()) .settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0")) - .mapping("{ \"properties\": { \"host_name\": { \"type\": \"keyword\" } } }", XContentType.JSON) + .mapping("{ \"properties\": { \"host_name\": { \"type\": \"keyword\" } } }", MediaTypeRegistry.JSON) .alias(new Alias("alias-1").indexRouting("abc")) .alias(new Alias("alias-1").indexRouting("abc")) .alias(new Alias("{index}-write").searchRouting("xyz")); @@ -1558,7 +1558,7 @@ public void testPutTemplateWithTypesUsingUntypedAPI() throws Exception { + " }" + " }" + "}", - XContentType.JSON + MediaTypeRegistry.JSON ) .alias(new Alias("alias-1").indexRouting("abc")) .alias(new Alias("{index}-write").searchRouting("xyz")); @@ -1664,7 +1664,7 @@ public void testCRUDIndexTemplate() throws Exception { equalTo(true) ); PutIndexTemplateRequest putTemplate2 = new PutIndexTemplateRequest("template-2").patterns(Arrays.asList("pattern-2", "name-2")) - .mapping("{\"properties\": { \"name\": { \"type\": \"text\" }}}", XContentType.JSON) + .mapping("{\"properties\": { \"name\": { \"type\": \"text\" }}}", MediaTypeRegistry.JSON) .settings(Settings.builder().put("number_of_shards", "2").put("number_of_replicas", "0")); assertThat( execute(putTemplate2, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged(), diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java index 75c5a71303af4..74ca9ae1720c5 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java @@ -75,8 +75,8 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; import org.opensearch.core.common.util.CollectionUtils; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchTestCase; import org.junit.Assert; import org.opensearch.core.common.unit.ByteSizeValue; @@ -858,7 +858,7 @@ public void testPutTemplateRequest() throws Exception { + "\" : { \"type\" : \"" + OpenSearchTestCase.randomFrom("text", "keyword") + "\" }}}", - XContentType.JSON + MediaTypeRegistry.JSON ); } if (OpenSearchTestCase.randomBoolean()) { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java index 0f377720b7aed..81d6a448cdfc6 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java @@ -38,7 +38,7 @@ import org.opensearch.action.ingest.SimulatePipelineRequest; import org.opensearch.action.support.master.AcknowledgedRequest; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchTestCase; import org.apache.hc.client5.http.classic.methods.HttpDelete; import org.apache.hc.client5.http.classic.methods.HttpGet; @@ -59,7 +59,7 @@ public void testPutPipeline() throws IOException { PutPipelineRequest request = new PutPipelineRequest( "some_pipeline_id", new BytesArray("{}".getBytes(StandardCharsets.UTF_8)), - XContentType.JSON + MediaTypeRegistry.JSON ); Map expectedParams = new HashMap<>(); RequestConvertersTests.setRandomClusterManagerTimeout(request, expectedParams); @@ -130,7 +130,7 @@ public void testSimulatePipeline() throws IOException { + "}"; SimulatePipelineRequest request = new SimulatePipelineRequest( new BytesArray(json.getBytes(StandardCharsets.UTF_8)), - XContentType.JSON + MediaTypeRegistry.JSON ); request.setId(pipelineId); request.setVerbose(verbose); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java b/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java index ee1f217f47ef2..97eee0353dd63 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java @@ -51,6 +51,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.concurrent.ThreadContext; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.common.xcontent.XContentType; @@ -223,7 +224,7 @@ protected static void createFieldAddingPipleine(String id, String fieldName, Str .endArray() .endObject(); - createPipeline(new PutPipelineRequest(id, BytesReference.bytes(pipeline), XContentType.JSON)); + createPipeline(new PutPipelineRequest(id, BytesReference.bytes(pipeline), MediaTypeRegistry.JSON)); } protected static void createPipeline(String pipelineId) throws IOException { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java index 65888e79683e3..be4fd71c6f5e8 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java @@ -42,7 +42,7 @@ import org.opensearch.action.support.WriteRequest; import org.opensearch.client.tasks.TaskSubmissionResponse; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.IdsQueryBuilder; import org.opensearch.index.reindex.BulkByScrollResponse; import org.opensearch.index.reindex.DeleteByQueryAction; @@ -76,9 +76,9 @@ public void testReindex() throws IOException { createIndex(sourceIndex, settings); createIndex(destinationIndex, settings); BulkRequest bulkRequest = new BulkRequest().add( - new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), MediaTypeRegistry.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status()); } @@ -132,9 +132,9 @@ public void testReindexTask() throws Exception { createIndex(sourceIndex, settings); createIndex(destinationIndex, settings); BulkRequest bulkRequest = new BulkRequest().add( - new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), MediaTypeRegistry.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status()); } @@ -163,9 +163,9 @@ public void testReindexConflict() throws IOException { createIndex(sourceIndex, settings); createIndex(destIndex, settings); final BulkRequest bulkRequest = new BulkRequest().add( - new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); assertThat(highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status(), equalTo(RestStatus.OK)); @@ -205,10 +205,10 @@ public void testDeleteByQuery() throws Exception { RestStatus.OK, highLevelClient().bulk( new BulkRequest().add( - new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON)) + .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), MediaTypeRegistry.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -305,10 +305,10 @@ public void testDeleteByQueryTask() throws Exception { RestStatus.OK, highLevelClient().bulk( new BulkRequest().add( - new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON)) + .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), MediaTypeRegistry.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java index 15a99b3e91685..239749e13b08b 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java @@ -72,11 +72,11 @@ import org.opensearch.common.logging.DeprecationLogger; import org.opensearch.common.lucene.uid.Versions; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -852,7 +852,7 @@ private static void setRandomIfSeqNoAndTerm(DocWriteRequest request, Map { UpdateRequest updateRequest = new UpdateRequest(); - updateRequest.doc(new IndexRequest().source(singletonMap("field", "doc"), XContentType.JSON)); + updateRequest.doc(new IndexRequest().source(singletonMap("field", "doc"), MediaTypeRegistry.JSON)); updateRequest.upsert(new IndexRequest().source(singletonMap("field", "upsert"), XContentType.YAML)); RequestConverters.update(updateRequest); }); @@ -876,7 +876,7 @@ public void testBulk() throws IOException { setRandomRefreshPolicy(bulkRequest::setRefreshPolicy, expectedParams); - XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE); + MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE); int nbItems = randomIntBetween(10, 100); DocWriteRequest[] requests = new DocWriteRequest[nbItems]; @@ -884,21 +884,21 @@ public void testBulk() throws IOException { String index = randomAlphaOfLength(5); String id = randomAlphaOfLength(5); - BytesReference source = RandomObjects.randomSource(random(), xContentType); + BytesReference source = RandomObjects.randomSource(random(), mediaType); DocWriteRequest.OpType opType = randomFrom(DocWriteRequest.OpType.values()); DocWriteRequest docWriteRequest; if (opType == DocWriteRequest.OpType.INDEX) { - IndexRequest indexRequest = new IndexRequest(index).id(id).source(source, xContentType); + IndexRequest indexRequest = new IndexRequest(index).id(id).source(source, mediaType); docWriteRequest = indexRequest; if (randomBoolean()) { indexRequest.setPipeline(randomAlphaOfLength(5)); } } else if (opType == DocWriteRequest.OpType.CREATE) { - IndexRequest createRequest = new IndexRequest(index).id(id).source(source, xContentType).create(true); + IndexRequest createRequest = new IndexRequest(index).id(id).source(source, mediaType).create(true); docWriteRequest = createRequest; } else if (opType == DocWriteRequest.OpType.UPDATE) { - final UpdateRequest updateRequest = new UpdateRequest(index, id).doc(new IndexRequest().source(source, xContentType)); + final UpdateRequest updateRequest = new UpdateRequest(index, id).doc(new IndexRequest().source(source, mediaType)); docWriteRequest = updateRequest; if (randomBoolean()) { updateRequest.retryOnConflict(randomIntBetween(1, 5)); @@ -927,14 +927,14 @@ public void testBulk() throws IOException { assertEquals("/_bulk", request.getEndpoint()); assertEquals(expectedParams, request.getParameters()); assertEquals(HttpPost.METHOD_NAME, request.getMethod()); - assertEquals(xContentType.mediaTypeWithoutParameters(), request.getEntity().getContentType()); + assertEquals(mediaType.mediaTypeWithoutParameters(), request.getEntity().getContentType()); byte[] content = new byte[(int) request.getEntity().getContentLength()]; try (InputStream inputStream = request.getEntity().getContent()) { Streams.readFully(inputStream, content); } BulkRequest parsedBulkRequest = new BulkRequest(); - parsedBulkRequest.add(content, 0, content.length, xContentType); + parsedBulkRequest.add(content, 0, content.length, mediaType); assertEquals(bulkRequest.numberOfActions(), parsedBulkRequest.numberOfActions()); for (int i = 0; i < bulkRequest.numberOfActions(); i++) { @@ -956,7 +956,7 @@ public void testBulk() throws IOException { IndexRequest parsedIndexRequest = (IndexRequest) parsedRequest; assertEquals(indexRequest.getPipeline(), parsedIndexRequest.getPipeline()); - assertToXContentEquivalent(indexRequest.source(), parsedIndexRequest.source(), xContentType); + assertToXContentEquivalent(indexRequest.source(), parsedIndexRequest.source(), mediaType); } else if (opType == DocWriteRequest.OpType.UPDATE) { UpdateRequest updateRequest = (UpdateRequest) originalRequest; UpdateRequest parsedUpdateRequest = (UpdateRequest) parsedRequest; @@ -964,7 +964,7 @@ public void testBulk() throws IOException { assertEquals(updateRequest.retryOnConflict(), parsedUpdateRequest.retryOnConflict()); assertEquals(updateRequest.fetchSource(), parsedUpdateRequest.fetchSource()); if (updateRequest.doc() != null) { - assertToXContentEquivalent(updateRequest.doc().source(), parsedUpdateRequest.doc().source(), xContentType); + assertToXContentEquivalent(updateRequest.doc().source(), parsedUpdateRequest.doc().source(), mediaType); } else { assertNull(parsedUpdateRequest.doc()); } @@ -980,34 +980,34 @@ public void testBulkWithDifferentContentTypes() throws IOException { bulkRequest.add(new DeleteRequest("index", "2")); Request request = RequestConverters.bulk(bulkRequest); - assertEquals(XContentType.JSON.mediaTypeWithoutParameters(), request.getEntity().getContentType()); + assertEquals(MediaTypeRegistry.JSON.mediaTypeWithoutParameters(), request.getEntity().getContentType()); } { - XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE); + MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE); BulkRequest bulkRequest = new BulkRequest(); bulkRequest.add(new DeleteRequest("index", "0")); - bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), xContentType)); + bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), mediaType)); bulkRequest.add(new DeleteRequest("index", "2")); Request request = RequestConverters.bulk(bulkRequest); - assertEquals(xContentType.mediaTypeWithoutParameters(), request.getEntity().getContentType()); + assertEquals(mediaType.mediaTypeWithoutParameters(), request.getEntity().getContentType()); } { - XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE); + MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE); UpdateRequest updateRequest = new UpdateRequest("index", "0"); if (randomBoolean()) { - updateRequest.doc(new IndexRequest().source(singletonMap("field", "value"), xContentType)); + updateRequest.doc(new IndexRequest().source(singletonMap("field", "value"), mediaType)); } else { - updateRequest.upsert(new IndexRequest().source(singletonMap("field", "value"), xContentType)); + updateRequest.upsert(new IndexRequest().source(singletonMap("field", "value"), mediaType)); } Request request = RequestConverters.bulk(new BulkRequest().add(updateRequest)); - assertEquals(xContentType.mediaTypeWithoutParameters(), request.getEntity().getContentType()); + assertEquals(mediaType.mediaTypeWithoutParameters(), request.getEntity().getContentType()); } { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), XContentType.SMILE)); - bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), XContentType.JSON)); + bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), MediaTypeRegistry.JSON)); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> RequestConverters.bulk(bulkRequest)); assertEquals( "Mismatching content-type found for request with content-type [JSON], " + "previous requests have content-type [SMILE]", @@ -1016,10 +1016,10 @@ public void testBulkWithDifferentContentTypes() throws IOException { } { BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), XContentType.JSON)); - bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), XContentType.JSON)); + bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), MediaTypeRegistry.JSON)); + bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), MediaTypeRegistry.JSON)); bulkRequest.add( - new UpdateRequest("index", "2").doc(new IndexRequest().source(singletonMap("field", "value"), XContentType.JSON)) + new UpdateRequest("index", "2").doc(new IndexRequest().source(singletonMap("field", "value"), MediaTypeRegistry.JSON)) .upsert(new IndexRequest().source(singletonMap("field", "value"), XContentType.SMILE)) ); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> RequestConverters.bulk(bulkRequest)); @@ -1032,10 +1032,10 @@ public void testBulkWithDifferentContentTypes() throws IOException { XContentType xContentType = randomFrom(XContentType.CBOR, XContentType.YAML); BulkRequest bulkRequest = new BulkRequest(); bulkRequest.add(new DeleteRequest("index", "0")); - bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), XContentType.JSON)); + bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), MediaTypeRegistry.JSON)); bulkRequest.add(new DeleteRequest("index", "2")); bulkRequest.add(new DeleteRequest("index", "3")); - bulkRequest.add(new IndexRequest("index").id("4").source(singletonMap("field", "value"), XContentType.JSON)); + bulkRequest.add(new IndexRequest("index").id("4").source(singletonMap("field", "value"), MediaTypeRegistry.JSON)); bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), xContentType)); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> RequestConverters.bulk(bulkRequest)); assertEquals( @@ -1048,9 +1048,9 @@ public void testBulkWithDifferentContentTypes() throws IOException { public void testGlobalPipelineOnBulkRequest() throws IOException { BulkRequest bulkRequest = new BulkRequest(); bulkRequest.pipeline("xyz"); - bulkRequest.add(new IndexRequest("test").id("11").source(XContentType.JSON, "field", "bulk1")); - bulkRequest.add(new IndexRequest("test").id("12").source(XContentType.JSON, "field", "bulk2")); - bulkRequest.add(new IndexRequest("test").id("13").source(XContentType.JSON, "field", "bulk3")); + bulkRequest.add(new IndexRequest("test").id("11").source(MediaTypeRegistry.JSON, "field", "bulk1")); + bulkRequest.add(new IndexRequest("test").id("12").source(MediaTypeRegistry.JSON, "field", "bulk2")); + bulkRequest.add(new IndexRequest("test").id("13").source(MediaTypeRegistry.JSON, "field", "bulk3")); Request request = RequestConverters.bulk(bulkRequest); @@ -1456,8 +1456,11 @@ public void testMultiSearchTemplate() throws Exception { assertEquals(expectedParams, multiRequest.getParameters()); HttpEntity actualEntity = multiRequest.getEntity(); - byte[] expectedBytes = MultiSearchTemplateRequest.writeMultiLineFormat(multiSearchTemplateRequest, XContentType.JSON.xContent()); - assertEquals(XContentType.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType()); + byte[] expectedBytes = MultiSearchTemplateRequest.writeMultiLineFormat( + multiSearchTemplateRequest, + MediaTypeRegistry.JSON.xContent() + ); + assertEquals(MediaTypeRegistry.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType()); assertEquals(new BytesArray(expectedBytes), new BytesArray(EntityUtils.toByteArray(actualEntity))); } @@ -1763,8 +1766,12 @@ public void testDeleteScriptRequest() { } static void assertToXContentBody(ToXContent expectedBody, HttpEntity actualEntity) throws IOException { - BytesReference expectedBytes = XContentHelper.toXContent(expectedBody, REQUEST_BODY_CONTENT_TYPE, false); - assertEquals(XContentType.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType()); + BytesReference expectedBytes = org.opensearch.core.xcontent.XContentHelper.toXContent( + expectedBody, + REQUEST_BODY_CONTENT_TYPE, + false + ); + assertEquals(MediaTypeRegistry.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType()); assertEquals(expectedBytes, new BytesArray(EntityUtils.toByteArray(actualEntity))); } @@ -1913,12 +1920,12 @@ public void testCreateContentType() { } public void testEnforceSameContentType() { - XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE); - IndexRequest indexRequest = new IndexRequest().source(singletonMap("field", "value"), xContentType); - assertEquals(xContentType, enforceSameContentType(indexRequest, null)); - assertEquals(xContentType, enforceSameContentType(indexRequest, xContentType)); + MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE); + IndexRequest indexRequest = new IndexRequest().source(singletonMap("field", "value"), mediaType); + assertEquals(mediaType, enforceSameContentType(indexRequest, null)); + assertEquals(mediaType, enforceSameContentType(indexRequest, mediaType)); - XContentType bulkContentType = randomBoolean() ? xContentType : null; + MediaType bulkContentType = randomBoolean() ? mediaType : null; IllegalArgumentException exception = expectThrows( IllegalArgumentException.class, @@ -1938,18 +1945,18 @@ public void testEnforceSameContentType() { exception.getMessage() ); - XContentType requestContentType = xContentType == XContentType.JSON ? XContentType.SMILE : XContentType.JSON; + MediaType requestContentType = mediaType == MediaTypeRegistry.JSON ? XContentType.SMILE : MediaTypeRegistry.JSON; exception = expectThrows( IllegalArgumentException.class, - () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), requestContentType), xContentType) + () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), requestContentType), mediaType) ); assertEquals( "Mismatching content-type found for request with content-type [" + requestContentType + "], " + "previous requests have content-type [" - + xContentType + + mediaType + "]", exception.getMessage() ); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java index 24b0fda6c18d5..0b3d395fcd118 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java @@ -106,7 +106,7 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.instanceOf; diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java index 233ea0ca5f48d..53a20aa58e5f8 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java @@ -54,9 +54,9 @@ import org.opensearch.client.core.CountResponse; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.unit.TimeValue; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.query.MatchQueryBuilder; import org.opensearch.index.query.QueryBuilder; import org.opensearch.index.query.QueryBuilders; @@ -1200,7 +1200,7 @@ public void testRenderSearchTemplate() throws IOException { BytesReference actualSource = searchTemplateResponse.getSource(); assertNotNull(actualSource); - assertToXContentEquivalent(expectedSource, actualSource, XContentType.JSON); + assertToXContentEquivalent(expectedSource, actualSource, MediaTypeRegistry.JSON); } public void testMultiSearchTemplate() throws Exception { diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java index df99d26a0a530..72072f2b7b790 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java @@ -54,7 +54,7 @@ import org.opensearch.action.support.master.AcknowledgedResponse; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.repositories.fs.FsRepository; import org.opensearch.core.rest.RestStatus; import org.opensearch.snapshots.RestoreInfo; @@ -76,7 +76,7 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase { private AcknowledgedResponse createTestRepository(String repository, String type, String settings) throws IOException { PutRepositoryRequest request = new PutRepositoryRequest(repository); - request.settings(settings, XContentType.JSON); + request.settings(settings, MediaTypeRegistry.JSON); request.type(type); return execute(request, highLevelClient().snapshot()::createRepository, highLevelClient().snapshot()::createRepositoryAsync); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java index c86de6ae645c1..4d792e53c6064 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java @@ -38,8 +38,8 @@ import org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptResponse; import org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.rest.RestStatus; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.script.Script; import org.opensearch.script.StoredScriptSource; @@ -58,10 +58,16 @@ public void testGetStoredScript() throws Exception { final StoredScriptSource scriptSource = new StoredScriptSource( "painless", "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType()) ); - PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); + PutStoredScriptRequest request = new PutStoredScriptRequest( + id, + "score", + new BytesArray("{}"), + MediaTypeRegistry.JSON, + scriptSource + ); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); GetStoredScriptRequest getRequest = new GetStoredScriptRequest("calculate-score"); @@ -76,10 +82,16 @@ public void testDeleteStoredScript() throws Exception { final StoredScriptSource scriptSource = new StoredScriptSource( "painless", "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType()) ); - PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); + PutStoredScriptRequest request = new PutStoredScriptRequest( + id, + "score", + new BytesArray("{}"), + MediaTypeRegistry.JSON, + scriptSource + ); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); DeleteStoredScriptRequest deleteRequest = new DeleteStoredScriptRequest(id); @@ -100,10 +112,16 @@ public void testPutScript() throws Exception { final StoredScriptSource scriptSource = new StoredScriptSource( "painless", "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType()) ); - PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); + PutStoredScriptRequest request = new PutStoredScriptRequest( + id, + "score", + new BytesArray("{}"), + MediaTypeRegistry.JSON, + scriptSource + ); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); Map script = getAsMap("/_scripts/" + id); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java index 24edd5f93bdba..7db593f57d55f 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java @@ -32,6 +32,7 @@ package org.opensearch.client; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.reindex.ReindexRequest; import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest; import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse; @@ -46,7 +47,6 @@ import org.opensearch.client.tasks.TaskId; import org.opensearch.client.tasks.TaskSubmissionResponse; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.rest.RestStatus; import java.io.IOException; @@ -94,9 +94,9 @@ public void testGetValidTask() throws Exception { createIndex(sourceIndex, settings); createIndex(destinationIndex, settings); BulkRequest bulkRequest = new BulkRequest().add( - new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), MediaTypeRegistry.JSON)) .setRefreshPolicy(RefreshPolicy.IMMEDIATE); assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status()); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java index e5fbb30d29292..c0447b30b73d6 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java @@ -41,7 +41,7 @@ import org.opensearch.action.support.WriteRequest; import org.opensearch.client.tasks.TaskSubmissionResponse; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.IdsQueryBuilder; import org.opensearch.index.reindex.BulkByScrollResponse; import org.opensearch.index.reindex.UpdateByQueryAction; @@ -76,9 +76,9 @@ public void testUpdateByQuery() throws Exception { RestStatus.OK, highLevelClient().bulk( new BulkRequest().add( - new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -197,10 +197,10 @@ public void testUpdateByQueryTask() throws Exception { RestStatus.OK, highLevelClient().bulk( new BulkRequest().add( - new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON) + new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON)) - .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), XContentType.JSON)) + .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON)) + .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), MediaTypeRegistry.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE), RequestOptions.DEFAULT ).status() @@ -230,9 +230,9 @@ public void testUpdateByQueryConflict() throws IOException { final Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build(); createIndex(index, settings); final BulkRequest bulkRequest = new BulkRequest().add( - new IndexRequest(index).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON) + new IndexRequest(index).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON) ) - .add(new IndexRequest(index).id("2").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)) + .add(new IndexRequest(index).id("2").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON)) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); assertThat(highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status(), equalTo(RestStatus.OK)); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java index 010b16a3f5720..58be005b94a8a 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java @@ -80,9 +80,9 @@ import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.index.VersionType; import org.opensearch.index.get.GetResult; @@ -173,7 +173,7 @@ public void testIndex() throws Exception { "\"postDate\":\"2013-01-30\"," + "\"message\":\"trying out OpenSearch\"" + "}"; - request.source(jsonString, XContentType.JSON); // <3> + request.source(jsonString, MediaTypeRegistry.JSON); // <3> //end::index-request-string // tag::index-execute @@ -380,7 +380,7 @@ public void testUpdate() throws Exception { "\"updated\":\"2017-01-01\"," + "\"reason\":\"daily update\"" + "}"; - request.doc(jsonString, XContentType.JSON); // <1> + request.doc(jsonString, MediaTypeRegistry.JSON); // <1> //end::update-request-with-doc-as-string request.fetchSource(true); // tag::update-execute @@ -524,7 +524,7 @@ public void testUpdate() throws Exception { // end::update-request-detect-noop // tag::update-request-upsert String jsonString = "{\"created\":\"2017-01-01\"}"; - request.upsert(jsonString, XContentType.JSON); // <1> + request.upsert(jsonString, MediaTypeRegistry.JSON); // <1> // end::update-request-upsert // tag::update-request-scripted-upsert request.scriptedUpsert(true); // <1> @@ -698,11 +698,11 @@ public void testBulk() throws Exception { // tag::bulk-request BulkRequest request = new BulkRequest(); // <1> request.add(new IndexRequest("posts").id("1") // <2> - .source(XContentType.JSON,"field", "foo")); + .source(MediaTypeRegistry.JSON,"field", "foo")); request.add(new IndexRequest("posts").id("2") // <3> - .source(XContentType.JSON,"field", "bar")); + .source(MediaTypeRegistry.JSON,"field", "bar")); request.add(new IndexRequest("posts").id("3") // <4> - .source(XContentType.JSON,"field", "baz")); + .source(MediaTypeRegistry.JSON,"field", "baz")); // end::bulk-request // tag::bulk-execute BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); @@ -715,9 +715,9 @@ public void testBulk() throws Exception { BulkRequest request = new BulkRequest(); request.add(new DeleteRequest("posts", "3")); // <1> request.add(new UpdateRequest("posts", "2") // <2> - .doc(XContentType.JSON,"other", "test")); + .doc(MediaTypeRegistry.JSON,"other", "test")); request.add(new IndexRequest("posts").id("4") // <3> - .source(XContentType.JSON,"field", "baz")); + .source(MediaTypeRegistry.JSON,"field", "baz")); // end::bulk-request-with-mixed-operations BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); assertSame(RestStatus.OK, bulkResponse.status()); @@ -1580,13 +1580,13 @@ public void afterBulk(long executionId, BulkRequest request, // tag::bulk-processor-add IndexRequest one = new IndexRequest("posts").id("1") - .source(XContentType.JSON, "title", + .source(MediaTypeRegistry.JSON, "title", "In which order are my OpenSearch queries executed?"); IndexRequest two = new IndexRequest("posts").id("2") - .source(XContentType.JSON, "title", + .source(MediaTypeRegistry.JSON, "title", "Current status and upcoming changes in OpenSearch"); IndexRequest three = new IndexRequest("posts").id("3") - .source(XContentType.JSON, "title", + .source(MediaTypeRegistry.JSON, "title", "The Future of Federated Search in OpenSearch"); bulkProcessor.add(one); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java index ccbb64b13b2d2..07062c4796bcb 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java @@ -65,7 +65,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.indices.recovery.RecoverySettings; import org.opensearch.core.rest.RestStatus; @@ -138,7 +138,7 @@ public void testClusterPutSettings() throws IOException { // tag::put-settings-settings-source request.transientSettings( "{\"indices.recovery.max_bytes_per_sec\": \"10b\"}" - , XContentType.JSON); // <1> + , MediaTypeRegistry.JSON); // <1> // end::put-settings-settings-source } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java index de2eb91c6660b..5cad389d32c87 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java @@ -107,9 +107,9 @@ import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.IndexSettings; import org.opensearch.index.query.QueryBuilder; import org.opensearch.index.query.QueryBuilders; @@ -329,7 +329,7 @@ public void testCreateIndex() throws IOException { " }\n" + " }\n" + "}", // <2> - XContentType.JSON); + MediaTypeRegistry.JSON); // end::create-index-request-mappings CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); @@ -407,7 +407,7 @@ public void testCreateIndex() throws IOException { " \"aliases\" : {\n" + " \"twitter_alias\" : {}\n" + " }\n" + - "}", XContentType.JSON); // <1> + "}", MediaTypeRegistry.JSON); // <1> // end::create-index-whole-source // tag::create-index-execute @@ -480,7 +480,7 @@ public void testPutMapping() throws IOException { " }\n" + " }\n" + "}", // <1> - XContentType.JSON); + MediaTypeRegistry.JSON); // end::put-mapping-request-source AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT); assertTrue(putMappingResponse.isAcknowledged()); @@ -585,7 +585,7 @@ public void testGetMapping() throws IOException { CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); PutMappingRequest request = new PutMappingRequest("twitter"); - request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", XContentType.JSON); + request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", MediaTypeRegistry.JSON); AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT); assertTrue(putMappingResponse.isAcknowledged()); } @@ -631,7 +631,7 @@ public void testGetMappingAsync() throws Exception { CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); PutMappingRequest request = new PutMappingRequest("twitter"); - request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", XContentType.JSON); + request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", MediaTypeRegistry.JSON); AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT); assertTrue(putMappingResponse.isAcknowledged()); } @@ -703,7 +703,7 @@ public void testGetFieldMapping() throws IOException, InterruptedException { + " }\n" + " }\n" + "}", // <1> - XContentType.JSON + MediaTypeRegistry.JSON ); AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT); assertTrue(putMappingResponse.isAcknowledged()); @@ -1127,7 +1127,8 @@ public void testGetIndex() throws Exception { { Settings settings = Settings.builder().put("number_of_shards", 3).build(); String mappings = "{\"properties\":{\"field-1\":{\"type\":\"integer\"}}}"; - CreateIndexRequest createIndexRequest = new CreateIndexRequest("index").settings(settings).mapping(mappings, XContentType.JSON); + CreateIndexRequest createIndexRequest = new CreateIndexRequest("index").settings(settings) + .mapping(mappings, MediaTypeRegistry.JSON); CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); } @@ -1830,7 +1831,7 @@ public void testRolloverIndex() throws Exception { // end::rollover-index-request-settings // tag::rollover-index-request-mapping String mappings = "{\"properties\":{\"field-1\":{\"type\":\"keyword\"}}}"; - request.getCreateIndexRequest().mapping(mappings, XContentType.JSON); // <1> + request.getCreateIndexRequest().mapping(mappings, MediaTypeRegistry.JSON); // <1> // end::rollover-index-request-mapping // tag::rollover-index-request-alias request.getCreateIndexRequest().alias(new Alias("another_alias")); // <1> @@ -2009,7 +2010,7 @@ public void testIndexPutSettings() throws Exception { // tag::indices-put-settings-settings-source request.settings( "{\"index.number_of_replicas\": \"2\"}" - , XContentType.JSON); // <1> + , MediaTypeRegistry.JSON); // <1> // end::indices-put-settings-settings-source } @@ -2090,7 +2091,7 @@ public void testPutTemplate() throws Exception { " }\n" + " }\n" + "}", - XContentType.JSON); + MediaTypeRegistry.JSON); // end::put-template-request-mappings-json assertTrue(client.indices().putTemplate(request, RequestOptions.DEFAULT).isAcknowledged()); } @@ -2165,7 +2166,7 @@ public void testPutTemplate() throws Exception { " \"alias-1\": {},\n" + " \"{index}-alias\": {}\n" + " }\n" + - "}", XContentType.JSON); // <1> + "}", MediaTypeRegistry.JSON); // <1> // end::put-template-whole-source // tag::put-template-request-create @@ -2220,7 +2221,7 @@ public void testGetTemplates() throws Exception { PutIndexTemplateRequest putRequest = new PutIndexTemplateRequest("my-template"); putRequest.patterns(Arrays.asList("pattern-1", "log-*")); putRequest.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1)); - putRequest.mapping("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", XContentType.JSON); + putRequest.mapping("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", MediaTypeRegistry.JSON); assertTrue(client.indices().putTemplate(putRequest, RequestOptions.DEFAULT).isAcknowledged()); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java index 6c11aff3d292e..61b004b5ff733 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java @@ -50,7 +50,7 @@ import org.opensearch.client.RestHighLevelClient; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.ingest.PipelineConfiguration; import java.io.IOException; @@ -91,7 +91,7 @@ public void testPutPipeline() throws IOException { PutPipelineRequest request = new PutPipelineRequest( "my-pipeline-id", // <1> new BytesArray(source.getBytes(StandardCharsets.UTF_8)), // <2> - XContentType.JSON // <3> + MediaTypeRegistry.JSON // <3> ); // end::put-pipeline-request @@ -125,7 +125,7 @@ public void testPutPipelineAsync() throws Exception { PutPipelineRequest request = new PutPipelineRequest( "my-pipeline-id", new BytesArray(source.getBytes(StandardCharsets.UTF_8)), - XContentType.JSON + MediaTypeRegistry.JSON ); // tag::put-pipeline-execute-listener @@ -314,7 +314,7 @@ public void testSimulatePipeline() throws IOException { "}"; SimulatePipelineRequest request = new SimulatePipelineRequest( new BytesArray(source.getBytes(StandardCharsets.UTF_8)), // <1> - XContentType.JSON // <2> + MediaTypeRegistry.JSON // <2> ); // end::simulate-pipeline-request @@ -370,7 +370,7 @@ public void testSimulatePipelineAsync() throws Exception { + "}"; SimulatePipelineRequest request = new SimulatePipelineRequest( new BytesArray(source.getBytes(StandardCharsets.UTF_8)), - XContentType.JSON + MediaTypeRegistry.JSON ); // tag::simulate-pipeline-execute-listener diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java index 7f7062f0e8a4c..24aae6d66d8bf 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java @@ -71,7 +71,7 @@ import org.opensearch.common.unit.Fuzziness; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.get.GetResult; import org.opensearch.index.query.MatchQueryBuilder; import org.opensearch.index.query.QueryBuilder; @@ -319,9 +319,9 @@ public void testSearchRequestAggregations() throws IOException { RestHighLevelClient client = highLevelClient(); { BulkRequest request = new BulkRequest(); - request.add(new IndexRequest("posts").id("1").source(XContentType.JSON, "company", "OpenSearch", "age", 20)); - request.add(new IndexRequest("posts").id("2").source(XContentType.JSON, "company", "OpenSearch", "age", 30)); - request.add(new IndexRequest("posts").id("3").source(XContentType.JSON, "company", "OpenSearch", "age", 40)); + request.add(new IndexRequest("posts").id("1").source(MediaTypeRegistry.JSON, "company", "OpenSearch", "age", 20)); + request.add(new IndexRequest("posts").id("2").source(MediaTypeRegistry.JSON, "company", "OpenSearch", "age", 30)); + request.add(new IndexRequest("posts").id("3").source(MediaTypeRegistry.JSON, "company", "OpenSearch", "age", 40)); request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); assertSame(RestStatus.OK, bulkResponse.status()); @@ -392,10 +392,10 @@ public void testSearchRequestSuggestions() throws IOException { RestHighLevelClient client = highLevelClient(); { BulkRequest request = new BulkRequest(); - request.add(new IndexRequest("posts").id("1").source(XContentType.JSON, "user", "foobar")); - request.add(new IndexRequest("posts").id("2").source(XContentType.JSON, "user", "quxx")); - request.add(new IndexRequest("posts").id("3").source(XContentType.JSON, "user", "quzz")); - request.add(new IndexRequest("posts").id("4").source(XContentType.JSON, "user", "corge")); + request.add(new IndexRequest("posts").id("1").source(MediaTypeRegistry.JSON, "user", "foobar")); + request.add(new IndexRequest("posts").id("2").source(MediaTypeRegistry.JSON, "user", "quxx")); + request.add(new IndexRequest("posts").id("3").source(MediaTypeRegistry.JSON, "user", "quzz")); + request.add(new IndexRequest("posts").id("4").source(MediaTypeRegistry.JSON, "user", "corge")); request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); assertSame(RestStatus.OK, bulkResponse.status()); @@ -438,7 +438,7 @@ public void testSearchRequestHighlighting() throws IOException { request.add( new IndexRequest("posts").id("1") .source( - XContentType.JSON, + MediaTypeRegistry.JSON, "title", "In which order are my OpenSearch queries executed?", "user", @@ -450,7 +450,7 @@ public void testSearchRequestHighlighting() throws IOException { request.add( new IndexRequest("posts").id("2") .source( - XContentType.JSON, + MediaTypeRegistry.JSON, "title", "Current status and upcoming changes in OpenSearch", "user", @@ -462,7 +462,7 @@ public void testSearchRequestHighlighting() throws IOException { request.add( new IndexRequest("posts").id("3") .source( - XContentType.JSON, + MediaTypeRegistry.JSON, "title", "The Future of Federated Search in OpenSearch", "user", @@ -525,7 +525,7 @@ public void testSearchRequestHighlighting() throws IOException { public void testSearchRequestProfiling() throws IOException { RestHighLevelClient client = highLevelClient(); { - IndexRequest request = new IndexRequest("posts").id("1").source(XContentType.JSON, "tags", "opensearch", "comments", 123); + IndexRequest request = new IndexRequest("posts").id("1").source(MediaTypeRegistry.JSON, "tags", "opensearch", "comments", 123); request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL); IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT); assertSame(RestStatus.CREATED, indexResponse.status()); @@ -597,13 +597,15 @@ public void testScroll() throws Exception { { BulkRequest request = new BulkRequest(); request.add( - new IndexRequest("posts").id("1").source(XContentType.JSON, "title", "In which order are my OpenSearch queries executed?") + new IndexRequest("posts").id("1") + .source(MediaTypeRegistry.JSON, "title", "In which order are my OpenSearch queries executed?") ); request.add( - new IndexRequest("posts").id("2").source(XContentType.JSON, "title", "Current status and upcoming changes in OpenSearch") + new IndexRequest("posts").id("2") + .source(MediaTypeRegistry.JSON, "title", "Current status and upcoming changes in OpenSearch") ); request.add( - new IndexRequest("posts").id("3").source(XContentType.JSON, "title", "The Future of Federated Search in OpenSearch") + new IndexRequest("posts").id("3").source(MediaTypeRegistry.JSON, "title", "The Future of Federated Search in OpenSearch") ); request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT); @@ -1320,7 +1322,7 @@ private void indexSearchTestData() throws IOException { bulkRequest.add( new IndexRequest("posts").id("1") .source( - XContentType.JSON, + MediaTypeRegistry.JSON, "id", 1, "title", @@ -1334,7 +1336,7 @@ private void indexSearchTestData() throws IOException { bulkRequest.add( new IndexRequest("posts").id("2") .source( - XContentType.JSON, + MediaTypeRegistry.JSON, "id", 2, "title", @@ -1348,7 +1350,7 @@ private void indexSearchTestData() throws IOException { bulkRequest.add( new IndexRequest("posts").id("3") .source( - XContentType.JSON, + MediaTypeRegistry.JSON, "id", 3, "title", @@ -1360,8 +1362,8 @@ private void indexSearchTestData() throws IOException { ) ); - bulkRequest.add(new IndexRequest("authors").id("1").source(XContentType.JSON, "id", 1, "user", "foobar")); - bulkRequest.add(new IndexRequest("contributors").id("1").source(XContentType.JSON, "id", 1, "user", "quuz")); + bulkRequest.add(new IndexRequest("authors").id("1").source(MediaTypeRegistry.JSON, "id", 1, "user", "foobar")); + bulkRequest.add(new IndexRequest("contributors").id("1").source(MediaTypeRegistry.JSON, "id", 1, "user", "quuz")); bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT); @@ -1472,7 +1474,7 @@ private static void indexCountTestData() throws IOException { bulkRequest.add( new IndexRequest("blog").id("1") .source( - XContentType.JSON, + MediaTypeRegistry.JSON, "title", "Doubling Down on Open?", "user", @@ -1484,7 +1486,7 @@ private static void indexCountTestData() throws IOException { bulkRequest.add( new IndexRequest("blog").id("2") .source( - XContentType.JSON, + MediaTypeRegistry.JSON, "title", "XYZ Joins Forces with OpenSearch", "user", @@ -1496,7 +1498,7 @@ private static void indexCountTestData() throws IOException { bulkRequest.add( new IndexRequest("blog").id("3") .source( - XContentType.JSON, + MediaTypeRegistry.JSON, "title", "On Net Neutrality", "user", @@ -1506,7 +1508,7 @@ private static void indexCountTestData() throws IOException { ) ); - bulkRequest.add(new IndexRequest("author").id("1").source(XContentType.JSON, "user", "foobar")); + bulkRequest.add(new IndexRequest("author").id("1").source(MediaTypeRegistry.JSON, "user", "foobar")); bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT); diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java index 976c69910d309..dcd1335e242b0 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java @@ -64,7 +64,7 @@ import org.opensearch.common.Booleans; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.repositories.fs.FsRepository; import org.opensearch.core.rest.RestStatus; import org.opensearch.snapshots.RestoreInfo; @@ -156,7 +156,7 @@ public void testSnapshotCreateRepository() throws IOException { { // tag::create-repository-settings-source request.settings("{\"location\": \".\", \"compress\": \"true\"}", - XContentType.JSON); // <1> + MediaTypeRegistry.JSON); // <1> // end::create-repository-settings-source } @@ -818,7 +818,7 @@ public void onFailure(Exception e) { private void createTestRepositories() throws IOException { PutRepositoryRequest request = new PutRepositoryRequest(repositoryName); request.type(FsRepository.TYPE); - request.settings("{\"location\": \".\"}", XContentType.JSON); + request.settings("{\"location\": \".\"}", MediaTypeRegistry.JSON); assertTrue(highLevelClient().snapshot().createRepository(request, RequestOptions.DEFAULT).isAcknowledged()); } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java index 742dfa69e718b..551973a3912ce 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java @@ -45,9 +45,9 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.unit.TimeValue; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.script.Script; import org.opensearch.script.StoredScriptSource; @@ -88,7 +88,7 @@ public void testGetStoredScript() throws Exception { final StoredScriptSource scriptSource = new StoredScriptSource( "painless", "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType()) ); putStoredScript("calculate-score", scriptSource); @@ -152,7 +152,7 @@ public void testDeleteStoredScript() throws Exception { final StoredScriptSource scriptSource = new StoredScriptSource( "painless", "Math.log(_score * 2) + params.my_modifier", - Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType()) ); putStoredScript("calculate-score", scriptSource); @@ -221,7 +221,7 @@ public void testPutScript() throws Exception { "\"source\": \"Math.log(_score * 2) + params.multiplier\"" + "}\n" + "}\n" - ), XContentType.JSON); // <2> + ), MediaTypeRegistry.JSON); // <2> // end::put-stored-script-request // tag::put-stored-script-context @@ -255,7 +255,7 @@ public void testPutScript() throws Exception { builder.endObject(); } builder.endObject(); - request.content(BytesReference.bytes(builder), XContentType.JSON); // <1> + request.content(BytesReference.bytes(builder), MediaTypeRegistry.JSON); // <1> // end::put-stored-script-content-painless // tag::put-stored-script-execute @@ -310,7 +310,7 @@ public void onFailure(Exception e) { builder.endObject(); } builder.endObject(); - request.content(BytesReference.bytes(builder), XContentType.JSON); // <1> + request.content(BytesReference.bytes(builder), MediaTypeRegistry.JSON); // <1> // end::put-stored-script-content-mustache client.putScript(request, RequestOptions.DEFAULT); @@ -322,7 +322,13 @@ public void onFailure(Exception e) { } private void putStoredScript(String id, StoredScriptSource scriptSource) throws IOException { - PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource); + PutStoredScriptRequest request = new PutStoredScriptRequest( + id, + "score", + new BytesArray("{}"), + MediaTypeRegistry.JSON, + scriptSource + ); assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync)); } } diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexTemplatesResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexTemplatesResponseTests.java index 8c83791d94d42..d1584e5230e34 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexTemplatesResponseTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexTemplatesResponseTests.java @@ -164,7 +164,7 @@ private Predicate randomFieldsExcludeFilter() { private static void assertEqualInstances(GetIndexTemplatesResponse expectedInstance, GetIndexTemplatesResponse newInstance) { assertEquals(expectedInstance, newInstance); // Check there's no doc types at the root of the mapping - Map expectedMap = XContentHelper.convertToMap(new BytesArray(mappingString), true, XContentType.JSON).v2(); + Map expectedMap = XContentHelper.convertToMap(new BytesArray(mappingString), true, MediaTypeRegistry.JSON).v2(); for (IndexTemplateMetadata template : newInstance.getIndexTemplates()) { MappingMetadata mappingMD = template.mappings(); if (mappingMD != null) { @@ -194,7 +194,7 @@ static GetIndexTemplatesResponse createTestInstance() { templateBuilder.version(between(0, 100)); } if (randomBoolean()) { - Map map = XContentHelper.convertToMap(new BytesArray(mappingString), true, XContentType.JSON).v2(); + Map map = XContentHelper.convertToMap(new BytesArray(mappingString), true, MediaTypeRegistry.JSON).v2(); MappingMetadata mapping = new MappingMetadata(MapperService.SINGLE_MAPPING_NAME, map); templateBuilder.mapping(mapping); } diff --git a/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/NodeRestUsageIT.java b/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/NodeRestUsageIT.java index 0f21984e5d8b9..c95cad310f126 100644 --- a/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/NodeRestUsageIT.java +++ b/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/NodeRestUsageIT.java @@ -37,6 +37,7 @@ import org.opensearch.client.ResponseException; import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.search.aggregations.AggregationBuilders; import org.opensearch.search.builder.SearchSourceBuilder; @@ -172,8 +173,8 @@ public void testAggregationUsage() throws IOException { .aggregation(AggregationBuilders.terms("str_terms").field("str.keyword")) .aggregation(AggregationBuilders.terms("num_terms").field("num")) .aggregation(AggregationBuilders.avg("num_avg").field("num")); - searchRequest.setJsonEntity(Strings.toString(XContentType.JSON, searchSource)); - searchRequest.setJsonEntity(Strings.toString(XContentType.JSON, searchSource)); + searchRequest.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, searchSource)); + searchRequest.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, searchSource)); client().performRequest(searchRequest); searchRequest = new Request("GET", "/test/_search"); @@ -182,8 +183,8 @@ public void testAggregationUsage() throws IOException { .aggregation(AggregationBuilders.avg("num1").field("num")) .aggregation(AggregationBuilders.avg("num2").field("num")) .aggregation(AggregationBuilders.terms("foo").field("foo.keyword")); - String r = Strings.toString(XContentType.JSON, searchSource); - searchRequest.setJsonEntity(Strings.toString(XContentType.JSON, searchSource)); + String r = Strings.toString(MediaTypeRegistry.JSON, searchSource); + searchRequest.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, searchSource)); client().performRequest(searchRequest); Response response = client().performRequest(new Request("GET", "_nodes/usage")); diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java index 54329038e1fc5..254c340f8836f 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java @@ -45,7 +45,7 @@ */ public class MapXContentParser extends AbstractXContentParser { - private MediaType xContentType; + private MediaType mediaType; private TokenIterator iterator; private boolean closed; @@ -53,10 +53,10 @@ public MapXContentParser( NamedXContentRegistry xContentRegistry, DeprecationHandler deprecationHandler, Map map, - MediaType xContentType + MediaType mediaType ) { super(xContentRegistry, deprecationHandler); - this.xContentType = xContentType; + this.mediaType = mediaType; this.iterator = new MapIterator(null, null, map); } @@ -105,7 +105,7 @@ protected BigInteger doBigIntegerValue() throws IOException { @Override public MediaType contentType() { - return xContentType; + return mediaType; } @Override diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentHelper.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentHelper.java new file mode 100644 index 0000000000000..a99a12273a6f0 --- /dev/null +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentHelper.java @@ -0,0 +1,53 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * The OpenSearch Contributors require contributions made to + * this file be licensed under the Apache-2.0 license or a + * compatible open source license. + */ + +package org.opensearch.core.xcontent; + +import org.opensearch.core.common.bytes.BytesReference; + +import java.io.IOException; + +/** + * Core XContent Helper Utilities + * + * @opensearch.internal + */ +public final class XContentHelper { + // no instance + private XContentHelper() {} + + /** + * Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided + * {@link MediaType}. Wraps the output into a new anonymous object according to the value returned + * by the {@link ToXContent#isFragment()} method returns. + */ + @Deprecated + public static BytesReference toXContent(ToXContent toXContent, MediaType mediaType, boolean humanReadable) throws IOException { + return toXContent(toXContent, mediaType, ToXContent.EMPTY_PARAMS, humanReadable); + } + + /** + * Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided + * {@link MediaType}. Wraps the output into a new anonymous object according to the value returned + * by the {@link ToXContent#isFragment()} method returns. + */ + public static BytesReference toXContent(ToXContent toXContent, MediaType mediaType, ToXContent.Params params, boolean humanReadable) + throws IOException { + try (XContentBuilder builder = XContentBuilder.builder(mediaType.xContent())) { + builder.humanReadable(humanReadable); + if (toXContent.isFragment()) { + builder.startObject(); + } + toXContent.toXContent(builder, params); + if (toXContent.isFragment()) { + builder.endObject(); + } + return BytesReference.bytes(builder); + } + } +} diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParser.java index 328eaa4bc36e9..a2f16209a5b7f 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParser.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParser.java @@ -48,8 +48,8 @@ * To obtain an instance of this class use the following pattern: * *
- *     XContentType xContentType = XContentType.JSON;
- *     XContentParser parser = xContentType.xContent().createParser(
+ *     MediaType mediaType = MediaTypeRegistry.JSON;
+ *     XContentParser parser = mediaType.xContent().createParser(
  *          NamedXContentRegistry.EMPTY, ParserField."{\"key\" : \"value\"}");
  * 
* diff --git a/libs/core/src/test/java/org/opensearch/core/action/support/DefaultShardOperationFailedExceptionTests.java b/libs/core/src/test/java/org/opensearch/core/action/support/DefaultShardOperationFailedExceptionTests.java index 9801e9cbcdb44..985a7fdf3614b 100644 --- a/libs/core/src/test/java/org/opensearch/core/action/support/DefaultShardOperationFailedExceptionTests.java +++ b/libs/core/src/test/java/org/opensearch/core/action/support/DefaultShardOperationFailedExceptionTests.java @@ -44,6 +44,7 @@ import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -92,7 +93,7 @@ public void testToXContent() throws IOException { assertEquals( "{\"shard\":-1,\"index\":null,\"status\":\"INTERNAL_SERVER_ERROR\"," + "\"reason\":{\"type\":\"exception\",\"reason\":\"foo\"}}", - Strings.toString(XContentType.JSON, exception) + Strings.toString(MediaTypeRegistry.JSON, exception) ); } { @@ -102,7 +103,7 @@ public void testToXContent() throws IOException { assertEquals( "{\"shard\":-1,\"index\":null,\"status\":\"INTERNAL_SERVER_ERROR\",\"reason\":{\"type\":\"exception\"," + "\"reason\":\"foo\",\"caused_by\":{\"type\":\"illegal_argument_exception\",\"reason\":\"bar\"}}}", - Strings.toString(XContentType.JSON, exception) + Strings.toString(MediaTypeRegistry.JSON, exception) ); } { @@ -112,7 +113,7 @@ public void testToXContent() throws IOException { assertEquals( "{\"shard\":2,\"index\":\"test\",\"status\":\"INTERNAL_SERVER_ERROR\"," + "\"reason\":{\"type\":\"illegal_state_exception\",\"reason\":\"bar\"}}", - Strings.toString(XContentType.JSON, exception) + Strings.toString(MediaTypeRegistry.JSON, exception) ); } { @@ -124,7 +125,7 @@ public void testToXContent() throws IOException { assertEquals( "{\"shard\":1,\"index\":\"test\",\"status\":\"BAD_REQUEST\"," + "\"reason\":{\"type\":\"illegal_argument_exception\",\"reason\":\"foo\"}}", - Strings.toString(XContentType.JSON, exception) + Strings.toString(MediaTypeRegistry.JSON, exception) ); } } diff --git a/libs/x-content/src/test/java/org/opensearch/common/xcontent/ObjectParserTests.java b/libs/x-content/src/test/java/org/opensearch/common/xcontent/ObjectParserTests.java index 6e7de4aa6bfe5..22ba914d9b165 100644 --- a/libs/x-content/src/test/java/org/opensearch/common/xcontent/ObjectParserTests.java +++ b/libs/x-content/src/test/java/org/opensearch/common/xcontent/ObjectParserTests.java @@ -33,6 +33,7 @@ import org.opensearch.common.CheckedFunction; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParserUtils; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ObjectParser.NamedObjectParser; @@ -394,7 +395,7 @@ public void testAllVariants() throws IOException { double expectedNullableDouble; int expectedNullableInt; - XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder(); builder.startObject(); builder.field("int_field", randomBoolean() ? "1" : 1); if (randomBoolean()) { @@ -646,7 +647,7 @@ public void testParseNamedObjectsInOrderNotSupported() throws IOException { } public void testIgnoreUnknownFields() throws IOException { - XContentBuilder b = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder b = MediaTypeRegistry.JSON.contentBuilder(); b.startObject(); { b.field("test", "foo"); @@ -668,7 +669,7 @@ class TestStruct { } public void testIgnoreUnknownObjects() throws IOException { - XContentBuilder b = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder b = MediaTypeRegistry.JSON.contentBuilder(); b.startObject(); { b.field("test", "foo"); @@ -694,7 +695,7 @@ class TestStruct { } public void testIgnoreUnknownArrays() throws IOException { - XContentBuilder b = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder b = MediaTypeRegistry.JSON.contentBuilder(); b.startObject(); { b.field("test", "foo"); diff --git a/modules/ingest-common/src/internalClusterTest/java/org/opensearch/ingest/common/IngestRestartIT.java b/modules/ingest-common/src/internalClusterTest/java/org/opensearch/ingest/common/IngestRestartIT.java index 49c7c7ae152c0..3dc450df534f3 100644 --- a/modules/ingest-common/src/internalClusterTest/java/org/opensearch/ingest/common/IngestRestartIT.java +++ b/modules/ingest-common/src/internalClusterTest/java/org/opensearch/ingest/common/IngestRestartIT.java @@ -36,7 +36,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.ingest.IngestStats; import org.opensearch.plugins.Plugin; import org.opensearch.script.MockScriptEngine; @@ -108,7 +108,7 @@ public void testFailureInConditionalProcessor() { + " ]\n" + "}" ), - XContentType.JSON + MediaTypeRegistry.JSON ) .get(); @@ -160,8 +160,8 @@ public void testScriptDisabled() throws Exception { equalTo(id) ); - client().admin().cluster().preparePutPipeline(pipelineIdWithScript, pipelineWithScript, XContentType.JSON).get(); - client().admin().cluster().preparePutPipeline(pipelineIdWithoutScript, pipelineWithoutScript, XContentType.JSON).get(); + client().admin().cluster().preparePutPipeline(pipelineIdWithScript, pipelineWithScript, MediaTypeRegistry.JSON).get(); + client().admin().cluster().preparePutPipeline(pipelineIdWithoutScript, pipelineWithoutScript, MediaTypeRegistry.JSON).get(); checkPipelineExists.accept(pipelineIdWithScript); checkPipelineExists.accept(pipelineIdWithoutScript); @@ -225,7 +225,7 @@ public void testPipelineWithScriptProcessorThatHasStoredScript() throws Exceptio .setId("1") .setContent( new BytesArray("{\"script\": {\"lang\": \"" + MockScriptEngine.NAME + "\", \"source\": \"my_script\"} }"), - XContentType.JSON + MediaTypeRegistry.JSON ) .get(); BytesReference pipeline = new BytesArray( @@ -236,7 +236,7 @@ public void testPipelineWithScriptProcessorThatHasStoredScript() throws Exceptio + " ]\n" + "}" ); - client().admin().cluster().preparePutPipeline("_id", pipeline, XContentType.JSON).get(); + client().admin().cluster().preparePutPipeline("_id", pipeline, MediaTypeRegistry.JSON).get(); client().prepareIndex("index") .setId("1") @@ -277,7 +277,7 @@ public void testWithDedicatedIngestNode() throws Exception { BytesReference pipeline = new BytesArray( "{\n" + " \"processors\" : [\n" + " {\"set\" : {\"field\": \"y\", \"value\": 0}}\n" + " ]\n" + "}" ); - client().admin().cluster().preparePutPipeline("_id", pipeline, XContentType.JSON).get(); + client().admin().cluster().preparePutPipeline("_id", pipeline, MediaTypeRegistry.JSON).get(); client().prepareIndex("index") .setId("1") diff --git a/modules/ingest-common/src/main/java/org/opensearch/ingest/common/ScriptProcessor.java b/modules/ingest-common/src/main/java/org/opensearch/ingest/common/ScriptProcessor.java index b66d0b709a824..6a22a0b1385a6 100644 --- a/modules/ingest-common/src/main/java/org/opensearch/ingest/common/ScriptProcessor.java +++ b/modules/ingest-common/src/main/java/org/opensearch/ingest/common/ScriptProcessor.java @@ -36,10 +36,10 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.util.CollectionUtils; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.ingest.AbstractProcessor; import org.opensearch.ingest.IngestDocument; @@ -137,7 +137,7 @@ public ScriptProcessor create( try ( XContentBuilder builder = XContentBuilder.builder(JsonXContent.jsonXContent).map(config); InputStream stream = BytesReference.bytes(builder).streamInput(); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, stream) ) { Script script = Script.parse(parser); diff --git a/modules/ingest-common/src/test/java/org/opensearch/ingest/common/JsonProcessorTests.java b/modules/ingest-common/src/test/java/org/opensearch/ingest/common/JsonProcessorTests.java index 531e22a386236..a197b5c9a7d89 100644 --- a/modules/ingest-common/src/test/java/org/opensearch/ingest/common/JsonProcessorTests.java +++ b/modules/ingest-common/src/test/java/org/opensearch/ingest/common/JsonProcessorTests.java @@ -33,9 +33,9 @@ package org.opensearch.ingest.common; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.ingest.IngestDocument; import org.opensearch.ingest.RandomDocumentPicks; @@ -61,7 +61,7 @@ public void testExecute() throws Exception { Map randomJsonMap = RandomDocumentPicks.randomSource(random()); XContentBuilder builder = JsonXContent.contentBuilder().map(randomJsonMap); - String randomJson = XContentHelper.convertToJson(BytesReference.bytes(builder), false, XContentType.JSON); + String randomJson = XContentHelper.convertToJson(BytesReference.bytes(builder), false, MediaTypeRegistry.JSON); document.put(randomField, randomJson); IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random(), document); diff --git a/modules/ingest-geoip/src/internalClusterTest/java/org/opensearch/ingest/geoip/GeoIpProcessorNonIngestNodeIT.java b/modules/ingest-geoip/src/internalClusterTest/java/org/opensearch/ingest/geoip/GeoIpProcessorNonIngestNodeIT.java index b947f929fce76..ebf298be74a80 100644 --- a/modules/ingest-geoip/src/internalClusterTest/java/org/opensearch/ingest/geoip/GeoIpProcessorNonIngestNodeIT.java +++ b/modules/ingest-geoip/src/internalClusterTest/java/org/opensearch/ingest/geoip/GeoIpProcessorNonIngestNodeIT.java @@ -39,8 +39,8 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Setting; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.ingest.IngestService; import org.opensearch.plugins.Plugin; @@ -158,7 +158,7 @@ public void testLazyLoading() throws IOException { builder.endObject(); bytes = BytesReference.bytes(builder); } - assertAcked(client().admin().cluster().putPipeline(new PutPipelineRequest("geoip", bytes, XContentType.JSON)).actionGet()); + assertAcked(client().admin().cluster().putPipeline(new PutPipelineRequest("geoip", bytes, MediaTypeRegistry.JSON)).actionGet()); // the geo-IP databases should not be loaded on any nodes as they are all non-ingest nodes Arrays.stream(internalCluster().getNodeNames()).forEach(node -> assertDatabaseLoadStatus(node, false)); diff --git a/modules/lang-expression/src/internalClusterTest/java/org/opensearch/script/expression/StoredExpressionIT.java b/modules/lang-expression/src/internalClusterTest/java/org/opensearch/script/expression/StoredExpressionIT.java index 7527092f4344c..3344d4e419924 100644 --- a/modules/lang-expression/src/internalClusterTest/java/org/opensearch/script/expression/StoredExpressionIT.java +++ b/modules/lang-expression/src/internalClusterTest/java/org/opensearch/script/expression/StoredExpressionIT.java @@ -34,7 +34,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.plugins.Plugin; import org.opensearch.script.Script; import org.opensearch.script.ScriptType; @@ -67,9 +67,9 @@ public void testAllOpsDisabledIndexedScripts() throws IOException { .cluster() .preparePutStoredScript() .setId("script1") - .setContent(new BytesArray("{\"script\": {\"lang\": \"expression\", \"source\": \"2\"} }"), XContentType.JSON) + .setContent(new BytesArray("{\"script\": {\"lang\": \"expression\", \"source\": \"2\"} }"), MediaTypeRegistry.JSON) .get(); - client().prepareIndex("test").setId("1").setSource("{\"theField\":\"foo\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{\"theField\":\"foo\"}", MediaTypeRegistry.JSON).get(); try { client().prepareUpdate("test", "1").setScript(new Script(ScriptType.STORED, null, "script1", Collections.emptyMap())).get(); fail("update script should have been rejected"); diff --git a/modules/lang-mustache/src/internalClusterTest/java/org/opensearch/script/mustache/SearchTemplateIT.java b/modules/lang-mustache/src/internalClusterTest/java/org/opensearch/script/mustache/SearchTemplateIT.java index d0a0b7bcd3e3e..9cdd89dadfd8d 100644 --- a/modules/lang-mustache/src/internalClusterTest/java/org/opensearch/script/mustache/SearchTemplateIT.java +++ b/modules/lang-mustache/src/internalClusterTest/java/org/opensearch/script/mustache/SearchTemplateIT.java @@ -36,8 +36,8 @@ import org.opensearch.action.bulk.BulkRequestBuilder; import org.opensearch.action.search.SearchRequest; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.plugins.Plugin; import org.opensearch.script.ScriptType; import org.opensearch.test.OpenSearchSingleNodeTestCase; @@ -177,7 +177,7 @@ public void testIndexedTemplateClient() throws Exception { + " }" + "}" ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -185,11 +185,11 @@ public void testIndexedTemplateClient() throws Exception { assertNotNull(getResponse.getSource()); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); - bulkRequestBuilder.add(client().prepareIndex("test").setId("1").setSource("{\"theField\":\"foo\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("2").setSource("{\"theField\":\"foo 2\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("3").setSource("{\"theField\":\"foo 3\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("4").setSource("{\"theField\":\"foo 4\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("5").setSource("{\"theField\":\"bar\"}", XContentType.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("1").setSource("{\"theField\":\"foo\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("2").setSource("{\"theField\":\"foo 2\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("3").setSource("{\"theField\":\"foo 3\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("4").setSource("{\"theField\":\"foo 4\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("5").setSource("{\"theField\":\"bar\"}", MediaTypeRegistry.JSON)); bulkRequestBuilder.get(); client().admin().indices().prepareRefresh().get(); @@ -224,16 +224,22 @@ public void testIndexedTemplate() throws Exception { + " }" + "}"; - assertAcked(client().admin().cluster().preparePutStoredScript().setId("1a").setContent(new BytesArray(script), XContentType.JSON)); - assertAcked(client().admin().cluster().preparePutStoredScript().setId("2").setContent(new BytesArray(script), XContentType.JSON)); - assertAcked(client().admin().cluster().preparePutStoredScript().setId("3").setContent(new BytesArray(script), XContentType.JSON)); + assertAcked( + client().admin().cluster().preparePutStoredScript().setId("1a").setContent(new BytesArray(script), MediaTypeRegistry.JSON) + ); + assertAcked( + client().admin().cluster().preparePutStoredScript().setId("2").setContent(new BytesArray(script), MediaTypeRegistry.JSON) + ); + assertAcked( + client().admin().cluster().preparePutStoredScript().setId("3").setContent(new BytesArray(script), MediaTypeRegistry.JSON) + ); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); - bulkRequestBuilder.add(client().prepareIndex("test").setId("1").setSource("{\"theField\":\"foo\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("2").setSource("{\"theField\":\"foo 2\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("3").setSource("{\"theField\":\"foo 3\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("4").setSource("{\"theField\":\"foo 4\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("5").setSource("{\"theField\":\"bar\"}", XContentType.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("1").setSource("{\"theField\":\"foo\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("2").setSource("{\"theField\":\"foo 2\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("3").setSource("{\"theField\":\"foo 3\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("4").setSource("{\"theField\":\"foo 4\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("5").setSource("{\"theField\":\"bar\"}", MediaTypeRegistry.JSON)); bulkRequestBuilder.get(); client().admin().indices().prepareRefresh().get(); @@ -295,7 +301,7 @@ public void testIndexedTemplateOverwrite() throws Exception { .cluster() .preparePutStoredScript() .setId("git01") - .setContent(new BytesArray(query.replace("{{slop}}", Integer.toString(-1))), XContentType.JSON) + .setContent(new BytesArray(query.replace("{{slop}}", Integer.toString(-1))), MediaTypeRegistry.JSON) ); GetStoredScriptResponse getResponse = client().admin().cluster().prepareGetStoredScript("git01").get(); @@ -319,7 +325,7 @@ public void testIndexedTemplateOverwrite() throws Exception { .cluster() .preparePutStoredScript() .setId("git01") - .setContent(new BytesArray(query.replace("{{slop}}", Integer.toString(0))), XContentType.JSON) + .setContent(new BytesArray(query.replace("{{slop}}", Integer.toString(0))), MediaTypeRegistry.JSON) ); SearchTemplateResponse searchResponse = new SearchTemplateRequestBuilder(client()).setRequest(new SearchRequest("testindex")) @@ -349,14 +355,14 @@ public void testIndexedTemplateWithArray() throws Exception { + " }\n" + "}"; assertAcked( - client().admin().cluster().preparePutStoredScript().setId("4").setContent(new BytesArray(multiQuery), XContentType.JSON) + client().admin().cluster().preparePutStoredScript().setId("4").setContent(new BytesArray(multiQuery), MediaTypeRegistry.JSON) ); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); - bulkRequestBuilder.add(client().prepareIndex("test").setId("1").setSource("{\"theField\":\"foo\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("2").setSource("{\"theField\":\"foo 2\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("3").setSource("{\"theField\":\"foo 3\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("4").setSource("{\"theField\":\"foo 4\"}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("test").setId("5").setSource("{\"theField\":\"bar\"}", XContentType.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("1").setSource("{\"theField\":\"foo\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("2").setSource("{\"theField\":\"foo 2\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("3").setSource("{\"theField\":\"foo 3\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("4").setSource("{\"theField\":\"foo 4\"}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("test").setId("5").setSource("{\"theField\":\"bar\"}", MediaTypeRegistry.JSON)); bulkRequestBuilder.get(); client().admin().indices().prepareRefresh().get(); diff --git a/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/CustomMustacheFactory.java b/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/CustomMustacheFactory.java index 0cf1ed525fbfe..55f530740813b 100644 --- a/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/CustomMustacheFactory.java +++ b/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/CustomMustacheFactory.java @@ -44,8 +44,8 @@ import com.github.mustachejava.codes.IterableCode; import com.github.mustachejava.codes.WriteCode; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.io.StringWriter; @@ -214,7 +214,7 @@ protected Function createFunction(Object resolved) { if (resolved == null) { return null; } - try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) { + try (XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder()) { if (resolved instanceof Iterable) { builder.startArray(); for (Object o : (Iterable) resolved) { diff --git a/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/MultiSearchTemplateResponse.java b/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/MultiSearchTemplateResponse.java index 49f5d4194d446..9587b9583aeb2 100644 --- a/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/MultiSearchTemplateResponse.java +++ b/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/MultiSearchTemplateResponse.java @@ -41,7 +41,7 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -200,6 +200,6 @@ public static MultiSearchTemplateResponse fromXContext(XContentParser parser) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/SearchTemplateResponse.java b/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/SearchTemplateResponse.java index da67a0d2dd13a..66dcc89261229 100644 --- a/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/SearchTemplateResponse.java +++ b/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/SearchTemplateResponse.java @@ -43,7 +43,6 @@ import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.rest.RestStatus; import java.io.IOException; @@ -104,7 +103,7 @@ public static SearchTemplateResponse fromXContent(XContentParser parser) throws if (contentAsMap.containsKey(TEMPLATE_OUTPUT_FIELD.getPreferredName())) { Object source = contentAsMap.get(TEMPLATE_OUTPUT_FIELD.getPreferredName()); - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON).value(source); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON).value(source); searchTemplateResponse.setSource(BytesReference.bytes(builder)); } else { MediaType contentType = parser.contentType(); @@ -126,7 +125,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.startObject(); // we can assume the template is always json as we convert it before compiling it try (InputStream stream = source.streamInput()) { - builder.rawField(TEMPLATE_OUTPUT_FIELD.getPreferredName(), stream, XContentType.JSON); + builder.rawField(TEMPLATE_OUTPUT_FIELD.getPreferredName(), stream, MediaTypeRegistry.JSON); } builder.endObject(); } diff --git a/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/TransportSearchTemplateAction.java b/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/TransportSearchTemplateAction.java index f6b0cc4eecf9a..6ec5dc8f7f9ca 100644 --- a/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/TransportSearchTemplateAction.java +++ b/modules/lang-mustache/src/main/java/org/opensearch/script/mustache/TransportSearchTemplateAction.java @@ -41,9 +41,9 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.inject.Inject; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.rest.action.search.RestSearchAction; import org.opensearch.script.Script; import org.opensearch.script.ScriptService; @@ -131,7 +131,8 @@ static SearchRequest convert( } try ( - XContentParser parser = XContentType.JSON.xContent().createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, source) + XContentParser parser = MediaTypeRegistry.JSON.xContent() + .createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, source) ) { SearchSourceBuilder builder = SearchSourceBuilder.searchSource(); builder.parseXContent(parser, false); diff --git a/modules/lang-mustache/src/test/java/org/opensearch/script/mustache/MultiSearchTemplateRequestTests.java b/modules/lang-mustache/src/test/java/org/opensearch/script/mustache/MultiSearchTemplateRequestTests.java index 311f14cb8d80d..7499d86f70b2b 100644 --- a/modules/lang-mustache/src/test/java/org/opensearch/script/mustache/MultiSearchTemplateRequestTests.java +++ b/modules/lang-mustache/src/test/java/org/opensearch/script/mustache/MultiSearchTemplateRequestTests.java @@ -34,7 +34,7 @@ import org.opensearch.action.search.SearchRequest; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.rest.RestRequest; import org.opensearch.script.ScriptType; import org.opensearch.search.Scroll; @@ -56,7 +56,7 @@ public class MultiSearchTemplateRequestTests extends OpenSearchTestCase { public void testParseRequest() throws Exception { byte[] data = StreamsUtils.copyToBytesFromClasspath("/org/opensearch/script/mustache/simple-msearch-template.json"); - RestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(data), XContentType.JSON) + RestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(data), MediaTypeRegistry.JSON) .build(); MultiSearchTemplateRequest request = RestMultiSearchTemplateAction.parseRequest(restRequest, true); @@ -92,8 +92,10 @@ public void testParseRequest() throws Exception { public void testParseWithCarriageReturn() throws Exception { final String content = "{\"index\":[\"test0\", \"test1\"], \"request_cache\": true}\r\n" + "{\"source\": {\"query\" : {\"match_{{template}}\" :{}}}, \"params\": {\"template\": \"all\" } }\r\n"; - RestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(content), XContentType.JSON) - .build(); + RestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent( + new BytesArray(content), + MediaTypeRegistry.JSON + ).build(); MultiSearchTemplateRequest request = RestMultiSearchTemplateAction.parseRequest(restRequest, true); @@ -144,8 +146,10 @@ public void testMultiSearchTemplateToJson() throws Exception { String serialized = toJsonString(multiSearchTemplateRequest); // Deserialize the request - RestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(serialized), XContentType.JSON) - .build(); + RestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent( + new BytesArray(serialized), + MediaTypeRegistry.JSON + ).build(); MultiSearchTemplateRequest deser = RestMultiSearchTemplateAction.parseRequest(restRequest, true); // For object equality purposes need to set the search requests' source to non-null @@ -163,7 +167,7 @@ public void testMultiSearchTemplateToJson() throws Exception { } protected String toJsonString(MultiSearchTemplateRequest multiSearchTemplateRequest) throws IOException { - byte[] bytes = MultiSearchTemplateRequest.writeMultiLineFormat(multiSearchTemplateRequest, XContentType.JSON.xContent()); + byte[] bytes = MultiSearchTemplateRequest.writeMultiLineFormat(multiSearchTemplateRequest, MediaTypeRegistry.JSON.xContent()); return new String(bytes, StandardCharsets.UTF_8); } diff --git a/modules/lang-mustache/src/test/java/org/opensearch/script/mustache/SearchTemplateResponseTests.java b/modules/lang-mustache/src/test/java/org/opensearch/script/mustache/SearchTemplateResponseTests.java index fd0a4e9612a8f..2c9500852897f 100644 --- a/modules/lang-mustache/src/test/java/org/opensearch/script/mustache/SearchTemplateResponseTests.java +++ b/modules/lang-mustache/src/test/java/org/opensearch/script/mustache/SearchTemplateResponseTests.java @@ -130,7 +130,7 @@ protected void assertEqualInstances(SearchTemplateResponse expectedInstance, Sea assertEquals(expectedSource == null, newSource == null); if (expectedSource != null) { try { - assertToXContentEquivalent(expectedSource, newSource, XContentType.JSON); + assertToXContentEquivalent(expectedSource, newSource, MediaTypeRegistry.JSON); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/modules/lang-painless/src/test/java/org/opensearch/painless/action/PainlessExecuteApiTests.java b/modules/lang-painless/src/test/java/org/opensearch/painless/action/PainlessExecuteApiTests.java index e80cc2d23e290..3bc1e806879ce 100644 --- a/modules/lang-painless/src/test/java/org/opensearch/painless/action/PainlessExecuteApiTests.java +++ b/modules/lang-painless/src/test/java/org/opensearch/painless/action/PainlessExecuteApiTests.java @@ -33,7 +33,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.query.MatchQueryBuilder; import org.opensearch.painless.PainlessModulePlugin; @@ -92,13 +92,13 @@ public void testFilterExecutionContext() throws IOException { IndexService indexService = createIndex("index", Settings.EMPTY, "doc", "field", "type=long"); Request.ContextSetup contextSetup = new Request.ContextSetup("index", new BytesArray("{\"field\": 3}"), null); - contextSetup.setXContentType(XContentType.JSON); + contextSetup.setXContentType(MediaTypeRegistry.JSON); Request request = new Request(new Script("doc['field'].value >= 3"), "filter", contextSetup); Response response = innerShardOperation(request, scriptService, indexService); assertThat(response.getResult(), equalTo(true)); contextSetup = new Request.ContextSetup("index", new BytesArray("{\"field\": 3}"), null); - contextSetup.setXContentType(XContentType.JSON); + contextSetup.setXContentType(MediaTypeRegistry.JSON); request = new Request( new Script(ScriptType.INLINE, "painless", "doc['field'].value >= params.max", singletonMap("max", 3)), "filter", @@ -108,7 +108,7 @@ public void testFilterExecutionContext() throws IOException { assertThat(response.getResult(), equalTo(true)); contextSetup = new Request.ContextSetup("index", new BytesArray("{\"field\": 2}"), null); - contextSetup.setXContentType(XContentType.JSON); + contextSetup.setXContentType(MediaTypeRegistry.JSON); request = new Request( new Script(ScriptType.INLINE, "painless", "doc['field'].value >= params.max", singletonMap("max", 3)), "filter", @@ -127,7 +127,7 @@ public void testScoreExecutionContext() throws IOException { new BytesArray("{\"rank\": 4.0, \"text\": \"quick brown fox\"}"), new MatchQueryBuilder("text", "fox") ); - contextSetup.setXContentType(XContentType.JSON); + contextSetup.setXContentType(MediaTypeRegistry.JSON); Request request = new Request( new Script( ScriptType.INLINE, diff --git a/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/BWCTemplateTests.java b/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/BWCTemplateTests.java index d498116efc108..6b14a1d930287 100644 --- a/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/BWCTemplateTests.java +++ b/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/BWCTemplateTests.java @@ -32,7 +32,7 @@ package org.opensearch.index.mapper; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.plugins.Plugin; import org.opensearch.test.OpenSearchSingleNodeTestCase; @@ -54,9 +54,9 @@ public void testBeatsTemplatesBWC() throws Exception { byte[] metricBeat = copyToBytesFromClasspath("/org/opensearch/index/mapper/metricbeat-6.0.template.json"); byte[] packetBeat = copyToBytesFromClasspath("/org/opensearch/index/mapper/packetbeat-6.0.template.json"); byte[] fileBeat = copyToBytesFromClasspath("/org/opensearch/index/mapper/filebeat-6.0.template.json"); - client().admin().indices().preparePutTemplate("metricbeat").setSource(metricBeat, XContentType.JSON).get(); - client().admin().indices().preparePutTemplate("packetbeat").setSource(packetBeat, XContentType.JSON).get(); - client().admin().indices().preparePutTemplate("filebeat").setSource(fileBeat, XContentType.JSON).get(); + client().admin().indices().preparePutTemplate("metricbeat").setSource(metricBeat, MediaTypeRegistry.JSON).get(); + client().admin().indices().preparePutTemplate("packetbeat").setSource(packetBeat, MediaTypeRegistry.JSON).get(); + client().admin().indices().preparePutTemplate("filebeat").setSource(fileBeat, MediaTypeRegistry.JSON).get(); client().prepareIndex("metricbeat-foo").setId("1").setSource("message", "foo").get(); client().prepareIndex("packetbeat-foo").setId("1").setSource("message", "foo").get(); diff --git a/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/RankFeatureMetaFieldMapperTests.java b/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/RankFeatureMetaFieldMapperTests.java index d35368350592c..c0b4b44b7935f 100644 --- a/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/RankFeatureMetaFieldMapperTests.java +++ b/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/RankFeatureMetaFieldMapperTests.java @@ -34,7 +34,6 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.plugins.Plugin; @@ -91,7 +90,7 @@ public void testDocumentParsingFailsOnMetaField() throws Exception { ); MapperParsingException e = expectThrows( MapperParsingException.class, - () -> mapper.parse(new SourceToParse("test", "1", bytes, XContentType.JSON)) + () -> mapper.parse(new SourceToParse("test", "1", bytes, MediaTypeRegistry.JSON)) ); assertTrue( e.getCause().getMessage().contains("Field [" + rfMetaField + "] is a metadata field and cannot be added inside a document.") diff --git a/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/ScaledFloatFieldMapperTests.java b/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/ScaledFloatFieldMapperTests.java index 4de11d7f64e8e..f0cd389fe3f94 100644 --- a/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/ScaledFloatFieldMapperTests.java +++ b/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/ScaledFloatFieldMapperTests.java @@ -35,9 +35,9 @@ import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.IndexableField; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.plugins.Plugin; import java.io.IOException; @@ -135,7 +135,7 @@ public void testNotIndexed() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", 123).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -156,7 +156,7 @@ public void testNoDocValues() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", 123).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -177,7 +177,7 @@ public void testStore() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", 123).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -200,7 +200,7 @@ public void testCoerce() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "123").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = doc.rootDoc().getFields("field"); @@ -219,7 +219,7 @@ public void testCoerce() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "123").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); MapperParsingException e = expectThrows(MapperParsingException.class, runnable); @@ -243,7 +243,7 @@ private void doTestIgnoreMalformed(Object value, String exceptionMessageContains "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", value).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); MapperParsingException e = expectThrows(MapperParsingException.class, runnable); @@ -257,7 +257,7 @@ private void doTestIgnoreMalformed(Object value, String exceptionMessageContains "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", value).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -272,7 +272,7 @@ public void testNullValue() throws IOException { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().nullField("field").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertArrayEquals(new IndexableField[0], doc.rootDoc().getFields("field")); @@ -285,7 +285,7 @@ public void testNullValue() throws IOException { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().nullField("field").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = doc.rootDoc().getFields("field"); diff --git a/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/SearchAsYouTypeFieldMapperTests.java b/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/SearchAsYouTypeFieldMapperTests.java index 551bd38b65f59..b5f687ce34d4b 100644 --- a/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/SearchAsYouTypeFieldMapperTests.java +++ b/modules/mapper-extras/src/test/java/org/opensearch/index/mapper/SearchAsYouTypeFieldMapperTests.java @@ -51,8 +51,8 @@ import org.apache.lucene.search.SynonymQuery; import org.apache.lucene.search.TermQuery; import org.opensearch.common.lucene.search.MultiPhrasePrefixQuery; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.index.IndexSettings; import org.opensearch.index.analysis.AnalyzerScope; @@ -600,7 +600,7 @@ public void testAnalyzerSerialization() throws IOException { b.field("type", "search_as_you_type"); b.field("analyzer", "simple"); })); - String serialized = Strings.toString(XContentType.JSON, ms.documentMapper()); + String serialized = Strings.toString(MediaTypeRegistry.JSON, ms.documentMapper()); assertEquals( serialized, "{\"_doc\":{\"properties\":{\"field\":" @@ -608,7 +608,7 @@ public void testAnalyzerSerialization() throws IOException { ); merge(ms, mapping(b -> {})); - assertEquals(serialized, Strings.toString(XContentType.JSON, ms.documentMapper())); + assertEquals(serialized, Strings.toString(MediaTypeRegistry.JSON, ms.documentMapper())); } private void documentParsingTestCase(Collection values) throws IOException { diff --git a/modules/parent-join/src/test/java/org/opensearch/join/mapper/ParentJoinFieldMapperTests.java b/modules/parent-join/src/test/java/org/opensearch/join/mapper/ParentJoinFieldMapperTests.java index 213ba43ee34cd..ed6a8259d6e90 100644 --- a/modules/parent-join/src/test/java/org/opensearch/join/mapper/ParentJoinFieldMapperTests.java +++ b/modules/parent-join/src/test/java/org/opensearch/join/mapper/ParentJoinFieldMapperTests.java @@ -34,8 +34,8 @@ import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.DocumentMapper; import org.opensearch.index.mapper.MapperException; @@ -78,7 +78,12 @@ public void testSingleLevel() throws Exception { // Doc without join ParsedDocument doc = docMapper.parse( - new SourceToParse("test", "0", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().endObject()), XContentType.JSON) + new SourceToParse( + "test", + "0", + BytesReference.bytes(MediaTypeRegistry.JSON.contentBuilder().startObject().endObject()), + MediaTypeRegistry.JSON + ) ); assertNull(doc.rootDoc().getBinaryValue("join_field")); @@ -88,7 +93,7 @@ public void testSingleLevel() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("join_field", "parent").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertEquals("1", doc.rootDoc().getBinaryValue("join_field#parent").utf8ToString()); @@ -108,7 +113,7 @@ public void testSingleLevel() throws Exception { .endObject() .endObject() ), - XContentType.JSON, + MediaTypeRegistry.JSON, "1" ) ); @@ -123,7 +128,7 @@ public void testSingleLevel() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("join_field", "unknown").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ); @@ -159,7 +164,7 @@ public void testParentIdSpecifiedAsNumber() throws Exception { .endObject() .endObject() ), - XContentType.JSON, + MediaTypeRegistry.JSON, "1" ) ); @@ -178,7 +183,7 @@ public void testParentIdSpecifiedAsNumber() throws Exception { .endObject() .endObject() ), - XContentType.JSON, + MediaTypeRegistry.JSON, "1" ) ); @@ -207,7 +212,12 @@ public void testMultipleLevels() throws Exception { // Doc without join ParsedDocument doc = docMapper.parse( - new SourceToParse("test", "0", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().endObject()), XContentType.JSON) + new SourceToParse( + "test", + "0", + BytesReference.bytes(XContentFactory.jsonBuilder().startObject().endObject()), + MediaTypeRegistry.JSON + ) ); assertNull(doc.rootDoc().getBinaryValue("join_field")); @@ -217,7 +227,7 @@ public void testMultipleLevels() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("join_field", "parent").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertEquals("1", doc.rootDoc().getBinaryValue("join_field#parent").utf8ToString()); @@ -237,7 +247,7 @@ public void testMultipleLevels() throws Exception { .endObject() .endObject() ), - XContentType.JSON, + MediaTypeRegistry.JSON, "1" ) ); @@ -253,7 +263,7 @@ public void testMultipleLevels() throws Exception { "test", "2", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("join_field", "child").endObject()), - XContentType.JSON, + MediaTypeRegistry.JSON, "1" ) ) @@ -276,7 +286,7 @@ public void testMultipleLevels() throws Exception { .endObject() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ); @@ -296,7 +306,7 @@ public void testMultipleLevels() throws Exception { .endObject() .endObject() ), - XContentType.JSON, + MediaTypeRegistry.JSON, "1" ) ); @@ -311,7 +321,7 @@ public void testMultipleLevels() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("join_field", "unknown").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ); diff --git a/modules/percolator/src/internalClusterTest/java/org/opensearch/percolator/PercolatorQuerySearchIT.java b/modules/percolator/src/internalClusterTest/java/org/opensearch/percolator/PercolatorQuerySearchIT.java index 278a8c1cc0ebc..8c091bd8de439 100644 --- a/modules/percolator/src/internalClusterTest/java/org/opensearch/percolator/PercolatorQuerySearchIT.java +++ b/modules/percolator/src/internalClusterTest/java/org/opensearch/percolator/PercolatorQuerySearchIT.java @@ -41,6 +41,7 @@ import org.opensearch.common.geo.GeoPoint; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.DistanceUnit; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.common.xcontent.XContentType; @@ -125,14 +126,16 @@ public void testPercolatorQuery() throws Exception { BytesReference source = BytesReference.bytes(jsonBuilder().startObject().endObject()); logger.info("percolating empty doc"); - SearchResponse response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get(); + SearchResponse response = client().prepareSearch() + .setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)) + .get(); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getId(), equalTo("1")); source = BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").endObject()); logger.info("percolating doc with 1 field"); response = client().prepareSearch() - .setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)) + .setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)) .addSort("id", SortOrder.ASC) .get(); assertHitCount(response, 2); @@ -144,7 +147,7 @@ public void testPercolatorQuery() throws Exception { source = BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").field("field2", "value").endObject()); logger.info("percolating doc with 2 fields"); response = client().prepareSearch() - .setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)) + .setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)) .addSort("id", SortOrder.ASC) .get(); assertHitCount(response, 3); @@ -164,7 +167,7 @@ public void testPercolatorQuery() throws Exception { BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").endObject()), BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").field("field2", "value").endObject()) ), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .addSort("id", SortOrder.ASC) @@ -267,44 +270,46 @@ public void testPercolatorRangeQueries() throws Exception { // Test long range: BytesReference source = BytesReference.bytes(jsonBuilder().startObject().field("field1", 12).endObject()); - SearchResponse response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get(); + SearchResponse response = client().prepareSearch() + .setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)) + .get(); logger.info("response={}", response); assertHitCount(response, 2); assertThat(response.getHits().getAt(0).getId(), equalTo("3")); assertThat(response.getHits().getAt(1).getId(), equalTo("1")); source = BytesReference.bytes(jsonBuilder().startObject().field("field1", 11).endObject()); - response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get(); + response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)).get(); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getId(), equalTo("1")); // Test double range: source = BytesReference.bytes(jsonBuilder().startObject().field("field2", 12).endObject()); - response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get(); + response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)).get(); assertHitCount(response, 2); assertThat(response.getHits().getAt(0).getId(), equalTo("6")); assertThat(response.getHits().getAt(1).getId(), equalTo("4")); source = BytesReference.bytes(jsonBuilder().startObject().field("field2", 11).endObject()); - response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get(); + response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)).get(); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getId(), equalTo("4")); // Test IP range: source = BytesReference.bytes(jsonBuilder().startObject().field("field3", "192.168.1.5").endObject()); - response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get(); + response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)).get(); assertHitCount(response, 2); assertThat(response.getHits().getAt(0).getId(), equalTo("9")); assertThat(response.getHits().getAt(1).getId(), equalTo("7")); source = BytesReference.bytes(jsonBuilder().startObject().field("field3", "192.168.1.4").endObject()); - response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get(); + response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)).get(); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getId(), equalTo("7")); // Test date range: source = BytesReference.bytes(jsonBuilder().startObject().field("field4", "2016-05-15").endObject()); - response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get(); + response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)).get(); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getId(), equalTo("10")); } @@ -355,7 +360,7 @@ public void testPercolatorGeoQueries() throws Exception { jsonBuilder().startObject().startObject("field1").field("lat", 52.20).field("lon", 4.51).endObject().endObject() ); SearchResponse response = client().prepareSearch() - .setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)) + .setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)) .addSort("id", SortOrder.ASC) .get(); assertHitCount(response, 3); @@ -390,9 +395,9 @@ public void testPercolatorQueryExistingDocument() throws Exception { ) .get(); - client().prepareIndex("test").setId("4").setSource("{\"id\": \"4\"}", XContentType.JSON).get(); - client().prepareIndex("test").setId("5").setSource(XContentType.JSON, "id", "5", "field1", "value").get(); - client().prepareIndex("test").setId("6").setSource(XContentType.JSON, "id", "6", "field1", "value", "field2", "value").get(); + client().prepareIndex("test").setId("4").setSource("{\"id\": \"4\"}", MediaTypeRegistry.JSON).get(); + client().prepareIndex("test").setId("5").setSource(MediaTypeRegistry.JSON, "id", "5", "field1", "value").get(); + client().prepareIndex("test").setId("6").setSource(MediaTypeRegistry.JSON, "id", "6", "field1", "value", "field2", "value").get(); client().admin().indices().prepareRefresh().get(); logger.info("percolating empty doc"); @@ -432,7 +437,7 @@ public void testPercolatorQueryExistingDocumentSourceDisabled() throws Exception client().prepareIndex("test").setId("1").setSource(jsonBuilder().startObject().field("query", matchAllQuery()).endObject()).get(); - client().prepareIndex("test").setId("2").setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId("2").setSource("{}", MediaTypeRegistry.JSON).get(); client().admin().indices().prepareRefresh().get(); logger.info("percolating empty doc with source disabled"); @@ -528,7 +533,7 @@ public void testPercolatorSpecificQueries() throws Exception { .endObject() ); SearchResponse response = client().prepareSearch() - .setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)) + .setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)) .addSort("id", SortOrder.ASC) .get(); assertHitCount(response, 4); @@ -586,7 +591,7 @@ public void testPercolatorQueryWithHighlighting() throws Exception { jsonBuilder().startObject().field("field1", "The quick brown fox jumps over the lazy dog").endObject() ); SearchResponse searchResponse = client().prepareSearch() - .setQuery(new PercolateQueryBuilder("query", document, XContentType.JSON)) + .setQuery(new PercolateQueryBuilder("query", document, MediaTypeRegistry.JSON)) .highlighter(new HighlightBuilder().field("field1")) .addSort("id", SortOrder.ASC) .get(); @@ -619,8 +624,8 @@ public void testPercolatorQueryWithHighlighting() throws Exception { BytesReference document2 = BytesReference.bytes(jsonBuilder().startObject().field("field1", "over the lazy dog").endObject()); searchResponse = client().prepareSearch() .setQuery( - boolQuery().should(new PercolateQueryBuilder("query", document1, XContentType.JSON).setName("query1")) - .should(new PercolateQueryBuilder("query", document2, XContentType.JSON).setName("query2")) + boolQuery().should(new PercolateQueryBuilder("query", document1, MediaTypeRegistry.JSON).setName("query1")) + .should(new PercolateQueryBuilder("query", document2, MediaTypeRegistry.JSON).setName("query2")) ) .highlighter(new HighlightBuilder().field("field1")) .addSort("id", SortOrder.ASC) @@ -659,7 +664,7 @@ public void testPercolatorQueryWithHighlighting() throws Exception { BytesReference.bytes(jsonBuilder().startObject().field("field1", "jumps").endObject()), BytesReference.bytes(jsonBuilder().startObject().field("field1", "brown fox").endObject()) ), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .highlighter(new HighlightBuilder().field("field1")) @@ -712,7 +717,7 @@ public void testPercolatorQueryWithHighlighting() throws Exception { BytesReference.bytes(jsonBuilder().startObject().field("field1", "dog").endObject()), BytesReference.bytes(jsonBuilder().startObject().field("field1", "fox").endObject()) ), - XContentType.JSON + MediaTypeRegistry.JSON ).setName("query1") ) .should( @@ -722,7 +727,7 @@ public void testPercolatorQueryWithHighlighting() throws Exception { BytesReference.bytes(jsonBuilder().startObject().field("field1", "jumps").endObject()), BytesReference.bytes(jsonBuilder().startObject().field("field1", "brown fox").endObject()) ), - XContentType.JSON + MediaTypeRegistry.JSON ).setName("query2") ) ) @@ -811,7 +816,7 @@ public void testTakePositionOffsetGapIntoAccount() throws Exception { client().admin().indices().prepareRefresh().get(); SearchResponse response = client().prepareSearch() - .setQuery(new PercolateQueryBuilder("query", new BytesArray("{\"field\" : [\"brown\", \"fox\"]}"), XContentType.JSON)) + .setQuery(new PercolateQueryBuilder("query", new BytesArray("{\"field\" : [\"brown\", \"fox\"]}"), MediaTypeRegistry.JSON)) .get(); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getId(), equalTo("2")); @@ -899,7 +904,7 @@ public void testWithMultiplePercolatorFields() throws Exception { BytesReference source = BytesReference.bytes(jsonBuilder().startObject().field("field", "value").endObject()); SearchResponse response = client().prepareSearch() - .setQuery(new PercolateQueryBuilder(queryFieldName, source, XContentType.JSON)) + .setQuery(new PercolateQueryBuilder(queryFieldName, source, MediaTypeRegistry.JSON)) .setIndices("test1") .get(); assertHitCount(response, 1); @@ -907,7 +912,7 @@ public void testWithMultiplePercolatorFields() throws Exception { assertThat(response.getHits().getAt(0).getIndex(), equalTo("test1")); response = client().prepareSearch() - .setQuery(new PercolateQueryBuilder("object_field." + queryFieldName, source, XContentType.JSON)) + .setQuery(new PercolateQueryBuilder("object_field." + queryFieldName, source, MediaTypeRegistry.JSON)) .setIndices("test2") .get(); assertHitCount(response, 1); @@ -1012,7 +1017,7 @@ public void testPercolateQueryWithNestedDocuments() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .addSort("id", SortOrder.ASC) @@ -1039,7 +1044,7 @@ public void testPercolateQueryWithNestedDocuments() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .addSort("id", SortOrder.ASC) @@ -1052,7 +1057,7 @@ public void testPercolateQueryWithNestedDocuments() throws Exception { new PercolateQueryBuilder( "query", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("companyname", "notstark").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .addSort("id", SortOrder.ASC) @@ -1105,7 +1110,7 @@ public void testPercolateQueryWithNestedDocuments() throws Exception { .endObject() ) ), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .addSort("id", SortOrder.ASC) @@ -1158,7 +1163,7 @@ public void testPercolatorQueryViaMultiSearch() throws Exception { new PercolateQueryBuilder( "query", BytesReference.bytes(jsonBuilder().startObject().field("field1", "b").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ) @@ -1178,7 +1183,7 @@ public void testPercolatorQueryViaMultiSearch() throws Exception { new PercolateQueryBuilder( "query", BytesReference.bytes(jsonBuilder().startObject().field("field1", "b c").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ) @@ -1188,7 +1193,7 @@ public void testPercolatorQueryViaMultiSearch() throws Exception { new PercolateQueryBuilder( "query", BytesReference.bytes(jsonBuilder().startObject().field("field1", "d").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ) @@ -1248,7 +1253,7 @@ public void testDisallowExpensiveQueries() throws IOException { // Execute with search.allow_expensive_queries = null => default value = false => success BytesReference source = BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").endObject()); SearchResponse response = client().prepareSearch() - .setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)) + .setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)) .get(); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getId(), equalTo("1")); @@ -1261,7 +1266,7 @@ public void testDisallowExpensiveQueries() throws IOException { OpenSearchException e = expectThrows( OpenSearchException.class, - () -> client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get() + () -> client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)).get() ); assertEquals( "[percolate] queries cannot be executed when 'search.allow_expensive_queries' is set to false.", @@ -1273,7 +1278,7 @@ public void testDisallowExpensiveQueries() throws IOException { updateSettingsRequest.persistentSettings(Settings.builder().put("search.allow_expensive_queries", true)); assertAcked(client().admin().cluster().updateSettings(updateSettingsRequest).actionGet()); - response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, XContentType.JSON)).get(); + response = client().prepareSearch().setQuery(new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON)).get(); assertHitCount(response, 1); assertThat(response.getHits().getAt(0).getId(), equalTo("1")); assertThat(response.getHits().getAt(0).getFields().get("_percolator_document_slot").getValue(), equalTo(0)); @@ -1307,7 +1312,7 @@ public void testWrappedWithConstantScore() throws Exception { new PercolateQueryBuilder( "q", BytesReference.bytes(jsonBuilder().startObject().field("d", "2020-02-01T15:00:00.000+11:00").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .get(); @@ -1318,7 +1323,7 @@ public void testWrappedWithConstantScore() throws Exception { new PercolateQueryBuilder( "q", BytesReference.bytes(jsonBuilder().startObject().field("d", "2020-02-01T15:00:00.000+11:00").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .addSort("_doc", SortOrder.ASC) @@ -1331,7 +1336,7 @@ public void testWrappedWithConstantScore() throws Exception { new PercolateQueryBuilder( "q", BytesReference.bytes(jsonBuilder().startObject().field("d", "2020-02-01T15:00:00.000+11:00").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ) diff --git a/modules/percolator/src/main/java/org/opensearch/percolator/PercolateQueryBuilder.java b/modules/percolator/src/main/java/org/opensearch/percolator/PercolateQueryBuilder.java index 9f49843c37ea5..3882cbbfd4b35 100644 --- a/modules/percolator/src/main/java/org/opensearch/percolator/PercolateQueryBuilder.java +++ b/modules/percolator/src/main/java/org/opensearch/percolator/PercolateQueryBuilder.java @@ -139,10 +139,10 @@ public class PercolateQueryBuilder extends AbstractQueryBuilder pqb.toQuery(createShardContext())); assertThat(e.getMessage(), equalTo("query builder must be rewritten first")); QueryBuilder rewrite = rewriteAndFetch(pqb, createShardContext()); - PercolateQueryBuilder geoShapeQueryBuilder = new PercolateQueryBuilder(pqb.getField(), documentSource, XContentType.JSON); + PercolateQueryBuilder geoShapeQueryBuilder = new PercolateQueryBuilder(pqb.getField(), documentSource, MediaTypeRegistry.JSON); assertEquals(geoShapeQueryBuilder, rewrite); } @@ -243,13 +243,13 @@ protected Set getObjectsHoldingArbitraryContent() { public void testRequiredParameters() { IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> { - new PercolateQueryBuilder(null, new BytesArray("{}"), XContentType.JSON); + new PercolateQueryBuilder(null, new BytesArray("{}"), MediaTypeRegistry.JSON); }); assertThat(e.getMessage(), equalTo("[field] is a required argument")); e = expectThrows( IllegalArgumentException.class, - () -> new PercolateQueryBuilder("_field", (List) null, XContentType.JSON) + () -> new PercolateQueryBuilder("_field", (List) null, MediaTypeRegistry.JSON) ); assertThat(e.getMessage(), equalTo("[document] is a required argument")); diff --git a/modules/percolator/src/test/java/org/opensearch/percolator/PercolateWithNestedQueryBuilderTests.java b/modules/percolator/src/test/java/org/opensearch/percolator/PercolateWithNestedQueryBuilderTests.java index 677d169162c74..f8f9ab1fe8aa5 100644 --- a/modules/percolator/src/test/java/org/opensearch/percolator/PercolateWithNestedQueryBuilderTests.java +++ b/modules/percolator/src/test/java/org/opensearch/percolator/PercolateWithNestedQueryBuilderTests.java @@ -35,7 +35,7 @@ import org.opensearch.action.admin.indices.mapping.put.PutMappingRequest; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.compress.CompressedXContent; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.mapper.MapperService; import org.opensearch.index.query.QueryBuilder; import org.opensearch.index.query.QueryShardContext; @@ -57,7 +57,11 @@ protected void initializeAdditionalMappings(MapperService mapperService) throws public void testDetectsNestedDocuments() throws IOException { QueryShardContext shardContext = createShardContext(); - PercolateQueryBuilder builder = new PercolateQueryBuilder(queryField, new BytesArray("{ \"foo\": \"bar\" }"), XContentType.JSON); + PercolateQueryBuilder builder = new PercolateQueryBuilder( + queryField, + new BytesArray("{ \"foo\": \"bar\" }"), + MediaTypeRegistry.JSON + ); QueryBuilder rewrittenBuilder = rewriteAndFetch(builder, shardContext); PercolateQuery query = (PercolateQuery) rewrittenBuilder.toQuery(shardContext); assertFalse(query.excludesNestedDocs()); @@ -65,7 +69,7 @@ public void testDetectsNestedDocuments() throws IOException { builder = new PercolateQueryBuilder( queryField, new BytesArray("{ \"foo\": \"bar\", \"some_nested_object\": [ { \"baz\": 42 } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ); rewrittenBuilder = rewriteAndFetch(builder, shardContext); query = (PercolateQuery) rewrittenBuilder.toQuery(shardContext); diff --git a/modules/percolator/src/test/java/org/opensearch/percolator/PercolatorFieldMapperTests.java b/modules/percolator/src/test/java/org/opensearch/percolator/PercolatorFieldMapperTests.java index c5e2a1f68de9c..b91d284770d52 100644 --- a/modules/percolator/src/test/java/org/opensearch/percolator/PercolatorFieldMapperTests.java +++ b/modules/percolator/src/test/java/org/opensearch/percolator/PercolatorFieldMapperTests.java @@ -67,9 +67,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.common.network.InetAddresses; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.IndexService; import org.opensearch.index.IndexSettings; import org.opensearch.index.mapper.DocumentMapper; @@ -557,7 +557,7 @@ public void testPercolatorFieldMapper() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field(fieldName, queryBuilder).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -577,7 +577,7 @@ public void testPercolatorFieldMapper() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field(fieldName, queryBuilder).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertThat(doc.rootDoc().getFields(fieldType.extractionResultField.name()).length, equalTo(1)); @@ -594,7 +594,7 @@ public void testPercolatorFieldMapper() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field(fieldName, queryBuilder).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertThat(doc.rootDoc().getFields(fieldType.extractionResultField.name()).length, equalTo(1)); @@ -622,7 +622,7 @@ public void testStoringQueries() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field(fieldName, query).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); BytesRef qbSource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue(); @@ -640,7 +640,7 @@ public void testQueryWithRewrite() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field(fieldName, queryBuilder).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); BytesRef qbSource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue(); @@ -666,7 +666,7 @@ public void testPercolatorFieldMapperUnMappedField() throws Exception { BytesReference.bytes( XContentFactory.jsonBuilder().startObject().field(fieldName, termQuery("unmapped_field", "value")).endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); }); @@ -682,7 +682,7 @@ public void testPercolatorFieldMapper_noQuery() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertThat(doc.rootDoc().getFields(fieldType.queryBuilderField.name()).length, equalTo(0)); @@ -694,7 +694,7 @@ public void testPercolatorFieldMapper_noQuery() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().nullField(fieldName).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); } catch (MapperParsingException e) { @@ -756,7 +756,7 @@ public void testMultiplePercolatorFields() throws Exception { BytesReference.bytes( jsonBuilder().startObject().field("query_field1", queryBuilder).field("query_field2", queryBuilder).endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertThat(doc.rootDoc().getFields().size(), equalTo(16)); // also includes all other meta fields @@ -797,7 +797,7 @@ public void testNestedPercolatorField() throws Exception { BytesReference.bytes( jsonBuilder().startObject().startObject("object_field").field("query_field", queryBuilder).endObject().endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertThat(doc.rootDoc().getFields().size(), equalTo(12)); // also includes all other meta fields @@ -822,7 +822,7 @@ public void testNestedPercolatorField() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertThat(doc.rootDoc().getFields().size(), equalTo(12)); // also includes all other meta fields @@ -847,7 +847,7 @@ public void testNestedPercolatorField() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); }); @@ -947,7 +947,7 @@ public void testImplicitlySetDefaultScriptLang() throws Exception { .rawField(fieldName, new BytesArray(query.toString()).streamInput(), query.contentType()) .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); BytesRef querySource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue(); @@ -994,7 +994,7 @@ public void testImplicitlySetDefaultScriptLang() throws Exception { .rawField(fieldName, new BytesArray(query.toString()).streamInput(), query.contentType()) .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); querySource = doc.rootDoc().getFields(fieldType.queryBuilderField.name())[0].binaryValue(); @@ -1083,7 +1083,7 @@ public void testDuplicatedClauses() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field(fieldName, qb).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -1108,7 +1108,7 @@ public void testDuplicatedClauses() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field(fieldName, qb).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -1136,7 +1136,7 @@ public void testDuplicatedClauses() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field(fieldName, qb).endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); diff --git a/modules/percolator/src/test/java/org/opensearch/percolator/PercolatorQuerySearchTests.java b/modules/percolator/src/test/java/org/opensearch/percolator/PercolatorQuerySearchTests.java index 7f0437a8a29aa..85cf6d86e29c7 100644 --- a/modules/percolator/src/test/java/org/opensearch/percolator/PercolatorQuerySearchTests.java +++ b/modules/percolator/src/test/java/org/opensearch/percolator/PercolatorQuerySearchTests.java @@ -37,9 +37,9 @@ import org.opensearch.action.support.WriteRequest; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.IndexService; import org.opensearch.index.cache.bitset.BitsetFilterCache; import org.opensearch.index.engine.Engine; @@ -115,7 +115,7 @@ public void testPercolateScriptQuery() throws IOException { new PercolateQueryBuilder( "query", BytesReference.bytes(jsonBuilder().startObject().field("field1", "b").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .get(); @@ -188,7 +188,7 @@ public void testPercolateQueryWithNestedDocuments_doNotLeakBitsetCacheEntries() .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .addSort("_doc", SortOrder.ASC) @@ -269,7 +269,7 @@ public void testPercolateQueryWithNestedDocuments_doLeakFieldDataCacheEntries() doc.endObject(); for (int i = 0; i < 32; i++) { SearchResponse response = client().prepareSearch() - .setQuery(new PercolateQueryBuilder("query", BytesReference.bytes(doc), XContentType.JSON)) + .setQuery(new PercolateQueryBuilder("query", BytesReference.bytes(doc), MediaTypeRegistry.JSON)) .addSort("_doc", SortOrder.ASC) .get(); assertHitCount(response, 1); @@ -293,7 +293,7 @@ public void testMapUnmappedFieldAsText() throws IOException { new PercolateQueryBuilder( "query", BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ) .get(); @@ -348,13 +348,13 @@ public void testRangeQueriesWithNow() throws Exception { BytesReference source = BytesReference.bytes( jsonBuilder().startObject().field("field1", "value").field("field2", currentTime[0]).endObject() ); - QueryBuilder queryBuilder = new PercolateQueryBuilder("query", source, XContentType.JSON); + QueryBuilder queryBuilder = new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON); Query query = queryBuilder.toQuery(queryShardContext); assertThat(searcher.count(query), equalTo(3)); currentTime[0] = currentTime[0] + 10800000; // + 3 hours source = BytesReference.bytes(jsonBuilder().startObject().field("field1", "value").field("field2", currentTime[0]).endObject()); - queryBuilder = new PercolateQueryBuilder("query", source, XContentType.JSON); + queryBuilder = new PercolateQueryBuilder("query", source, MediaTypeRegistry.JSON); query = queryBuilder.toQuery(queryShardContext); assertThat(searcher.count(query), equalTo(3)); } diff --git a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RankEvalResponse.java b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RankEvalResponse.java index 68c61183a4486..496320dabe650 100644 --- a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RankEvalResponse.java +++ b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RankEvalResponse.java @@ -40,11 +40,11 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.xcontent.XContentParserUtils; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.Collections; @@ -106,7 +106,7 @@ public Map getFailures() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RankEvalSpec.java b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RankEvalSpec.java index 44eeceb117794..229782b5fb5d1 100644 --- a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RankEvalSpec.java +++ b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RankEvalSpec.java @@ -39,11 +39,11 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.xcontent.XContentParserUtils; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.script.Script; import java.io.IOException; @@ -250,7 +250,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RatedDocument.java b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RatedDocument.java index e91b8671d0804..bb11a594baf77 100644 --- a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RatedDocument.java +++ b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RatedDocument.java @@ -36,9 +36,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -129,7 +129,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RatedRequest.java b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RatedRequest.java index 78c2dbd33182f..83b7d9bb82d8e 100644 --- a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RatedRequest.java +++ b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/RatedRequest.java @@ -37,9 +37,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -341,7 +341,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/TransportRankEvalAction.java b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/TransportRankEvalAction.java index 688a0787c95b8..cc34be0485150 100644 --- a/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/TransportRankEvalAction.java +++ b/modules/rank-eval/src/main/java/org/opensearch/index/rankeval/TransportRankEvalAction.java @@ -44,9 +44,9 @@ import org.opensearch.common.inject.Inject; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.script.Script; import org.opensearch.script.ScriptService; import org.opensearch.script.TemplateScript; @@ -126,7 +126,7 @@ protected void doExecute(Task task, RankEvalRequest request, ActionListener buildRequest(Hit doc } }; ScrollableHitSource.BasicHit hit = new ScrollableHitSource.BasicHit("index", "id", 0); - hit.setSource(new BytesArray("{}"), XContentType.JSON); + hit.setSource(new BytesArray("{}"), MediaTypeRegistry.JSON); ScrollableHitSource.Response response = new ScrollableHitSource.Response(false, emptyList(), 1, singletonList(hit), null); simulateScrollResponse(action, System.nanoTime(), 0, response); ExecutionException e = expectThrows(ExecutionException.class, () -> listener.get()); diff --git a/modules/reindex/src/test/java/org/opensearch/index/reindex/CancelTests.java b/modules/reindex/src/test/java/org/opensearch/index/reindex/CancelTests.java index 26fcfd226371f..6dd168c07a8ea 100644 --- a/modules/reindex/src/test/java/org/opensearch/index/reindex/CancelTests.java +++ b/modules/reindex/src/test/java/org/opensearch/index/reindex/CancelTests.java @@ -41,7 +41,7 @@ import org.opensearch.action.ingest.DeletePipelineRequest; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexModule; import org.opensearch.index.engine.Engine; import org.opensearch.index.engine.Engine.Operation.Origin; @@ -263,7 +263,7 @@ public void testUpdateByQueryCancel() throws Exception { + " } ]\n" + "}" ); - assertAcked(client().admin().cluster().preparePutPipeline("set-processed", pipeline, XContentType.JSON).get()); + assertAcked(client().admin().cluster().preparePutPipeline("set-processed", pipeline, MediaTypeRegistry.JSON).get()); testCancel(UpdateByQueryAction.NAME, updateByQuery().setPipeline("set-processed").source(INDEX), (response, total, modified) -> { assertThat(response, matcher().updated(modified).reasonCancelled(equalTo("by user request"))); @@ -307,7 +307,7 @@ public void testUpdateByQueryCancelWithWorkers() throws Exception { + " } ]\n" + "}" ); - assertAcked(client().admin().cluster().preparePutPipeline("set-processed", pipeline, XContentType.JSON).get()); + assertAcked(client().admin().cluster().preparePutPipeline("set-processed", pipeline, MediaTypeRegistry.JSON).get()); testCancel( UpdateByQueryAction.NAME, diff --git a/modules/reindex/src/test/java/org/opensearch/index/reindex/RestReindexActionTests.java b/modules/reindex/src/test/java/org/opensearch/index/reindex/RestReindexActionTests.java index 651ccd47df7bd..1269cbe6b5438 100644 --- a/modules/reindex/src/test/java/org/opensearch/index/reindex/RestReindexActionTests.java +++ b/modules/reindex/src/test/java/org/opensearch/index/reindex/RestReindexActionTests.java @@ -35,8 +35,8 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.NamedWriteableRegistry; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.test.rest.FakeRestRequest; import org.opensearch.test.rest.RestActionTestCase; @@ -88,14 +88,14 @@ public void testPipelineQueryParameterIsError() throws IOException { public void testSetScrollTimeout() throws IOException { { FakeRestRequest.Builder requestBuilder = new FakeRestRequest.Builder(xContentRegistry()); - requestBuilder.withContent(new BytesArray("{}"), XContentType.JSON); + requestBuilder.withContent(new BytesArray("{}"), MediaTypeRegistry.JSON); ReindexRequest request = action.buildRequest(requestBuilder.build(), new NamedWriteableRegistry(Collections.emptyList())); assertEquals(AbstractBulkByScrollRequest.DEFAULT_SCROLL_TIMEOUT, request.getScrollTime()); } { FakeRestRequest.Builder requestBuilder = new FakeRestRequest.Builder(xContentRegistry()); requestBuilder.withParams(singletonMap("scroll", "10m")); - requestBuilder.withContent(new BytesArray("{}"), XContentType.JSON); + requestBuilder.withContent(new BytesArray("{}"), MediaTypeRegistry.JSON); ReindexRequest request = action.buildRequest(requestBuilder.build(), new NamedWriteableRegistry(Collections.emptyList())); assertEquals("10m", request.getScrollTime().toString()); } diff --git a/modules/search-pipeline-common/src/internalClusterTest/java/org/opensearch/search/pipeline/common/SearchPipelineCommonIT.java b/modules/search-pipeline-common/src/internalClusterTest/java/org/opensearch/search/pipeline/common/SearchPipelineCommonIT.java index faa0859e8e33f..c7b891080b321 100644 --- a/modules/search-pipeline-common/src/internalClusterTest/java/org/opensearch/search/pipeline/common/SearchPipelineCommonIT.java +++ b/modules/search-pipeline-common/src/internalClusterTest/java/org/opensearch/search/pipeline/common/SearchPipelineCommonIT.java @@ -19,7 +19,7 @@ import org.opensearch.action.search.SearchResponse; import org.opensearch.action.support.master.AcknowledgedResponse; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.MatchAllQueryBuilder; import org.opensearch.plugins.Plugin; import org.opensearch.core.rest.RestStatus; @@ -58,7 +58,7 @@ public void testFilterQuery() { + "]" + "}" ), - XContentType.JSON + MediaTypeRegistry.JSON ); AcknowledgedResponse ackRsp = client().admin().cluster().putSearchPipeline(putSearchPipelineRequest).actionGet(); assertTrue(ackRsp.isAcknowledged()); diff --git a/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/FilterQueryRequestProcessor.java b/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/FilterQueryRequestProcessor.java index eab8bc95bd668..6ec3da02854cb 100644 --- a/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/FilterQueryRequestProcessor.java +++ b/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/FilterQueryRequestProcessor.java @@ -11,8 +11,8 @@ import org.opensearch.action.search.SearchRequest; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.xcontent.LoggingDeprecationHandler; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -114,7 +114,7 @@ public FilterQueryRequestProcessor create( try ( XContentBuilder builder = XContentBuilder.builder(JsonXContent.jsonXContent).map(query); InputStream stream = BytesReference.bytes(builder).streamInput(); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(namedXContentRegistry, LoggingDeprecationHandler.INSTANCE, stream) ) { return new FilterQueryRequestProcessor(tag, description, ignoreFailure, parseInnerQueryBuilder(parser)); diff --git a/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/ScriptRequestProcessor.java b/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/ScriptRequestProcessor.java index 3849d2f905490..e39f0b15aa538 100644 --- a/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/ScriptRequestProcessor.java +++ b/modules/search-pipeline-common/src/main/java/org/opensearch/search/pipeline/common/ScriptRequestProcessor.java @@ -13,10 +13,10 @@ import org.opensearch.common.Nullable; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.script.Script; @@ -163,7 +163,7 @@ public ScriptRequestProcessor create( try ( XContentBuilder builder = XContentBuilder.builder(JsonXContent.jsonXContent).map(scriptConfig); InputStream stream = BytesReference.bytes(builder).streamInput(); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, stream) ) { Script script = Script.parse(parser); diff --git a/plugins/analysis-icu/src/internalClusterTest/java/org/opensearch/index/mapper/ICUCollationKeywordFieldMapperIT.java b/plugins/analysis-icu/src/internalClusterTest/java/org/opensearch/index/mapper/ICUCollationKeywordFieldMapperIT.java index 4f596034bfece..ea3c7d2e47504 100644 --- a/plugins/analysis-icu/src/internalClusterTest/java/org/opensearch/index/mapper/ICUCollationKeywordFieldMapperIT.java +++ b/plugins/analysis-icu/src/internalClusterTest/java/org/opensearch/index/mapper/ICUCollationKeywordFieldMapperIT.java @@ -42,8 +42,8 @@ import com.ibm.icu.util.ULocale; import org.opensearch.action.search.SearchRequest; import org.opensearch.action.search.SearchResponse; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.query.QueryBuilders; import org.opensearch.plugin.analysis.icu.AnalysisICUPlugin; import org.opensearch.plugins.Plugin; @@ -91,8 +91,12 @@ public void testBasicUsage() throws Exception { // both values should collate to same value indexRandom( true, - client().prepareIndex(index).setId("1").setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", XContentType.JSON) + client().prepareIndex(index) + .setId("1") + .setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index) + .setId("2") + .setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", MediaTypeRegistry.JSON) ); // searching for either of the terms should return both results since they collate to the same value @@ -134,8 +138,10 @@ public void testMultipleValues() throws Exception { true, client().prepareIndex(index) .setId("1") - .setSource("{\"id\":\"1\", \"collate\":[\"" + equivalent[0] + "\", \"" + equivalent[1] + "\"]}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[2] + "\"}", XContentType.JSON) + .setSource("{\"id\":\"1\", \"collate\":[\"" + equivalent[0] + "\", \"" + equivalent[1] + "\"]}", MediaTypeRegistry.JSON), + client().prepareIndex(index) + .setId("2") + .setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[2] + "\"}", MediaTypeRegistry.JSON) ); // using sort mode = max, values B and C will be used for the sort @@ -195,8 +201,12 @@ public void testNormalization() throws Exception { indexRandom( true, - client().prepareIndex(index).setId("1").setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", XContentType.JSON) + client().prepareIndex(index) + .setId("1") + .setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index) + .setId("2") + .setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", MediaTypeRegistry.JSON) ); // searching for either of the terms should return both results since they collate to the same value @@ -240,8 +250,12 @@ public void testSecondaryStrength() throws Exception { indexRandom( true, - client().prepareIndex(index).setId("1").setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", XContentType.JSON) + client().prepareIndex(index) + .setId("1") + .setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index) + .setId("2") + .setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", MediaTypeRegistry.JSON) ); SearchRequest request = new SearchRequest().indices(index) @@ -285,8 +299,12 @@ public void testIgnorePunctuation() throws Exception { indexRandom( true, - client().prepareIndex(index).setId("1").setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", XContentType.JSON) + client().prepareIndex(index) + .setId("1") + .setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index) + .setId("2") + .setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", MediaTypeRegistry.JSON) ); SearchRequest request = new SearchRequest().indices(index) @@ -330,9 +348,9 @@ public void testIgnoreWhitespace() throws Exception { indexRandom( true, - client().prepareIndex(index).setId("1").setSource("{\"id\":\"1\",\"collate\":\"foo bar\"}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"foobar\"}", XContentType.JSON), - client().prepareIndex(index).setId("3").setSource("{\"id\":\"3\",\"collate\":\"foo-bar\"}", XContentType.JSON) + client().prepareIndex(index).setId("1").setSource("{\"id\":\"1\",\"collate\":\"foo bar\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"foobar\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index).setId("3").setSource("{\"id\":\"3\",\"collate\":\"foo-bar\"}", MediaTypeRegistry.JSON) ); SearchRequest request = new SearchRequest().indices(index) @@ -372,8 +390,8 @@ public void testNumerics() throws Exception { indexRandom( true, - client().prepareIndex(index).setId("1").setSource("{\"collate\":\"foobar-10\"}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"collate\":\"foobar-9\"}", XContentType.JSON) + client().prepareIndex(index).setId("1").setSource("{\"collate\":\"foobar-10\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index).setId("2").setSource("{\"collate\":\"foobar-9\"}", MediaTypeRegistry.JSON) ); SearchRequest request = new SearchRequest().indices(index) @@ -411,10 +429,10 @@ public void testIgnoreAccentsButNotCase() throws Exception { indexRandom( true, - client().prepareIndex(index).setId("1").setSource("{\"id\":\"1\",\"collate\":\"résumé\"}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"Resume\"}", XContentType.JSON), - client().prepareIndex(index).setId("3").setSource("{\"id\":\"3\",\"collate\":\"resume\"}", XContentType.JSON), - client().prepareIndex(index).setId("4").setSource("{\"id\":\"4\",\"collate\":\"Résumé\"}", XContentType.JSON) + client().prepareIndex(index).setId("1").setSource("{\"id\":\"1\",\"collate\":\"résumé\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"Resume\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index).setId("3").setSource("{\"id\":\"3\",\"collate\":\"resume\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index).setId("4").setSource("{\"id\":\"4\",\"collate\":\"Résumé\"}", MediaTypeRegistry.JSON) ); SearchRequest request = new SearchRequest().indices(index) @@ -449,8 +467,8 @@ public void testUpperCaseFirst() throws Exception { indexRandom( true, - client().prepareIndex(index).setId("1").setSource("{\"collate\":\"resume\"}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"collate\":\"Resume\"}", XContentType.JSON) + client().prepareIndex(index).setId("1").setSource("{\"collate\":\"resume\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index).setId("2").setSource("{\"collate\":\"Resume\"}", MediaTypeRegistry.JSON) ); SearchRequest request = new SearchRequest().indices(index) @@ -497,8 +515,12 @@ public void testCustomRules() throws Exception { indexRandom( true, - client().prepareIndex(index).setId("1").setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", XContentType.JSON), - client().prepareIndex(index).setId("2").setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", XContentType.JSON) + client().prepareIndex(index) + .setId("1") + .setSource("{\"id\":\"1\",\"collate\":\"" + equivalent[0] + "\"}", MediaTypeRegistry.JSON), + client().prepareIndex(index) + .setId("2") + .setSource("{\"id\":\"2\",\"collate\":\"" + equivalent[1] + "\"}", MediaTypeRegistry.JSON) ); SearchRequest request = new SearchRequest().indices(index) diff --git a/plugins/events-correlation-engine/src/main/java/org/opensearch/plugin/correlation/utils/IndexUtils.java b/plugins/events-correlation-engine/src/main/java/org/opensearch/plugin/correlation/utils/IndexUtils.java index a240fa17d1d22..d40e986e4b0d1 100644 --- a/plugins/events-correlation-engine/src/main/java/org/opensearch/plugin/correlation/utils/IndexUtils.java +++ b/plugins/events-correlation-engine/src/main/java/org/opensearch/plugin/correlation/utils/IndexUtils.java @@ -15,7 +15,7 @@ import org.opensearch.cluster.ClusterState; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.xcontent.LoggingDeprecationHandler; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; @@ -80,7 +80,7 @@ public static Boolean shouldUpdateIndex(IndexMetadata index, String mapping) thr * @throws IOException IOException */ public static Integer getSchemaVersion(String mapping) throws IOException { - XContentParser xcp = XContentType.JSON.xContent() + XContentParser xcp = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, mapping); while (!xcp.isClosed()) { @@ -129,7 +129,7 @@ public static void updateIndexMapping( ) throws IOException { if (clusterState.metadata().indices().containsKey(index)) { if (shouldUpdateIndex(clusterState.metadata().index(index), mapping)) { - PutMappingRequest putMappingRequest = new PutMappingRequest(index).source(mapping, XContentType.JSON); + PutMappingRequest putMappingRequest = new PutMappingRequest(index).source(mapping, MediaTypeRegistry.JSON); client.putMapping(putMappingRequest, actionListener); } else { actionListener.onResponse(new AcknowledgedResponse(true)); diff --git a/plugins/events-correlation-engine/src/test/java/org/opensearch/plugin/correlation/core/index/query/CorrelationQueryBuilderTests.java b/plugins/events-correlation-engine/src/test/java/org/opensearch/plugin/correlation/core/index/query/CorrelationQueryBuilderTests.java index 3489dfdcc4530..cc229acaad4d3 100644 --- a/plugins/events-correlation-engine/src/test/java/org/opensearch/plugin/correlation/core/index/query/CorrelationQueryBuilderTests.java +++ b/plugins/events-correlation-engine/src/test/java/org/opensearch/plugin/correlation/core/index/query/CorrelationQueryBuilderTests.java @@ -14,12 +14,12 @@ import org.opensearch.cluster.ClusterModule; import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.NamedWriteableAwareStreamInput; import org.opensearch.core.common.io.stream.NamedWriteableRegistry; import org.opensearch.core.common.io.stream.StreamInput; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -114,7 +114,7 @@ public void testFromXContentFromString() throws IOException { XContentParser contentParser = createParser(JsonXContent.jsonXContent, correlationQuery); contentParser.nextToken(); CorrelationQueryBuilder actualBuilder = CorrelationQueryBuilder.parse(contentParser); - Assert.assertEquals(correlationQuery.replace("\n", "").replace(" ", ""), Strings.toString(XContentType.JSON, actualBuilder)); + Assert.assertEquals(correlationQuery.replace("\n", "").replace(" ", ""), Strings.toString(MediaTypeRegistry.JSON, actualBuilder)); } /** diff --git a/plugins/mapper-size/src/internalClusterTest/java/org/opensearch/index/mapper/size/SizeMappingIT.java b/plugins/mapper-size/src/internalClusterTest/java/org/opensearch/index/mapper/size/SizeMappingIT.java index 2c307ef4cc015..51e0979324623 100644 --- a/plugins/mapper-size/src/internalClusterTest/java/org/opensearch/index/mapper/size/SizeMappingIT.java +++ b/plugins/mapper-size/src/internalClusterTest/java/org/opensearch/index/mapper/size/SizeMappingIT.java @@ -34,8 +34,8 @@ import org.opensearch.action.admin.indices.mapping.get.GetMappingsResponse; import org.opensearch.action.get.GetResponse; import org.opensearch.action.support.master.AcknowledgedResponse; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.plugin.mapper.MapperSizePlugin; import org.opensearch.plugins.Plugin; import org.opensearch.test.OpenSearchIntegTestCase; @@ -123,7 +123,7 @@ private void assertSizeMappingEnabled(String index, boolean enabled) throws IOEx public void testBasic() throws Exception { assertAcked(prepareCreate("test").setMapping("_size", "enabled=true")); final String source = "{\"f\":10}"; - indexRandom(true, client().prepareIndex("test").setId("1").setSource(source, XContentType.JSON)); + indexRandom(true, client().prepareIndex("test").setId("1").setSource(source, MediaTypeRegistry.JSON)); GetResponse getResponse = client().prepareGet("test", "1").setStoredFields("_size").get(); assertNotNull(getResponse.getField("_size")); assertEquals(source.length(), (int) getResponse.getField("_size").getValue()); diff --git a/plugins/mapper-size/src/internalClusterTest/java/org/opensearch/index/mapper/size/SizeMappingTests.java b/plugins/mapper-size/src/internalClusterTest/java/org/opensearch/index/mapper/size/SizeMappingTests.java index 87b1624cbcd64..72df59e2097d5 100644 --- a/plugins/mapper-size/src/internalClusterTest/java/org/opensearch/index/mapper/size/SizeMappingTests.java +++ b/plugins/mapper-size/src/internalClusterTest/java/org/opensearch/index/mapper/size/SizeMappingTests.java @@ -38,7 +38,7 @@ import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.MapperService; import org.opensearch.index.mapper.DocumentMapper; @@ -65,7 +65,7 @@ public void testSizeEnabled() throws Exception { DocumentMapper docMapper = service.mapperService().documentMapper(); BytesReference source = BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "value").endObject()); - ParsedDocument doc = docMapper.parse(new SourceToParse("test", "1", source, XContentType.JSON)); + ParsedDocument doc = docMapper.parse(new SourceToParse("test", "1", source, MediaTypeRegistry.JSON)); boolean stored = false; boolean points = false; @@ -82,7 +82,7 @@ public void testSizeDisabled() throws Exception { DocumentMapper docMapper = service.mapperService().documentMapper(); BytesReference source = BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "value").endObject()); - ParsedDocument doc = docMapper.parse(new SourceToParse("test", "1", source, XContentType.JSON)); + ParsedDocument doc = docMapper.parse(new SourceToParse("test", "1", source, MediaTypeRegistry.JSON)); assertThat(doc.rootDoc().getField("_size"), nullValue()); } @@ -92,7 +92,7 @@ public void testSizeNotSet() throws Exception { DocumentMapper docMapper = service.mapperService().documentMapper(); BytesReference source = BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "value").endObject()); - ParsedDocument doc = docMapper.parse(new SourceToParse("test", "1", source, XContentType.JSON)); + ParsedDocument doc = docMapper.parse(new SourceToParse("test", "1", source, MediaTypeRegistry.JSON)); assertThat(doc.rootDoc().getField("_size"), nullValue()); } diff --git a/plugins/repository-gcs/src/test/java/org/opensearch/repositories/gcs/TestUtils.java b/plugins/repository-gcs/src/test/java/org/opensearch/repositories/gcs/TestUtils.java index bc5a542972e83..648955c079b3e 100644 --- a/plugins/repository-gcs/src/test/java/org/opensearch/repositories/gcs/TestUtils.java +++ b/plugins/repository-gcs/src/test/java/org/opensearch/repositories/gcs/TestUtils.java @@ -31,8 +31,8 @@ package org.opensearch.repositories.gcs; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import java.io.ByteArrayOutputStream; import java.security.KeyPairGenerator; @@ -54,7 +54,7 @@ static byte[] createServiceAccount(final Random random) { final String privateKey = Base64.getEncoder().encodeToString(keyPairGenerator.generateKeyPair().getPrivate().getEncoded()); final ByteArrayOutputStream out = new ByteArrayOutputStream(); - try (XContentBuilder builder = new XContentBuilder(XContentType.JSON.xContent(), out)) { + try (XContentBuilder builder = new XContentBuilder(MediaTypeRegistry.JSON.xContent(), out)) { builder.startObject(); { builder.field("type", "service_account"); diff --git a/qa/full-cluster-restart/src/test/java/org/opensearch/upgrades/FullClusterRestartIT.java b/qa/full-cluster-restart/src/test/java/org/opensearch/upgrades/FullClusterRestartIT.java index 95bc7f8dc404e..cbd13357fedd9 100644 --- a/qa/full-cluster-restart/src/test/java/org/opensearch/upgrades/FullClusterRestartIT.java +++ b/qa/full-cluster-restart/src/test/java/org/opensearch/upgrades/FullClusterRestartIT.java @@ -46,6 +46,7 @@ import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.common.xcontent.support.XContentMapValues; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.index.IndexSettings; import org.opensearch.test.NotEqualMessageBuilder; @@ -1365,7 +1366,7 @@ public void testResize() throws Exception { if (randomBoolean()) { settings.put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true); } - shrinkRequest.setJsonEntity("{\"settings\":" + Strings.toString(XContentType.JSON, settings.build()) + "}"); + shrinkRequest.setJsonEntity("{\"settings\":" + Strings.toString(MediaTypeRegistry.JSON, settings.build()) + "}"); client().performRequest(shrinkRequest); ensureGreenLongWait(target); assertNumHits(target, numDocs + moreDocs, 1); @@ -1377,7 +1378,7 @@ public void testResize() throws Exception { settings.put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), true); } Request splitRequest = new Request("PUT", "/" + index + "/_split/" + target); - splitRequest.setJsonEntity("{\"settings\":" + Strings.toString(XContentType.JSON, settings.build()) + "}"); + splitRequest.setJsonEntity("{\"settings\":" + Strings.toString(MediaTypeRegistry.JSON, settings.build()) + "}"); client().performRequest(splitRequest); ensureGreenLongWait(target); assertNumHits(target, numDocs + moreDocs, 6); diff --git a/qa/multi-cluster-search/src/test/java/org/opensearch/search/CCSDuelIT.java b/qa/multi-cluster-search/src/test/java/org/opensearch/search/CCSDuelIT.java index 1f2409741a878..218254a8cdba4 100644 --- a/qa/multi-cluster-search/src/test/java/org/opensearch/search/CCSDuelIT.java +++ b/qa/multi-cluster-search/src/test/java/org/opensearch/search/CCSDuelIT.java @@ -54,11 +54,11 @@ import org.opensearch.client.indices.CreateIndexRequest; import org.opensearch.client.indices.CreateIndexResponse; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; +import org.opensearch.core.xcontent.XContentHelper; import org.opensearch.index.query.InnerHitBuilder; import org.opensearch.index.query.MatchQueryBuilder; import org.opensearch.index.query.QueryBuilders; @@ -198,7 +198,7 @@ private static void indexDocuments(String idPrefix) throws IOException, Interrup createIndexRequest.mapping("{\"properties\":{" + "\"id\":{\"type\":\"keyword\"}," + "\"suggest\":{\"type\":\"completion\"}," + - "\"join\":{\"type\":\"join\", \"relations\": {\"question\":\"answer\"}}}}", XContentType.JSON); + "\"join\":{\"type\":\"join\", \"relations\": {\"question\":\"answer\"}}}}", MediaTypeRegistry.JSON); CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT); assertTrue(createIndexResponse.isAcknowledged()); @@ -255,7 +255,7 @@ private static IndexRequest buildIndexRequest(String id, String type, String que if (questionId != null) { joinField.put("parent", questionId); } - indexRequest.source(XContentType.JSON, + indexRequest.source(MediaTypeRegistry.JSON, "id", id, "type", type, "votes", randomIntBetween(0, 30), @@ -726,7 +726,7 @@ public void testCompletionSuggester() throws Exception { sourceBuilder.suggest(suggestBuilder); duelSearch(searchRequest, response -> { assertMultiClusterSearchResponse(response); - assertEquals(Strings.toString(XContentType.JSON, response, true, true), 3, response.getSuggest().size()); + assertEquals(Strings.toString(MediaTypeRegistry.JSON, response, true, true), 3, response.getSuggest().size()); assertThat(response.getSuggest().getSuggestion("python").getEntries().size(), greaterThan(0)); assertThat(response.getSuggest().getSuggestion("java").getEntries().size(), greaterThan(0)); assertThat(response.getSuggest().getSuggestion("ruby").getEntries().size(), greaterThan(0)); @@ -827,8 +827,8 @@ private static void assertAggs(SearchResponse response) { @SuppressWarnings("unchecked") private static Map responseToMap(SearchResponse response) throws IOException { - BytesReference bytesReference = XContentHelper.toXContent(response, XContentType.JSON, false); - Map responseMap = XContentHelper.convertToMap(bytesReference, false, XContentType.JSON).v2(); + BytesReference bytesReference = XContentHelper.toXContent(response, MediaTypeRegistry.JSON, false); + Map responseMap = org.opensearch.common.xcontent.XContentHelper.convertToMap(bytesReference, false, MediaTypeRegistry.JSON).v2(); assertNotNull(responseMap.put("took", -1)); responseMap.remove("num_reduce_phases"); Map profile = (Map)responseMap.get("profile"); diff --git a/qa/rolling-upgrade/src/test/java/org/opensearch/upgrades/RecoveryIT.java b/qa/rolling-upgrade/src/test/java/org/opensearch/upgrades/RecoveryIT.java index 6d143d08452e9..6c7cea5e3af93 100644 --- a/qa/rolling-upgrade/src/test/java/org/opensearch/upgrades/RecoveryIT.java +++ b/qa/rolling-upgrade/src/test/java/org/opensearch/upgrades/RecoveryIT.java @@ -45,6 +45,7 @@ import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.support.XContentMapValues; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.mapper.MapperService; import org.opensearch.core.rest.RestStatus; @@ -733,7 +734,7 @@ public void testSoftDeletesDisabledWarning() throws Exception { settings.put(IndexSettings.INDEX_SOFT_DELETES_SETTING.getKey(), softDeletesEnabled); } Request request = new Request("PUT", "/" + indexName); - request.setJsonEntity("{\"settings\": " + Strings.toString(XContentType.JSON, settings.build()) + "}"); + request.setJsonEntity("{\"settings\": " + Strings.toString(MediaTypeRegistry.JSON, settings.build()) + "}"); if (softDeletesEnabled == false) { expectSoftDeletesWarning(request, indexName); } diff --git a/qa/smoke-test-http/src/test/java/org/opensearch/http/SearchRestCancellationIT.java b/qa/smoke-test-http/src/test/java/org/opensearch/http/SearchRestCancellationIT.java index b1143ad647327..29e3d8bdcd41b 100644 --- a/qa/smoke-test-http/src/test/java/org/opensearch/http/SearchRestCancellationIT.java +++ b/qa/smoke-test-http/src/test/java/org/opensearch/http/SearchRestCancellationIT.java @@ -48,8 +48,9 @@ import org.opensearch.client.Response; import org.opensearch.client.ResponseListener; import org.opensearch.common.SetOnce; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.plugins.Plugin; import org.opensearch.plugins.PluginsService; import org.opensearch.script.MockScriptPlugin; @@ -98,12 +99,12 @@ public void testAutomaticCancellationDuringQueryPhase() throws Exception { Request searchRequest = new Request("GET", "/test/_search"); SearchSourceBuilder searchSource = new SearchSourceBuilder().query(scriptQuery( new Script(ScriptType.INLINE, "mockscript", ScriptedBlockPlugin.SCRIPT_NAME, Collections.emptyMap()))); - searchRequest.setJsonEntity(Strings.toString(XContentType.JSON, searchSource)); + searchRequest.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, searchSource)); verifyCancellationDuringQueryPhase(SearchAction.NAME, searchRequest); } public void testAutomaticCancellationMultiSearchDuringQueryPhase() throws Exception { - XContentType contentType = XContentType.JSON; + MediaType contentType = MediaTypeRegistry.JSON; MultiSearchRequest multiSearchRequest = new MultiSearchRequest().add(new SearchRequest("test") .source(new SearchSourceBuilder().scriptField("test_field", new Script(ScriptType.INLINE, "mockscript", ScriptedBlockPlugin.SCRIPT_NAME, Collections.emptyMap())))); @@ -147,12 +148,12 @@ public void testAutomaticCancellationDuringFetchPhase() throws Exception { Request searchRequest = new Request("GET", "/test/_search"); SearchSourceBuilder searchSource = new SearchSourceBuilder().scriptField("test_field", new Script(ScriptType.INLINE, "mockscript", ScriptedBlockPlugin.SCRIPT_NAME, Collections.emptyMap())); - searchRequest.setJsonEntity(Strings.toString(XContentType.JSON, searchSource)); + searchRequest.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, searchSource)); verifyCancellationDuringFetchPhase(SearchAction.NAME, searchRequest); } public void testAutomaticCancellationMultiSearchDuringFetchPhase() throws Exception { - XContentType contentType = XContentType.JSON; + MediaType contentType = MediaTypeRegistry.JSON; MultiSearchRequest multiSearchRequest = new MultiSearchRequest().add(new SearchRequest("test") .source(new SearchSourceBuilder().scriptField("test_field", new Script(ScriptType.INLINE, "mockscript", ScriptedBlockPlugin.SCRIPT_NAME, Collections.emptyMap())))); @@ -298,7 +299,7 @@ public Map, Object>> pluginScripts() { } } - private static ContentType createContentType(final XContentType xContentType) { - return ContentType.create(xContentType.mediaTypeWithoutParameters(), (Charset) null); + private static ContentType createContentType(final MediaType mediaType) { + return ContentType.create(mediaType.mediaTypeWithoutParameters(), (Charset) null); } } diff --git a/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/AbstractTasksIT.java b/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/AbstractTasksIT.java index 84e7d82d25ab2..8ba566aaa69b2 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/AbstractTasksIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/AbstractTasksIT.java @@ -16,8 +16,8 @@ import org.opensearch.cluster.service.ClusterService; import org.opensearch.common.collect.Tuple; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.plugins.Plugin; import org.opensearch.tasks.TaskId; import org.opensearch.tasks.TaskInfo; @@ -182,7 +182,7 @@ protected void indexDocumentsWithRefresh(String indexName, int numDocs) { for (int i = 0; i < numDocs; i++) { client().prepareIndex(indexName) .setId("test_id_" + String.valueOf(i)) - .setSource("{\"foo_" + String.valueOf(i) + "\": \"bar_" + String.valueOf(i) + "\"}", XContentType.JSON) + .setSource("{\"foo_" + String.valueOf(i) + "\": \"bar_" + String.valueOf(i) + "\"}", MediaTypeRegistry.JSON) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .get(); } diff --git a/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/TasksIT.java b/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/TasksIT.java index 67e52529ae86b..e6b578f41e4cf 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/TasksIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/admin/cluster/node/tasks/TasksIT.java @@ -59,7 +59,7 @@ import org.opensearch.common.collect.Tuple; import org.opensearch.common.regex.Regex; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.QueryBuilders; import org.opensearch.search.builder.SearchSourceBuilder; import org.opensearch.tasks.Task; @@ -287,7 +287,9 @@ public void testTransportBulkTasks() { ensureGreen("test"); // Make sure all shards are allocated to catch replication tasks // ensures the mapping is available on all nodes so we won't retry the request (in case replicas don't have the right mapping). client().admin().indices().preparePutMapping("test").setSource("foo", "type=keyword").get(); - client().prepareBulk().add(client().prepareIndex("test").setId("test_id").setSource("{\"foo\": \"bar\"}", XContentType.JSON)).get(); + client().prepareBulk() + .add(client().prepareIndex("test").setId("test_id").setSource("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON)) + .get(); // the bulk operation should produce one main task List topTask = findEvents(BulkAction.NAME, Tuple::v1); @@ -338,7 +340,7 @@ public void testSearchTaskDescriptions() { ensureGreen("test"); // Make sure all shards are allocated to catch replication tasks client().prepareIndex("test") .setId("test_id") - .setSource("{\"foo\": \"bar\"}", XContentType.JSON) + .setSource("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON) .setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE) .get(); diff --git a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/CloneIndexIT.java b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/CloneIndexIT.java index 98fc6483703c4..0551d19b02b8f 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/CloneIndexIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/CloneIndexIT.java @@ -37,7 +37,7 @@ import org.opensearch.action.admin.indices.stats.IndicesStatsResponse; import org.opensearch.cluster.routing.allocation.decider.EnableAllocationDecider; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.TermsQueryBuilder; import org.opensearch.index.seqno.SeqNoStats; import org.opensearch.test.OpenSearchIntegTestCase; @@ -62,7 +62,7 @@ public void testCreateCloneIndex() { ).get(); final int docs = randomIntBetween(0, 128); for (int i = 0; i < docs; i++) { - client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } internalCluster().ensureAtLeastNumDataNodes(2); // ensure all shards are allocated otherwise the ensure green below might not succeed since we require the merge node @@ -122,7 +122,7 @@ public void testCreateCloneIndex() { } for (int i = docs; i < 2 * docs; i++) { - client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } flushAndRefresh(); assertHitCount( diff --git a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/ShrinkIndexIT.java b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/ShrinkIndexIT.java index a75448dadf427..de767c0ee95bc 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/ShrinkIndexIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/ShrinkIndexIT.java @@ -67,8 +67,8 @@ import org.opensearch.common.settings.Settings; import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.Index; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.engine.SegmentsStats; import org.opensearch.index.query.TermsQueryBuilder; @@ -109,7 +109,7 @@ public void testCreateShrinkIndexToN() { for (int i = 0; i < 20; i++) { client().prepareIndex("source") .setId(Integer.toString(i)) - .setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON) + .setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON) .get(); } final Map dataNodes = client().admin().cluster().prepareState().get().getState().nodes().getDataNodes(); @@ -147,7 +147,7 @@ public void testCreateShrinkIndexToN() { for (int i = 0; i < 20; i++) { // now update client().prepareIndex("first_shrink") .setId(Integer.toString(i)) - .setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON) + .setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON) .get(); } flushAndRefresh(); @@ -190,7 +190,7 @@ public void testCreateShrinkIndexToN() { for (int i = 0; i < 20; i++) { // now update client().prepareIndex("second_shrink") .setId(Integer.toString(i)) - .setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON) + .setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON) .get(); } flushAndRefresh(); @@ -232,7 +232,7 @@ public void testShrinkIndexPrimaryTerm() throws Exception { final int hash = Math.floorMod(Murmur3HashFunction.hash(s), numberOfShards); if (hash == shardId) { final IndexRequest request = new IndexRequest("source").id(s) - .source("{ \"f\": \"" + s + "\"}", XContentType.JSON); + .source("{ \"f\": \"" + s + "\"}", MediaTypeRegistry.JSON); client().index(request).get(); break; } else { @@ -283,7 +283,7 @@ public void testCreateShrinkIndex() { ).get(); final int docs = randomIntBetween(0, 128); for (int i = 0; i < docs; i++) { - client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } final Map dataNodes = client().admin().cluster().prepareState().get().getState().nodes().getDataNodes(); assertTrue("at least 2 nodes but was: " + dataNodes.size(), dataNodes.size() >= 2); @@ -378,7 +378,7 @@ public void testCreateShrinkIndex() { } for (int i = docs; i < 2 * docs; i++) { - client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } flushAndRefresh(); assertHitCount(client().prepareSearch("target").setSize(2 * size).setQuery(new TermsQueryBuilder("foo", "bar")).get(), 2 * docs); @@ -405,7 +405,7 @@ public void testCreateShrinkIndexFails() throws Exception { Settings.builder().put(indexSettings()).put("number_of_shards", randomIntBetween(2, 7)).put("number_of_replicas", 0) ).get(); for (int i = 0; i < 20; i++) { - client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } final Map dataNodes = client().admin().cluster().prepareState().get().getState().nodes().getDataNodes(); assertTrue("at least 2 nodes but was: " + dataNodes.size(), dataNodes.size() >= 2); @@ -506,7 +506,7 @@ public void testCreateShrinkWithIndexSort() throws Exception { for (int i = 0; i < 20; i++) { client().prepareIndex("source") .setId(Integer.toString(i)) - .setSource("{\"foo\" : \"bar\", \"id\" : " + i + "}", XContentType.JSON) + .setSource("{\"foo\" : \"bar\", \"id\" : " + i + "}", MediaTypeRegistry.JSON) .get(); } final Map dataNodes = client().admin().cluster().prepareState().get().getState().nodes().getDataNodes(); @@ -569,7 +569,7 @@ public void testCreateShrinkWithIndexSort() throws Exception { // ... and that the index sort is also applied to updates for (int i = 20; i < 40; i++) { - client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } flushAndRefresh(); assertSortedSegments("target", expectedIndexSort); @@ -580,7 +580,7 @@ public void testShrinkCommitsMergeOnIdle() throws Exception { Settings.builder().put(indexSettings()).put("index.number_of_replicas", 0).put("number_of_shards", 5) ).get(); for (int i = 0; i < 30; i++) { - client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } client().admin().indices().prepareFlush("source").get(); final Map dataNodes = client().admin().cluster().prepareState().get().getState().nodes().getDataNodes(); @@ -737,7 +737,7 @@ public void testCreateShrinkIndexWithMaxShardSize() { .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, shardCount) ).get(); for (int i = 0; i < 20; i++) { - client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } client().admin().indices().prepareFlush("source").get(); ensureGreen(); diff --git a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/SplitIndexIT.java b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/SplitIndexIT.java index ea53efe176eaf..48ef1ab52747c 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/SplitIndexIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/create/SplitIndexIT.java @@ -61,8 +61,8 @@ import org.opensearch.cluster.routing.allocation.decider.EnableAllocationDecider; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.Index; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.engine.SegmentsStats; import org.opensearch.index.query.TermsQueryBuilder; @@ -347,7 +347,7 @@ public void testSplitIndexPrimaryTerm() throws Exception { final int hash = Math.floorMod(Murmur3HashFunction.hash(s), numberOfShards); if (hash == shardId) { final IndexRequest request = new IndexRequest("source").id(s) - .source("{ \"f\": \"" + s + "\"}", XContentType.JSON); + .source("{ \"f\": \"" + s + "\"}", MediaTypeRegistry.JSON); client().index(request).get(); break; } else { @@ -403,7 +403,7 @@ public void testCreateSplitIndex() throws Exception { ).get(); final int docs = randomIntBetween(0, 128); for (int i = 0; i < docs; i++) { - client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("source").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } // ensure all shards are allocated otherwise the ensure green below might not succeed since we require the merge node // if we change the setting too quickly we will end up with one replica unassigned which can't be assigned anymore due @@ -487,7 +487,7 @@ public void testCreateSplitIndex() throws Exception { } for (int i = docs; i < 2 * docs; i++) { - client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } flushAndRefresh(); assertHitCount( @@ -526,7 +526,7 @@ public void testCreateSplitWithIndexSort() throws Exception { for (int i = 0; i < 20; i++) { client().prepareIndex("source") .setId(Integer.toString(i)) - .setSource("{\"foo\" : \"bar\", \"id\" : " + i + "}", XContentType.JSON) + .setSource("{\"foo\" : \"bar\", \"id\" : " + i + "}", MediaTypeRegistry.JSON) .get(); } // ensure all shards are allocated otherwise the ensure green below might not succeed since we require the merge node @@ -582,7 +582,7 @@ public void testCreateSplitWithIndexSort() throws Exception { // ... and that the index sort is also applied to updates for (int i = 20; i < 40; i++) { - client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get(); + client().prepareIndex("target").setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", MediaTypeRegistry.JSON).get(); } flushAndRefresh(); assertSortedSegments("target", expectedIndexSort); diff --git a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/datastream/DataStreamTestCase.java b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/datastream/DataStreamTestCase.java index 44f66dd4e0f90..13bb576c35984 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/datastream/DataStreamTestCase.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/datastream/DataStreamTestCase.java @@ -19,8 +19,8 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentHelper; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.OpenSearchIntegTestCase; import java.util.List; @@ -90,7 +90,7 @@ public AcknowledgedResponse createDataStreamIndexTemplate(String name, List index(new IndexRequest("logs-demo").id("doc-1").source("{}", XContentType.JSON))); + exception = expectThrows( + Exception.class, + () -> index(new IndexRequest("logs-demo").id("doc-1").source("{}", MediaTypeRegistry.JSON)) + ); assertThat(exception.getMessage(), containsString("only write ops with an op_type of create are allowed in data streams")); // Documents must contain a valid timestamp field. exception = expectThrows( Exception.class, - () -> index(new IndexRequest("logs-demo").id("doc-1").source("{}", XContentType.JSON).opType(DocWriteRequest.OpType.CREATE)) + () -> index( + new IndexRequest("logs-demo").id("doc-1").source("{}", MediaTypeRegistry.JSON).opType(DocWriteRequest.OpType.CREATE) + ) ); assertThat( exception.getMessage(), diff --git a/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkIntegrationIT.java b/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkIntegrationIT.java index 1c2e8200abb6d..e8db4038db6ae 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkIntegrationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkIntegrationIT.java @@ -46,8 +46,8 @@ import org.opensearch.action.update.UpdateRequest; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.ingest.IngestTestPlugin; import org.opensearch.plugins.Plugin; import org.opensearch.core.rest.RestStatus; @@ -84,7 +84,7 @@ protected Collection> nodePlugins() { public void testBulkIndexCreatesMapping() throws Exception { String bulkAction = copyToStringFromClasspath("/org/opensearch/action/bulk/bulk-log.json"); BulkRequestBuilder bulkBuilder = client().prepareBulk(); - bulkBuilder.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkBuilder.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); bulkBuilder.get(); assertBusy(() -> { GetMappingsResponse mappingsResponse = client().admin().indices().prepareGetMappings().get(); @@ -155,7 +155,7 @@ public void testBulkWithGlobalDefaults() throws Exception { String bulkAction = copyToStringFromClasspath("/org/opensearch/action/bulk/simple-bulk-missing-index-type.json"); { BulkRequestBuilder bulkBuilder = client().prepareBulk(); - bulkBuilder.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkBuilder.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); ActionRequestValidationException ex = expectThrows(ActionRequestValidationException.class, bulkBuilder::get); assertThat(ex.validationErrors(), containsInAnyOrder("index is missing", "index is missing", "index is missing")); @@ -165,7 +165,7 @@ public void testBulkWithGlobalDefaults() throws Exception { createSamplePipeline("pipeline"); BulkRequestBuilder bulkBuilder = client().prepareBulk("test").routing("routing").pipeline("pipeline"); - bulkBuilder.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkBuilder.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); BulkResponse bulkItemResponses = bulkBuilder.get(); assertFalse(bulkItemResponses.hasFailures()); } @@ -183,7 +183,7 @@ private void createSamplePipeline(String pipelineId) throws IOException, Executi AcknowledgedResponse acknowledgedResponse = client().admin() .cluster() - .putPipeline(new PutPipelineRequest(pipelineId, BytesReference.bytes(pipeline), XContentType.JSON)) + .putPipeline(new PutPipelineRequest(pipelineId, BytesReference.bytes(pipeline), MediaTypeRegistry.JSON)) .get(); assertTrue(acknowledgedResponse.isAcknowledged()); @@ -201,7 +201,7 @@ public void testDeleteIndexWhileIndexing() throws Exception { try { IndexResponse response = client().prepareIndex(index) .setId(id) - .setSource(Collections.singletonMap("f" + randomIntBetween(1, 10), randomNonNegativeLong()), XContentType.JSON) + .setSource(Collections.singletonMap("f" + randomIntBetween(1, 10), randomNonNegativeLong()), MediaTypeRegistry.JSON) .get(); assertThat(response.getResult(), is(oneOf(CREATED, UPDATED))); logger.info("--> index id={} seq_no={}", response.getId(), response.getSeqNo()); diff --git a/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkProcessorClusterSettingsIT.java b/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkProcessorClusterSettingsIT.java index 14531787e9903..ea7af48266905 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkProcessorClusterSettingsIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkProcessorClusterSettingsIT.java @@ -33,7 +33,7 @@ package org.opensearch.action.bulk; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchIntegTestCase; import org.opensearch.test.OpenSearchIntegTestCase.ClusterScope; import org.opensearch.test.OpenSearchIntegTestCase.Scope; @@ -50,9 +50,9 @@ public void testBulkProcessorAutoCreateRestrictions() throws Exception { client().admin().cluster().prepareHealth("willwork").setWaitForGreenStatus().execute().actionGet(); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); - bulkRequestBuilder.add(client().prepareIndex("willwork").setId("1").setSource("{\"foo\":1}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("wontwork").setId("2").setSource("{\"foo\":2}", XContentType.JSON)); - bulkRequestBuilder.add(client().prepareIndex("willwork").setId("3").setSource("{\"foo\":3}", XContentType.JSON)); + bulkRequestBuilder.add(client().prepareIndex("willwork").setId("1").setSource("{\"foo\":1}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("wontwork").setId("2").setSource("{\"foo\":2}", MediaTypeRegistry.JSON)); + bulkRequestBuilder.add(client().prepareIndex("willwork").setId("3").setSource("{\"foo\":3}", MediaTypeRegistry.JSON)); BulkResponse br = bulkRequestBuilder.get(); BulkItemResponse[] responses = br.getItems(); assertEquals(3, responses.length); diff --git a/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkWithUpdatesIT.java b/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkWithUpdatesIT.java index 139b2cb896ded..ce6cbe23d4701 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkWithUpdatesIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/bulk/BulkWithUpdatesIT.java @@ -47,8 +47,8 @@ import org.opensearch.client.Requests; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.VersionType; import org.opensearch.indices.IndexClosedException; import org.opensearch.plugins.Plugin; @@ -618,19 +618,19 @@ public void testThatInvalidIndexNamesShouldNotBreakCompleteBulkRequest() { // issue 6630 public void testThatFailedUpdateRequestReturnsCorrectType() throws Exception { BulkResponse indexBulkItemResponse = client().prepareBulk() - .add(new IndexRequest("test").id("3").source("{ \"title\" : \"Great Title of doc 3\" }", XContentType.JSON)) - .add(new IndexRequest("test").id("4").source("{ \"title\" : \"Great Title of doc 4\" }", XContentType.JSON)) - .add(new IndexRequest("test").id("5").source("{ \"title\" : \"Great Title of doc 5\" }", XContentType.JSON)) - .add(new IndexRequest("test").id("6").source("{ \"title\" : \"Great Title of doc 6\" }", XContentType.JSON)) + .add(new IndexRequest("test").id("3").source("{ \"title\" : \"Great Title of doc 3\" }", MediaTypeRegistry.JSON)) + .add(new IndexRequest("test").id("4").source("{ \"title\" : \"Great Title of doc 4\" }", MediaTypeRegistry.JSON)) + .add(new IndexRequest("test").id("5").source("{ \"title\" : \"Great Title of doc 5\" }", MediaTypeRegistry.JSON)) + .add(new IndexRequest("test").id("6").source("{ \"title\" : \"Great Title of doc 6\" }", MediaTypeRegistry.JSON)) .setRefreshPolicy(RefreshPolicy.IMMEDIATE) .get(); assertNoFailures(indexBulkItemResponse); BulkResponse bulkItemResponse = client().prepareBulk() - .add(new IndexRequest("test").id("1").source("{ \"title\" : \"Great Title of doc 1\" }", XContentType.JSON)) - .add(new IndexRequest("test").id("2").source("{ \"title\" : \"Great Title of doc 2\" }", XContentType.JSON)) - .add(new UpdateRequest("test", "3").doc("{ \"date\" : \"2014-01-30T23:59:57\"}", XContentType.JSON)) - .add(new UpdateRequest("test", "4").doc("{ \"date\" : \"2014-13-30T23:59:57\"}", XContentType.JSON)) + .add(new IndexRequest("test").id("1").source("{ \"title\" : \"Great Title of doc 1\" }", MediaTypeRegistry.JSON)) + .add(new IndexRequest("test").id("2").source("{ \"title\" : \"Great Title of doc 2\" }", MediaTypeRegistry.JSON)) + .add(new UpdateRequest("test", "3").doc("{ \"date\" : \"2014-01-30T23:59:57\"}", MediaTypeRegistry.JSON)) + .add(new UpdateRequest("test", "4").doc("{ \"date\" : \"2014-13-30T23:59:57\"}", MediaTypeRegistry.JSON)) .add(new DeleteRequest("test", "5")) .add(new DeleteRequest("test", "6")) .get(); @@ -732,7 +732,11 @@ public void testNoopUpdate() { final BulkItemResponse noopUpdate = bulkResponse.getItems()[0]; assertThat(noopUpdate.getResponse().getResult(), equalTo(DocWriteResponse.Result.NOOP)); - assertThat(Strings.toString(XContentType.JSON, noopUpdate), noopUpdate.getResponse().getShardInfo().getSuccessful(), equalTo(2)); + assertThat( + Strings.toString(MediaTypeRegistry.JSON, noopUpdate), + noopUpdate.getResponse().getShardInfo().getSuccessful(), + equalTo(2) + ); final BulkItemResponse notFoundUpdate = bulkResponse.getItems()[1]; assertNotNull(notFoundUpdate.getFailure()); @@ -740,7 +744,7 @@ public void testNoopUpdate() { final BulkItemResponse notFoundDelete = bulkResponse.getItems()[2]; assertThat(notFoundDelete.getResponse().getResult(), equalTo(DocWriteResponse.Result.NOT_FOUND)); assertThat( - Strings.toString(XContentType.JSON, notFoundDelete), + Strings.toString(MediaTypeRegistry.JSON, notFoundDelete), notFoundDelete.getResponse().getShardInfo().getSuccessful(), equalTo(2) ); diff --git a/server/src/internalClusterTest/java/org/opensearch/action/ingest/AsyncIngestProcessorIT.java b/server/src/internalClusterTest/java/org/opensearch/action/ingest/AsyncIngestProcessorIT.java index 58c18be59fdac..c62c61d5919d6 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/ingest/AsyncIngestProcessorIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/ingest/AsyncIngestProcessorIT.java @@ -42,8 +42,8 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.NamedWriteableRegistry; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.env.Environment; import org.opensearch.env.NodeEnvironment; import org.opensearch.ingest.AbstractProcessor; @@ -84,12 +84,12 @@ protected Collection> getPlugins() { public void testAsyncProcessorImplementation() { // A pipeline with 2 processors: the test async processor and sync test processor. BytesReference pipelineBody = new BytesArray("{\"processors\": [{\"test-async\": {}, \"test\": {}}]}"); - client().admin().cluster().putPipeline(new PutPipelineRequest("_id", pipelineBody, XContentType.JSON)).actionGet(); + client().admin().cluster().putPipeline(new PutPipelineRequest("_id", pipelineBody, MediaTypeRegistry.JSON)).actionGet(); BulkRequest bulkRequest = new BulkRequest(); int numDocs = randomIntBetween(8, 256); for (int i = 0; i < numDocs; i++) { - bulkRequest.add(new IndexRequest("foobar").id(Integer.toString(i)).source("{}", XContentType.JSON).setPipeline("_id")); + bulkRequest.add(new IndexRequest("foobar").id(Integer.toString(i)).source("{}", MediaTypeRegistry.JSON).setPipeline("_id")); } BulkResponse bulkResponse = client().bulk(bulkRequest).actionGet(); assertThat(bulkResponse.getItems().length, equalTo(numDocs)); diff --git a/server/src/internalClusterTest/java/org/opensearch/action/support/WaitActiveShardCountIT.java b/server/src/internalClusterTest/java/org/opensearch/action/support/WaitActiveShardCountIT.java index c82af8bce6e2d..1300a82a52e86 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/support/WaitActiveShardCountIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/support/WaitActiveShardCountIT.java @@ -39,8 +39,8 @@ import org.opensearch.cluster.health.ClusterHealthStatus; import org.opensearch.common.Priority; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.rest.RestStatus; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchIntegTestCase; import static org.opensearch.common.unit.TimeValue.timeValueMillis; @@ -63,11 +63,11 @@ public void testReplicationWaitsForActiveShardCount() throws Exception { assertAcked(createIndexResponse); // indexing, by default, will work (waiting for one shard copy only) - client().prepareIndex("test").setId("1").setSource(source("1", "test"), XContentType.JSON).execute().actionGet(); + client().prepareIndex("test").setId("1").setSource(source("1", "test"), MediaTypeRegistry.JSON).execute().actionGet(); try { client().prepareIndex("test") .setId("1") - .setSource(source("1", "test"), XContentType.JSON) + .setSource(source("1", "test"), MediaTypeRegistry.JSON) .setWaitForActiveShards(2) // wait for 2 active shard copies .setTimeout(timeValueMillis(100)) .execute() @@ -99,7 +99,7 @@ public void testReplicationWaitsForActiveShardCount() throws Exception { // this should work, since we now have two client().prepareIndex("test") .setId("1") - .setSource(source("1", "test"), XContentType.JSON) + .setSource(source("1", "test"), MediaTypeRegistry.JSON) .setWaitForActiveShards(2) .setTimeout(timeValueSeconds(1)) .execute() @@ -108,7 +108,7 @@ public void testReplicationWaitsForActiveShardCount() throws Exception { try { client().prepareIndex("test") .setId("1") - .setSource(source("1", "test"), XContentType.JSON) + .setSource(source("1", "test"), MediaTypeRegistry.JSON) .setWaitForActiveShards(ActiveShardCount.ALL) .setTimeout(timeValueMillis(100)) .execute() @@ -143,7 +143,7 @@ public void testReplicationWaitsForActiveShardCount() throws Exception { // this should work, since we now have all shards started client().prepareIndex("test") .setId("1") - .setSource(source("1", "test"), XContentType.JSON) + .setSource(source("1", "test"), MediaTypeRegistry.JSON) .setWaitForActiveShards(ActiveShardCount.ALL) .setTimeout(timeValueSeconds(1)) .execute() diff --git a/server/src/internalClusterTest/java/org/opensearch/aliases/IndexAliasesIT.java b/server/src/internalClusterTest/java/org/opensearch/aliases/IndexAliasesIT.java index 0b050fd60f920..f91df19232971 100644 --- a/server/src/internalClusterTest/java/org/opensearch/aliases/IndexAliasesIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/aliases/IndexAliasesIT.java @@ -50,7 +50,7 @@ import org.opensearch.common.StopWatch; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.QueryBuilder; import org.opensearch.index.query.QueryBuilders; import org.opensearch.index.query.TermQueryBuilder; @@ -115,7 +115,7 @@ public void testAliases() throws Exception { logger.info("--> indexing against [alias1], should fail now"); IllegalArgumentException exception = expectThrows( IllegalArgumentException.class, - () -> client().index(indexRequest("alias1").id("1").source(source("2", "test"), XContentType.JSON)).actionGet() + () -> client().index(indexRequest("alias1").id("1").source(source("2", "test"), MediaTypeRegistry.JSON)).actionGet() ); assertThat( exception.getMessage(), @@ -132,7 +132,7 @@ public void testAliases() throws Exception { }); logger.info("--> indexing against [alias1], should work now"); - IndexResponse indexResponse = client().index(indexRequest("alias1").id("1").source(source("1", "test"), XContentType.JSON)) + IndexResponse indexResponse = client().index(indexRequest("alias1").id("1").source(source("1", "test"), MediaTypeRegistry.JSON)) .actionGet(); assertThat(indexResponse.getIndex(), equalTo("test")); @@ -149,7 +149,7 @@ public void testAliases() throws Exception { logger.info("--> indexing against [alias1], should fail now"); exception = expectThrows( IllegalArgumentException.class, - () -> client().index(indexRequest("alias1").id("1").source(source("2", "test"), XContentType.JSON)).actionGet() + () -> client().index(indexRequest("alias1").id("1").source(source("2", "test"), MediaTypeRegistry.JSON)).actionGet() ); assertThat( exception.getMessage(), @@ -177,7 +177,7 @@ public void testAliases() throws Exception { }); logger.info("--> indexing against [alias1], should work now"); - indexResponse = client().index(indexRequest("alias1").id("1").source(source("1", "test"), XContentType.JSON)).actionGet(); + indexResponse = client().index(indexRequest("alias1").id("1").source(source("1", "test"), MediaTypeRegistry.JSON)).actionGet(); assertThat(indexResponse.getIndex(), equalTo("test")); assertAliasesVersionIncreases("test_x", () -> { @@ -186,7 +186,7 @@ public void testAliases() throws Exception { }); logger.info("--> indexing against [alias1], should work now"); - indexResponse = client().index(indexRequest("alias1").id("1").source(source("1", "test"), XContentType.JSON)).actionGet(); + indexResponse = client().index(indexRequest("alias1").id("1").source(source("1", "test"), MediaTypeRegistry.JSON)).actionGet(); assertThat(indexResponse.getIndex(), equalTo("test_x")); logger.info("--> deleting against [alias1], should fail now"); @@ -199,7 +199,7 @@ public void testAliases() throws Exception { }); logger.info("--> indexing against [alias1], should work against [test_x]"); - indexResponse = client().index(indexRequest("alias1").id("1").source(source("1", "test"), XContentType.JSON)).actionGet(); + indexResponse = client().index(indexRequest("alias1").id("1").source(source("1", "test"), MediaTypeRegistry.JSON)).actionGet(); assertThat(indexResponse.getIndex(), equalTo("test_x")); } @@ -281,16 +281,18 @@ public void testSearchingFilteringAliasesSingleIndex() throws Exception { logger.info("--> indexing against [test]"); client().index( - indexRequest("test").id("1").source(source("1", "foo test"), XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE) + indexRequest("test").id("1").source(source("1", "foo test"), MediaTypeRegistry.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE) ).actionGet(); client().index( - indexRequest("test").id("2").source(source("2", "bar test"), XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE) + indexRequest("test").id("2").source(source("2", "bar test"), MediaTypeRegistry.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE) ).actionGet(); client().index( - indexRequest("test").id("3").source(source("3", "baz test"), XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE) + indexRequest("test").id("3").source(source("3", "baz test"), MediaTypeRegistry.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE) ).actionGet(); client().index( - indexRequest("test").id("4").source(source("4", "something else"), XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE) + indexRequest("test").id("4") + .source(source("4", "something else"), MediaTypeRegistry.JSON) + .setRefreshPolicy(RefreshPolicy.IMMEDIATE) ).actionGet(); logger.info("--> checking single filtering alias search"); @@ -387,16 +389,16 @@ public void testSearchingFilteringAliasesTwoIndices() throws Exception { ); logger.info("--> indexing against [test1]"); - client().index(indexRequest("test1").id("1").source(source("1", "foo test"), XContentType.JSON)).get(); - client().index(indexRequest("test1").id("2").source(source("2", "bar test"), XContentType.JSON)).get(); - client().index(indexRequest("test1").id("3").source(source("3", "baz test"), XContentType.JSON)).get(); - client().index(indexRequest("test1").id("4").source(source("4", "something else"), XContentType.JSON)).get(); + client().index(indexRequest("test1").id("1").source(source("1", "foo test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test1").id("2").source(source("2", "bar test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test1").id("3").source(source("3", "baz test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test1").id("4").source(source("4", "something else"), MediaTypeRegistry.JSON)).get(); logger.info("--> indexing against [test2]"); - client().index(indexRequest("test2").id("5").source(source("5", "foo test"), XContentType.JSON)).get(); - client().index(indexRequest("test2").id("6").source(source("6", "bar test"), XContentType.JSON)).get(); - client().index(indexRequest("test2").id("7").source(source("7", "baz test"), XContentType.JSON)).get(); - client().index(indexRequest("test2").id("8").source(source("8", "something else"), XContentType.JSON)).get(); + client().index(indexRequest("test2").id("5").source(source("5", "foo test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test2").id("6").source(source("6", "bar test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test2").id("7").source(source("7", "baz test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test2").id("8").source(source("8", "something else"), MediaTypeRegistry.JSON)).get(); refresh(); @@ -501,17 +503,17 @@ public void testSearchingFilteringAliasesMultipleIndices() throws Exception { ); logger.info("--> indexing against [test1]"); - client().index(indexRequest("test1").id("11").source(source("11", "foo test1"), XContentType.JSON)).get(); - client().index(indexRequest("test1").id("12").source(source("12", "bar test1"), XContentType.JSON)).get(); - client().index(indexRequest("test1").id("13").source(source("13", "baz test1"), XContentType.JSON)).get(); + client().index(indexRequest("test1").id("11").source(source("11", "foo test1"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test1").id("12").source(source("12", "bar test1"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test1").id("13").source(source("13", "baz test1"), MediaTypeRegistry.JSON)).get(); - client().index(indexRequest("test2").id("21").source(source("21", "foo test2"), XContentType.JSON)).get(); - client().index(indexRequest("test2").id("22").source(source("22", "bar test2"), XContentType.JSON)).get(); - client().index(indexRequest("test2").id("23").source(source("23", "baz test2"), XContentType.JSON)).get(); + client().index(indexRequest("test2").id("21").source(source("21", "foo test2"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test2").id("22").source(source("22", "bar test2"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test2").id("23").source(source("23", "baz test2"), MediaTypeRegistry.JSON)).get(); - client().index(indexRequest("test3").id("31").source(source("31", "foo test3"), XContentType.JSON)).get(); - client().index(indexRequest("test3").id("32").source(source("32", "bar test3"), XContentType.JSON)).get(); - client().index(indexRequest("test3").id("33").source(source("33", "baz test3"), XContentType.JSON)).get(); + client().index(indexRequest("test3").id("31").source(source("31", "foo test3"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test3").id("32").source(source("32", "bar test3"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test3").id("33").source(source("33", "baz test3"), MediaTypeRegistry.JSON)).get(); refresh(); @@ -624,16 +626,16 @@ public void testDeletingByQueryFilteringAliases() throws Exception { ); logger.info("--> indexing against [test1]"); - client().index(indexRequest("test1").id("1").source(source("1", "foo test"), XContentType.JSON)).get(); - client().index(indexRequest("test1").id("2").source(source("2", "bar test"), XContentType.JSON)).get(); - client().index(indexRequest("test1").id("3").source(source("3", "baz test"), XContentType.JSON)).get(); - client().index(indexRequest("test1").id("4").source(source("4", "something else"), XContentType.JSON)).get(); + client().index(indexRequest("test1").id("1").source(source("1", "foo test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test1").id("2").source(source("2", "bar test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test1").id("3").source(source("3", "baz test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test1").id("4").source(source("4", "something else"), MediaTypeRegistry.JSON)).get(); logger.info("--> indexing against [test2]"); - client().index(indexRequest("test2").id("5").source(source("5", "foo test"), XContentType.JSON)).get(); - client().index(indexRequest("test2").id("6").source(source("6", "bar test"), XContentType.JSON)).get(); - client().index(indexRequest("test2").id("7").source(source("7", "baz test"), XContentType.JSON)).get(); - client().index(indexRequest("test2").id("8").source(source("8", "something else"), XContentType.JSON)).get(); + client().index(indexRequest("test2").id("5").source(source("5", "foo test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test2").id("6").source(source("6", "bar test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test2").id("7").source(source("7", "baz test"), MediaTypeRegistry.JSON)).get(); + client().index(indexRequest("test2").id("8").source(source("8", "something else"), MediaTypeRegistry.JSON)).get(); refresh(); @@ -722,7 +724,7 @@ public void testWaitForAliasCreationMultipleShards() throws Exception { for (int i = 0; i < 10; i++) { final String aliasName = "alias" + i; assertAliasesVersionIncreases("test", () -> assertAcked(admin().indices().prepareAliases().addAlias("test", aliasName))); - client().index(indexRequest(aliasName).id("1").source(source("1", "test"), XContentType.JSON)).get(); + client().index(indexRequest(aliasName).id("1").source(source("1", "test"), MediaTypeRegistry.JSON)).get(); } } @@ -743,7 +745,7 @@ public void testWaitForAliasCreationSingleShard() throws Exception { for (int i = 0; i < 10; i++) { final String aliasName = "alias" + i; assertAliasesVersionIncreases("test", () -> assertAcked(admin().indices().prepareAliases().addAlias("test", aliasName))); - client().index(indexRequest(aliasName).id("1").source(source("1", "test"), XContentType.JSON)).get(); + client().index(indexRequest(aliasName).id("1").source(source("1", "test"), MediaTypeRegistry.JSON)).get(); } } @@ -765,7 +767,7 @@ public void run() { "test", () -> assertAcked(admin().indices().prepareAliases().addAlias("test", aliasName)) ); - client().index(indexRequest(aliasName).id("1").source(source("1", "test"), XContentType.JSON)).actionGet(); + client().index(indexRequest(aliasName).id("1").source(source("1", "test"), MediaTypeRegistry.JSON)).actionGet(); } }); } @@ -1086,7 +1088,7 @@ public void testCreateIndexWithAliasesInSource() throws Exception { + " \"alias4\" : {\"is_hidden\": true}\n" + " }\n" + "}", - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -1379,12 +1381,13 @@ public void testIndexingAndQueryingHiddenAliases() throws Exception { ensureGreen(); // Put a couple docs in each index directly - IndexResponse res = client().index(indexRequest(nonWriteIndex).id("1").source(source("1", "nonwrite"), XContentType.JSON)).get(); + IndexResponse res = client().index(indexRequest(nonWriteIndex).id("1").source(source("1", "nonwrite"), MediaTypeRegistry.JSON)) + .get(); assertThat(res.status().getStatus(), equalTo(201)); - res = client().index(indexRequest(writeIndex).id("2").source(source("2", "writeindex"), XContentType.JSON)).get(); + res = client().index(indexRequest(writeIndex).id("2").source(source("2", "writeindex"), MediaTypeRegistry.JSON)).get(); assertThat(res.status().getStatus(), equalTo(201)); // And through the alias - res = client().index(indexRequest(alias).id("3").source(source("3", "through alias"), XContentType.JSON)).get(); + res = client().index(indexRequest(alias).id("3").source(source("3", "through alias"), MediaTypeRegistry.JSON)).get(); assertThat(res.status().getStatus(), equalTo(201)); refresh(writeIndex, nonWriteIndex); diff --git a/server/src/internalClusterTest/java/org/opensearch/cluster/SimpleDataNodesIT.java b/server/src/internalClusterTest/java/org/opensearch/cluster/SimpleDataNodesIT.java index d7adf57593953..86b3b842a7da1 100644 --- a/server/src/internalClusterTest/java/org/opensearch/cluster/SimpleDataNodesIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/cluster/SimpleDataNodesIT.java @@ -41,7 +41,7 @@ import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.Priority; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchIntegTestCase; import org.opensearch.test.OpenSearchIntegTestCase.ClusterScope; import org.opensearch.test.OpenSearchIntegTestCase.Scope; @@ -62,7 +62,7 @@ public void testIndexingBeforeAndAfterDataNodesStart() { internalCluster().startNode(nonDataNode()); client().admin().indices().create(createIndexRequest("test").waitForActiveShards(ActiveShardCount.NONE)).actionGet(); try { - client().index(Requests.indexRequest("test").id("1").source(SOURCE, XContentType.JSON).timeout(timeValueSeconds(1))) + client().index(Requests.indexRequest("test").id("1").source(SOURCE, MediaTypeRegistry.JSON).timeout(timeValueSeconds(1))) .actionGet(); fail("no allocation should happen"); } catch (UnavailableShardsException e) { @@ -85,7 +85,7 @@ public void testIndexingBeforeAndAfterDataNodesStart() { // still no shard should be allocated try { - client().index(Requests.indexRequest("test").id("1").source(SOURCE, XContentType.JSON).timeout(timeValueSeconds(1))) + client().index(Requests.indexRequest("test").id("1").source(SOURCE, MediaTypeRegistry.JSON).timeout(timeValueSeconds(1))) .actionGet(); fail("no allocation should happen"); } catch (UnavailableShardsException e) { @@ -107,7 +107,8 @@ public void testIndexingBeforeAndAfterDataNodesStart() { equalTo(false) ); - IndexResponse indexResponse = client().index(Requests.indexRequest("test").id("1").source(SOURCE, XContentType.JSON)).actionGet(); + IndexResponse indexResponse = client().index(Requests.indexRequest("test").id("1").source(SOURCE, MediaTypeRegistry.JSON)) + .actionGet(); assertThat(indexResponse.getId(), equalTo("1")); } diff --git a/server/src/internalClusterTest/java/org/opensearch/cluster/routing/PrimaryAllocationIT.java b/server/src/internalClusterTest/java/org/opensearch/cluster/routing/PrimaryAllocationIT.java index 14b6ffcd50825..20fa2199e642b 100644 --- a/server/src/internalClusterTest/java/org/opensearch/cluster/routing/PrimaryAllocationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/cluster/routing/PrimaryAllocationIT.java @@ -48,8 +48,8 @@ import org.opensearch.cluster.service.ClusterService; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.set.Sets; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.gateway.GatewayAllocator; import org.opensearch.index.IndexNotFoundException; import org.opensearch.index.engine.Engine; @@ -136,7 +136,7 @@ public void testBulkWeirdScenario() throws Exception { assertThat(bulkResponse.hasFailures(), equalTo(false)); assertThat(bulkResponse.getItems().length, equalTo(2)); - logger.info(Strings.toString(XContentType.JSON, bulkResponse, true, true)); + logger.info(Strings.toString(MediaTypeRegistry.JSON, bulkResponse, true, true)); internalCluster().assertSeqNos(); diff --git a/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterDisruptionCleanSettingsIT.java b/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterDisruptionCleanSettingsIT.java index 7040bfb950663..5b33ef5c7b513 100644 --- a/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterDisruptionCleanSettingsIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterDisruptionCleanSettingsIT.java @@ -39,7 +39,7 @@ import org.opensearch.action.index.IndexRequestBuilder; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.indices.store.IndicesStoreIntegrationIT; import org.opensearch.plugins.Plugin; import org.opensearch.test.OpenSearchIntegTestCase; @@ -80,7 +80,7 @@ public void testSearchWithRelocationAndSlowClusterStateProcessing() throws Excep final String node_2 = internalCluster().startDataOnlyNode(); List indexRequestBuilderList = new ArrayList<>(); for (int i = 0; i < 100; i++) { - indexRequestBuilderList.add(client().prepareIndex().setIndex("test").setSource("{\"int_field\":1}", XContentType.JSON)); + indexRequestBuilderList.add(client().prepareIndex().setIndex("test").setSource("{\"int_field\":1}", MediaTypeRegistry.JSON)); } indexRandom(true, indexRequestBuilderList); diff --git a/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterDisruptionIT.java b/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterDisruptionIT.java index 184c866aee2db..7535762fe7d1a 100644 --- a/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterDisruptionIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterDisruptionIT.java @@ -53,7 +53,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.concurrent.ConcurrentCollections; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.VersionType; import org.opensearch.index.shard.IndexShard; import org.opensearch.index.shard.IndexShardTestCase; @@ -173,7 +173,10 @@ public void testAckedIndexing() throws Exception { logger.trace("[{}] indexing id [{}] through node [{}] targeting shard [{}]", name, id, node, shard); IndexRequestBuilder indexRequestBuilder = client.prepareIndex("test") .setId(id) - .setSource(Collections.singletonMap(randomFrom(fieldNames), randomNonNegativeLong()), XContentType.JSON) + .setSource( + Collections.singletonMap(randomFrom(fieldNames), randomNonNegativeLong()), + MediaTypeRegistry.JSON + ) .setTimeout(timeout); if (conflictMode == ConflictMode.external) { @@ -515,7 +518,10 @@ public void testRestartNodeWhileIndexing() throws Exception { try { IndexResponse response = client().prepareIndex(index) .setId(id) - .setSource(Collections.singletonMap("f" + randomIntBetween(1, 10), randomNonNegativeLong()), XContentType.JSON) + .setSource( + Collections.singletonMap("f" + randomIntBetween(1, 10), randomNonNegativeLong()), + MediaTypeRegistry.JSON + ) .get(); assertThat(response.getResult(), is(oneOf(CREATED, UPDATED))); logger.info("--> index id={} seq_no={}", response.getId(), response.getSeqNo()); diff --git a/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterManagerDisruptionIT.java b/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterManagerDisruptionIT.java index 7a7cdb5885054..1463c45aa9b2f 100644 --- a/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterManagerDisruptionIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/discovery/ClusterManagerDisruptionIT.java @@ -41,7 +41,7 @@ import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchIntegTestCase; import org.opensearch.test.disruption.BlockClusterManagerServiceOnClusterManager; import org.opensearch.test.disruption.IntermittentLongGCDisruption; @@ -326,9 +326,9 @@ public void testMappingTimeout() throws Exception { disruption.startDisrupting(); BulkRequestBuilder bulk = client().prepareBulk(); - bulk.add(client().prepareIndex("test").setId("2").setSource("{ \"f\": 1 }", XContentType.JSON)); - bulk.add(client().prepareIndex("test").setId("3").setSource("{ \"g\": 1 }", XContentType.JSON)); - bulk.add(client().prepareIndex("test").setId("4").setSource("{ \"f\": 1 }", XContentType.JSON)); + bulk.add(client().prepareIndex("test").setId("2").setSource("{ \"f\": 1 }", MediaTypeRegistry.JSON)); + bulk.add(client().prepareIndex("test").setId("3").setSource("{ \"g\": 1 }", MediaTypeRegistry.JSON)); + bulk.add(client().prepareIndex("test").setId("4").setSource("{ \"f\": 1 }", MediaTypeRegistry.JSON)); BulkResponse bulkResponse = bulk.get(); assertTrue(bulkResponse.hasFailures()); diff --git a/server/src/internalClusterTest/java/org/opensearch/document/DocumentActionsIT.java b/server/src/internalClusterTest/java/org/opensearch/document/DocumentActionsIT.java index 10e6aa906ecc9..7bccb81a38633 100644 --- a/server/src/internalClusterTest/java/org/opensearch/document/DocumentActionsIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/document/DocumentActionsIT.java @@ -43,9 +43,9 @@ import org.opensearch.action.search.SearchResponse; import org.opensearch.action.support.WriteRequest.RefreshPolicy; import org.opensearch.cluster.health.ClusterHealthStatus; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.OpenSearchIntegTestCase; import org.opensearch.test.hamcrest.OpenSearchAssertions; @@ -210,7 +210,7 @@ public void testBulk() throws Exception { .add(client().prepareIndex().setIndex("test").setSource(source("3", "test"))) .add(client().prepareIndex().setIndex("test").setCreate(true).setSource(source("4", "test"))) .add(client().prepareDelete().setIndex("test").setId("1")) - .add(client().prepareIndex().setIndex("test").setSource("{ xxx }", XContentType.JSON)) // failure + .add(client().prepareIndex().setIndex("test").setSource("{ xxx }", MediaTypeRegistry.JSON)) // failure .execute() .actionGet(); diff --git a/server/src/internalClusterTest/java/org/opensearch/document/ShardInfoIT.java b/server/src/internalClusterTest/java/org/opensearch/document/ShardInfoIT.java index 5f217548794db..4912997206a06 100644 --- a/server/src/internalClusterTest/java/org/opensearch/document/ShardInfoIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/document/ShardInfoIT.java @@ -44,7 +44,7 @@ import org.opensearch.cluster.ClusterState; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchIntegTestCase; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked; @@ -60,7 +60,7 @@ public class ShardInfoIT extends OpenSearchIntegTestCase { public void testIndexAndDelete() throws Exception { prepareIndex(1); - IndexResponse indexResponse = client().prepareIndex("idx").setSource("{}", XContentType.JSON).get(); + IndexResponse indexResponse = client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON).get(); assertShardInfo(indexResponse); DeleteResponse deleteResponse = client().prepareDelete("idx", indexResponse.getId()).get(); assertShardInfo(deleteResponse); @@ -68,7 +68,7 @@ public void testIndexAndDelete() throws Exception { public void testUpdate() throws Exception { prepareIndex(1); - UpdateResponse updateResponse = client().prepareUpdate("idx", "1").setDoc("{}", XContentType.JSON).setDocAsUpsert(true).get(); + UpdateResponse updateResponse = client().prepareUpdate("idx", "1").setDoc("{}", MediaTypeRegistry.JSON).setDocAsUpsert(true).get(); assertShardInfo(updateResponse); } @@ -76,7 +76,7 @@ public void testBulkWithIndexAndDeleteItems() throws Exception { prepareIndex(1); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); for (int i = 0; i < 10; i++) { - bulkRequestBuilder.add(client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + bulkRequestBuilder.add(client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); } BulkResponse bulkResponse = bulkRequestBuilder.get(); @@ -98,7 +98,9 @@ public void testBulkWithUpdateItems() throws Exception { prepareIndex(1); BulkRequestBuilder bulkRequestBuilder = client().prepareBulk(); for (int i = 0; i < 10; i++) { - bulkRequestBuilder.add(client().prepareUpdate("idx", Integer.toString(i)).setDoc("{}", XContentType.JSON).setDocAsUpsert(true)); + bulkRequestBuilder.add( + client().prepareUpdate("idx", Integer.toString(i)).setDoc("{}", MediaTypeRegistry.JSON).setDocAsUpsert(true) + ); } BulkResponse bulkResponse = bulkRequestBuilder.get(); diff --git a/server/src/internalClusterTest/java/org/opensearch/get/GetActionIT.java b/server/src/internalClusterTest/java/org/opensearch/get/GetActionIT.java index 2375c62342533..dd162e5b1f3b2 100644 --- a/server/src/internalClusterTest/java/org/opensearch/get/GetActionIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/get/GetActionIT.java @@ -48,9 +48,9 @@ import org.opensearch.common.lucene.uid.Versions; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.engine.VersionConflictEngineException; import org.opensearch.plugins.Plugin; import org.opensearch.core.rest.RestStatus; @@ -632,7 +632,7 @@ public void testGetFieldsComplexField() throws Exception { logger.info("indexing documents"); - client().prepareIndex("my-index").setId("1").setSource(source, XContentType.JSON).get(); + client().prepareIndex("my-index").setId("1").setSource(source, MediaTypeRegistry.JSON).get(); logger.info("checking real time retrieval"); @@ -691,7 +691,7 @@ public void testUngeneratedFieldsThatAreNeverStored() throws IOException { + " }\n" + " }\n" + "}"; - assertAcked(prepareCreate("test").addAlias(new Alias("alias")).setSource(createIndexSource, XContentType.JSON)); + assertAcked(prepareCreate("test").addAlias(new Alias("alias")).setSource(createIndexSource, MediaTypeRegistry.JSON)); ensureGreen(); String doc = "{\n" + " \"suggest\": {\n" @@ -721,10 +721,10 @@ public void testUngeneratedFieldsThatAreAlwaysStored() throws IOException { + " \"refresh_interval\": \"-1\"\n" + " }\n" + "}"; - assertAcked(prepareCreate("test").addAlias(new Alias("alias")).setSource(createIndexSource, XContentType.JSON)); + assertAcked(prepareCreate("test").addAlias(new Alias("alias")).setSource(createIndexSource, MediaTypeRegistry.JSON)); ensureGreen(); - client().prepareIndex("test").setId("1").setRouting("routingValue").setId("1").setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setRouting("routingValue").setId("1").setSource("{}", MediaTypeRegistry.JSON).get(); String[] fieldsList = { "_routing" }; // before refresh - document is only in translog @@ -745,10 +745,10 @@ public void testUngeneratedFieldsNotPartOfSourceStored() throws IOException { + " }\n" + "}"; - assertAcked(prepareCreate("test").addAlias(new Alias("alias")).setSource(createIndexSource, XContentType.JSON)); + assertAcked(prepareCreate("test").addAlias(new Alias("alias")).setSource(createIndexSource, MediaTypeRegistry.JSON)); ensureGreen(); String doc = "{\n" + " \"text\": \"some text.\"\n" + "}\n"; - client().prepareIndex("test").setId("1").setSource(doc, XContentType.JSON).setRouting("1").get(); + client().prepareIndex("test").setId("1").setSource(doc, MediaTypeRegistry.JSON).setRouting("1").get(); String[] fieldsList = { "_routing" }; // before refresh - document is only in translog assertGetFieldsAlwaysWorks(indexOrAlias(), "_doc", "1", fieldsList, "1"); @@ -816,7 +816,7 @@ void indexSingleDocumentWithStringFieldsGeneratedFromText(boolean stored, boolea + " }\n" + "}"; - assertAcked(prepareCreate("test").addAlias(new Alias("alias")).setSource(createIndexSource, XContentType.JSON)); + assertAcked(prepareCreate("test").addAlias(new Alias("alias")).setSource(createIndexSource, MediaTypeRegistry.JSON)); ensureGreen(); String doc = "{\n" + " \"text1\": \"some text.\"\n," + " \"text2\": \"more text.\"\n" + "}\n"; index("test", "_doc", "1", doc); diff --git a/server/src/internalClusterTest/java/org/opensearch/index/FinalPipelineIT.java b/server/src/internalClusterTest/java/org/opensearch/index/FinalPipelineIT.java index 22dc1224f6e09..5ea71efbe504e 100644 --- a/server/src/internalClusterTest/java/org/opensearch/index/FinalPipelineIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/index/FinalPipelineIT.java @@ -49,8 +49,8 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.NamedWriteableRegistry; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.env.Environment; import org.opensearch.env.NodeEnvironment; import org.opensearch.ingest.AbstractProcessor; @@ -103,7 +103,10 @@ public void testFinalPipelineCantChangeDestination() { createIndex("index", settings); final BytesReference finalPipelineBody = new BytesArray("{\"processors\": [{\"changing_dest\": {}}]}"); - client().admin().cluster().putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, XContentType.JSON)).actionGet(); + client().admin() + .cluster() + .putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, MediaTypeRegistry.JSON)) + .actionGet(); final IllegalStateException e = expectThrows( IllegalStateException.class, @@ -122,11 +125,14 @@ public void testFinalPipelineOfOldDestinationIsNotInvoked() { BytesReference defaultPipelineBody = new BytesArray("{\"processors\": [{\"changing_dest\": {}}]}"); client().admin() .cluster() - .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, XContentType.JSON)) + .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, MediaTypeRegistry.JSON)) .actionGet(); BytesReference finalPipelineBody = new BytesArray("{\"processors\": [{\"final\": {\"exists\":\"no_such_field\"}}]}"); - client().admin().cluster().putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, XContentType.JSON)).actionGet(); + client().admin() + .cluster() + .putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, MediaTypeRegistry.JSON)) + .actionGet(); IndexResponse indexResponse = client().prepareIndex("index") .setId("1") @@ -149,11 +155,14 @@ public void testFinalPipelineOfNewDestinationIsInvoked() { BytesReference defaultPipelineBody = new BytesArray("{\"processors\": [{\"changing_dest\": {}}]}"); client().admin() .cluster() - .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, XContentType.JSON)) + .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, MediaTypeRegistry.JSON)) .actionGet(); BytesReference finalPipelineBody = new BytesArray("{\"processors\": [{\"final\": {}}]}"); - client().admin().cluster().putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, XContentType.JSON)).actionGet(); + client().admin() + .cluster() + .putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, MediaTypeRegistry.JSON)) + .actionGet(); IndexResponse indexResponse = client().prepareIndex("index") .setId("1") @@ -176,13 +185,13 @@ public void testDefaultPipelineOfNewDestinationIsNotInvoked() { BytesReference defaultPipelineBody = new BytesArray("{\"processors\": [{\"changing_dest\": {}}]}"); client().admin() .cluster() - .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, XContentType.JSON)) + .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, MediaTypeRegistry.JSON)) .actionGet(); BytesReference targetPipeline = new BytesArray("{\"processors\": [{\"final\": {}}]}"); client().admin() .cluster() - .putPipeline(new PutPipelineRequest("target_default_pipeline", targetPipeline, XContentType.JSON)) + .putPipeline(new PutPipelineRequest("target_default_pipeline", targetPipeline, MediaTypeRegistry.JSON)) .actionGet(); IndexResponse indexResponse = client().prepareIndex("index") @@ -212,10 +221,13 @@ public void testRequestPipelineAndFinalPipeline() { final BytesReference requestPipelineBody = new BytesArray("{\"processors\": [{\"request\": {}}]}"); client().admin() .cluster() - .putPipeline(new PutPipelineRequest("request_pipeline", requestPipelineBody, XContentType.JSON)) + .putPipeline(new PutPipelineRequest("request_pipeline", requestPipelineBody, MediaTypeRegistry.JSON)) .actionGet(); final BytesReference finalPipelineBody = new BytesArray("{\"processors\": [{\"final\": {\"exists\":\"request\"}}]}"); - client().admin().cluster().putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, XContentType.JSON)).actionGet(); + client().admin() + .cluster() + .putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, MediaTypeRegistry.JSON)) + .actionGet(); final Settings settings = Settings.builder().put(IndexSettings.FINAL_PIPELINE.getKey(), "final_pipeline").build(); createIndex("index", settings); final IndexRequestBuilder index = client().prepareIndex("index").setId("1"); @@ -238,10 +250,13 @@ public void testDefaultAndFinalPipeline() { final BytesReference defaultPipelineBody = new BytesArray("{\"processors\": [{\"default\": {}}]}"); client().admin() .cluster() - .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, XContentType.JSON)) + .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, MediaTypeRegistry.JSON)) .actionGet(); final BytesReference finalPipelineBody = new BytesArray("{\"processors\": [{\"final\": {\"exists\":\"default\"}}]}"); - client().admin().cluster().putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, XContentType.JSON)).actionGet(); + client().admin() + .cluster() + .putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, MediaTypeRegistry.JSON)) + .actionGet(); final Settings settings = Settings.builder() .put(IndexSettings.DEFAULT_PIPELINE.getKey(), "default_pipeline") .put(IndexSettings.FINAL_PIPELINE.getKey(), "final_pipeline") @@ -266,10 +281,13 @@ public void testDefaultAndFinalPipelineFromTemplates() { final BytesReference defaultPipelineBody = new BytesArray("{\"processors\": [{\"default\": {}}]}"); client().admin() .cluster() - .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, XContentType.JSON)) + .putPipeline(new PutPipelineRequest("default_pipeline", defaultPipelineBody, MediaTypeRegistry.JSON)) .actionGet(); final BytesReference finalPipelineBody = new BytesArray("{\"processors\": [{\"final\": {\"exists\":\"default\"}}]}"); - client().admin().cluster().putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, XContentType.JSON)).actionGet(); + client().admin() + .cluster() + .putPipeline(new PutPipelineRequest("final_pipeline", finalPipelineBody, MediaTypeRegistry.JSON)) + .actionGet(); final int lowOrder = randomIntBetween(0, Integer.MAX_VALUE - 1); final int highOrder = randomIntBetween(lowOrder + 1, Integer.MAX_VALUE); final int finalPipelineOrder; diff --git a/server/src/internalClusterTest/java/org/opensearch/index/IndexRequestBuilderIT.java b/server/src/internalClusterTest/java/org/opensearch/index/IndexRequestBuilderIT.java index 925a1b50fd6a8..57bdaff645838 100644 --- a/server/src/internalClusterTest/java/org/opensearch/index/IndexRequestBuilderIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/index/IndexRequestBuilderIT.java @@ -36,7 +36,7 @@ import org.opensearch.action.search.SearchResponse; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.QueryBuilders; import org.opensearch.test.OpenSearchIntegTestCase; import org.opensearch.test.hamcrest.OpenSearchAssertions; @@ -54,11 +54,11 @@ public void testSetSource() throws InterruptedException, ExecutionException { map.put("test_field", "foobar"); IndexRequestBuilder[] builders = new IndexRequestBuilder[] { client().prepareIndex("test").setSource("test_field", "foobar"), - client().prepareIndex("test").setSource("{\"test_field\" : \"foobar\"}", XContentType.JSON), - client().prepareIndex("test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}"), XContentType.JSON), - client().prepareIndex("test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}"), XContentType.JSON), + client().prepareIndex("test").setSource("{\"test_field\" : \"foobar\"}", MediaTypeRegistry.JSON), + client().prepareIndex("test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}"), MediaTypeRegistry.JSON), + client().prepareIndex("test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}"), MediaTypeRegistry.JSON), client().prepareIndex("test") - .setSource(BytesReference.toBytes(new BytesArray("{\"test_field\" : \"foobar\"}")), XContentType.JSON), + .setSource(BytesReference.toBytes(new BytesArray("{\"test_field\" : \"foobar\"}")), MediaTypeRegistry.JSON), client().prepareIndex("test").setSource(map) }; indexRandom(true, builders); SearchResponse searchResponse = client().prepareSearch("test").setQuery(QueryBuilders.termQuery("test_field", "foobar")).get(); diff --git a/server/src/internalClusterTest/java/org/opensearch/index/engine/MaxDocsLimitIT.java b/server/src/internalClusterTest/java/org/opensearch/index/engine/MaxDocsLimitIT.java index 2a47e6ce74e58..2362e6f9f33b5 100644 --- a/server/src/internalClusterTest/java/org/opensearch/index/engine/MaxDocsLimitIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/index/engine/MaxDocsLimitIT.java @@ -36,7 +36,7 @@ import org.opensearch.action.search.SearchResponse; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.query.MatchAllQueryBuilder; import org.opensearch.index.translog.Translog; @@ -204,7 +204,7 @@ static IndexingResult indexDocs(int numRequests, int numThreads) throws Exceptio phaser.arriveAndAwaitAdvance(); while (completedRequests.incrementAndGet() <= numRequests) { try { - final IndexResponse resp = client().prepareIndex("test").setSource("{}", XContentType.JSON).get(); + final IndexResponse resp = client().prepareIndex("test").setSource("{}", MediaTypeRegistry.JSON).get(); numSuccess.incrementAndGet(); assertThat(resp.status(), equalTo(RestStatus.CREATED)); } catch (IllegalArgumentException e) { diff --git a/server/src/internalClusterTest/java/org/opensearch/index/seqno/GlobalCheckpointSyncIT.java b/server/src/internalClusterTest/java/org/opensearch/index/seqno/GlobalCheckpointSyncIT.java index ce7cb81dbd2df..1524c0eb8982f 100644 --- a/server/src/internalClusterTest/java/org/opensearch/index/seqno/GlobalCheckpointSyncIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/index/seqno/GlobalCheckpointSyncIT.java @@ -37,7 +37,7 @@ import org.opensearch.cluster.node.DiscoveryNodes; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.IndexSettings; import org.opensearch.index.shard.IndexShard; @@ -82,7 +82,7 @@ public void testGlobalCheckpointSyncWithAsyncDurability() throws Exception { for (int j = 0; j < 10; j++) { final String id = Integer.toString(j); - client().prepareIndex("test").setId(id).setSource("{\"foo\": " + id + "}", XContentType.JSON).get(); + client().prepareIndex("test").setId(id).setSource("{\"foo\": " + id + "}", MediaTypeRegistry.JSON).get(); } assertBusy(() -> { @@ -194,7 +194,7 @@ private void runGlobalCheckpointSyncTest( } for (int j = 0; j < numberOfDocuments; j++) { final String id = Integer.toString(index * numberOfDocuments + j); - client().prepareIndex("test").setId(id).setSource("{\"foo\": " + id + "}", XContentType.JSON).get(); + client().prepareIndex("test").setId(id).setSource("{\"foo\": " + id + "}", MediaTypeRegistry.JSON).get(); } try { barrier.await(); @@ -251,7 +251,7 @@ public void testPersistGlobalCheckpoint() throws Exception { } int numDocs = randomIntBetween(1, 20); for (int i = 0; i < numDocs; i++) { - client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", MediaTypeRegistry.JSON).get(); } ensureGreen("test"); assertBusy(() -> { @@ -281,7 +281,7 @@ public void testPersistLocalCheckpoint() { logger.info("numDocs {}", numDocs); long maxSeqNo = 0; for (int i = 0; i < numDocs; i++) { - maxSeqNo = client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", XContentType.JSON).get().getSeqNo(); + maxSeqNo = client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", MediaTypeRegistry.JSON).get().getSeqNo(); logger.info("got {}", maxSeqNo); } for (IndicesService indicesService : internalCluster().getDataNodeInstances(IndicesService.class)) { diff --git a/server/src/internalClusterTest/java/org/opensearch/index/shard/GlobalCheckpointListenersIT.java b/server/src/internalClusterTest/java/org/opensearch/index/shard/GlobalCheckpointListenersIT.java index 76ff2f809cb83..d60e852a82ca0 100644 --- a/server/src/internalClusterTest/java/org/opensearch/index/shard/GlobalCheckpointListenersIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/index/shard/GlobalCheckpointListenersIT.java @@ -34,7 +34,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.indices.IndicesService; import org.opensearch.test.OpenSearchSingleNodeTestCase; @@ -88,7 +88,7 @@ public void accept(final long g, final Exception e) { } }, null); - client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", MediaTypeRegistry.JSON).get(); assertBusy(() -> assertThat(globalCheckpoint.get(), equalTo((long) index))); // adding a listener expecting a lower global checkpoint should fire immediately final AtomicLong immediateGlobalCheckpint = new AtomicLong(); diff --git a/server/src/internalClusterTest/java/org/opensearch/index/shard/IndexShardIT.java b/server/src/internalClusterTest/java/org/opensearch/index/shard/IndexShardIT.java index d9eeb3f7f8f42..6702690c2f671 100644 --- a/server/src/internalClusterTest/java/org/opensearch/index/shard/IndexShardIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/index/shard/IndexShardIT.java @@ -61,9 +61,9 @@ import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.core.index.shard.ShardId; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.env.Environment; import org.opensearch.env.NodeEnvironment; import org.opensearch.env.ShardLock; @@ -176,7 +176,7 @@ public void testLockTryingToDelete() throws Exception { public void testDurableFlagHasEffect() throws Exception { createIndex("test"); ensureGreen(); - client().prepareIndex("test").setId("1").setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{}", MediaTypeRegistry.JSON).get(); IndicesService indicesService = getInstanceFromNode(IndicesService.class); IndexService test = indicesService.indexService(resolveIndex("test")); IndexShard shard = test.getShardOrNull(0); @@ -196,7 +196,7 @@ public void testDurableFlagHasEffect() throws Exception { setDurability(shard, Translog.Durability.REQUEST); assertFalse(needsSync.test(translog)); setDurability(shard, Translog.Durability.ASYNC); - client().prepareIndex("test").setId("2").setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId("2").setSource("{}", MediaTypeRegistry.JSON).get(); assertTrue(needsSync.test(translog)); setDurability(shard, Translog.Durability.REQUEST); client().prepareDelete("test", "1").get(); @@ -208,7 +208,7 @@ public void testDurableFlagHasEffect() throws Exception { setDurability(shard, Translog.Durability.REQUEST); assertNoFailures( client().prepareBulk() - .add(client().prepareIndex("test").setId("3").setSource("{}", XContentType.JSON)) + .add(client().prepareIndex("test").setId("3").setSource("{}", MediaTypeRegistry.JSON)) .add(client().prepareDelete("test", "1")) .get() ); @@ -217,7 +217,7 @@ public void testDurableFlagHasEffect() throws Exception { setDurability(shard, Translog.Durability.ASYNC); assertNoFailures( client().prepareBulk() - .add(client().prepareIndex("test").setId("4").setSource("{}", XContentType.JSON)) + .add(client().prepareIndex("test").setId("4").setSource("{}", MediaTypeRegistry.JSON)) .add(client().prepareDelete("test", "3")) .get() ); @@ -255,7 +255,7 @@ public void testIndexDirIsDeletedWhenShardRemoved() throws Exception { Settings idxSettings = Settings.builder().put(IndexMetadata.SETTING_DATA_PATH, idxPath).build(); createIndex("test", idxSettings); ensureGreen("test"); - client().prepareIndex("test").setId("1").setSource("{}", XContentType.JSON).setRefreshPolicy(IMMEDIATE).get(); + client().prepareIndex("test").setId("1").setSource("{}", MediaTypeRegistry.JSON).setRefreshPolicy(IMMEDIATE).get(); SearchResponse response = client().prepareSearch("test").get(); assertHitCount(response, 1L); client().admin().indices().prepareDelete("test").get(); @@ -271,7 +271,7 @@ public void testExpectedShardSizeIsPresent() throws InterruptedException { .setSettings(Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 0)) ); for (int i = 0; i < 50; i++) { - client().prepareIndex("test").setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setSource("{}", MediaTypeRegistry.JSON).get(); } ensureGreen("test"); InternalClusterInfoService clusterInfoService = (InternalClusterInfoService) getInstanceFromNode(ClusterInfoService.class); @@ -394,14 +394,14 @@ public void testMaybeFlush() throws Exception { .get(); client().prepareIndex("test") .setId("0") - .setSource("{}", XContentType.JSON) + .setSource("{}", MediaTypeRegistry.JSON) .setRefreshPolicy(randomBoolean() ? IMMEDIATE : NONE) .get(); assertFalse(shard.shouldPeriodicallyFlush()); shard.applyIndexOperationOnPrimary( Versions.MATCH_ANY, VersionType.INTERNAL, - new SourceToParse("test", "1", new BytesArray("{}"), XContentType.JSON), + new SourceToParse("test", "1", new BytesArray("{}"), MediaTypeRegistry.JSON), SequenceNumbers.UNASSIGNED_SEQ_NO, 0, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, @@ -413,7 +413,7 @@ public void testMaybeFlush() throws Exception { assertThat(shard.flushStats().getTotal(), equalTo(0L)); client().prepareIndex("test") .setId("2") - .setSource("{}", XContentType.JSON) + .setSource("{}", MediaTypeRegistry.JSON) .setRefreshPolicy(randomBoolean() ? IMMEDIATE : NONE) .get(); assertThat(shard.getLastKnownGlobalCheckpoint(), equalTo(2L)); @@ -454,7 +454,7 @@ public void testMaybeFlush() throws Exception { final FlushStats flushStats = shard.flushStats(); logger.info( "--> translog stats [{}] gen [{}] commit_stats [{}] flush_stats [{}/{}]", - Strings.toString(XContentType.JSON, translogStats), + Strings.toString(MediaTypeRegistry.JSON, translogStats), translog.getGeneration().translogFileGeneration, commitStats.getUserData(), flushStats.getPeriodic(), @@ -486,7 +486,7 @@ public void testMaybeRollTranslogGeneration() throws Exception { final Engine.IndexResult result = shard.applyIndexOperationOnPrimary( Versions.MATCH_ANY, VersionType.INTERNAL, - new SourceToParse("test", "1", new BytesArray("{}"), XContentType.JSON), + new SourceToParse("test", "1", new BytesArray("{}"), MediaTypeRegistry.JSON), SequenceNumbers.UNASSIGNED_SEQ_NO, 0, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, @@ -522,7 +522,7 @@ public void testStressMaybeFlushOrRollTranslogGeneration() throws Exception { client().admin().indices().prepareUpdateSettings("test").setSettings(settings).get(); client().prepareIndex("test") .setId("0") - .setSource("{}", XContentType.JSON) + .setSource("{}", MediaTypeRegistry.JSON) .setRefreshPolicy(randomBoolean() ? IMMEDIATE : NONE) .get(); assertFalse(shard.shouldPeriodicallyFlush()); @@ -547,7 +547,7 @@ public void testStressMaybeFlushOrRollTranslogGeneration() throws Exception { final CheckedRunnable check; if (flush) { final FlushStats initialStats = shard.flushStats(); - client().prepareIndex("test").setId("1").setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{}", MediaTypeRegistry.JSON).get(); check = () -> { assertFalse(shard.shouldPeriodicallyFlush()); final FlushStats currentStats = shard.flushStats(); @@ -572,7 +572,7 @@ public void testStressMaybeFlushOrRollTranslogGeneration() throws Exception { }; } else { final long generation = getTranslog(shard).currentFileGeneration(); - client().prepareIndex("test").setId("1").setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{}", MediaTypeRegistry.JSON).get(); check = () -> { assertFalse(shard.shouldRollTranslogGeneration()); assertEquals(generation + 1, getTranslog(shard).currentFileGeneration()); @@ -593,7 +593,7 @@ public void testFlushStats() throws Exception { client().admin().indices().prepareUpdateSettings("test").setSettings(settings).get(); final int numDocs = between(10, 100); for (int i = 0; i < numDocs; i++) { - client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", MediaTypeRegistry.JSON).get(); } // A flush stats may include the new total count but the old period count - assert eventually. assertBusy(() -> { @@ -604,7 +604,7 @@ public void testFlushStats() throws Exception { settings = Settings.builder().put("index.translog.flush_threshold_size", (String) null).build(); client().admin().indices().prepareUpdateSettings("test").setSettings(settings).get(); - client().prepareIndex("test").setId(UUIDs.randomBase64UUID()).setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId(UUIDs.randomBase64UUID()).setSource("{}", MediaTypeRegistry.JSON).get(); client().admin().indices().prepareFlush("test").setForce(randomBoolean()).setWaitIfOngoing(true).get(); final FlushStats flushStats = client().admin().indices().prepareStats("test").clear().setFlush(true).get().getTotal().flush; assertThat(flushStats.getTotal(), greaterThan(flushStats.getPeriodic())); @@ -616,9 +616,9 @@ public void testShardHasMemoryBufferOnTranslogRecover() throws Throwable { IndicesService indicesService = getInstanceFromNode(IndicesService.class); IndexService indexService = indicesService.indexService(resolveIndex("test")); IndexShard shard = indexService.getShardOrNull(0); - client().prepareIndex("test").setId("0").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("0").setSource("{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON).get(); client().prepareDelete("test", "0").get(); - client().prepareIndex("test").setId("1").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).setRefreshPolicy(IMMEDIATE).get(); + client().prepareIndex("test").setId("1").setSource("{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON).setRefreshPolicy(IMMEDIATE).get(); CheckedFunction wrapper = directoryReader -> directoryReader; shard.close("simon says", false, false); @@ -734,7 +734,7 @@ public void testInvalidateIndicesRequestCacheWhenRollbackEngine() throws Excepti final SearchRequest countRequest = new SearchRequest("test").source(new SearchSourceBuilder().size(0)); final long numDocs = between(10, 20); for (int i = 0; i < numDocs; i++) { - client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", MediaTypeRegistry.JSON).get(); if (randomBoolean()) { shard.refresh("test"); } @@ -756,7 +756,7 @@ public void testInvalidateIndicesRequestCacheWhenRollbackEngine() throws Excepti final long moreDocs = between(10, 20); for (int i = 0; i < moreDocs; i++) { - client().prepareIndex("test").setId(Long.toString(i + numDocs)).setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId(Long.toString(i + numDocs)).setSource("{}", MediaTypeRegistry.JSON).get(); if (randomBoolean()) { shard.refresh("test"); } @@ -787,7 +787,7 @@ public void testShardChangesWithDefaultDocType() throws Exception { int numOps = between(1, 10); for (int i = 0; i < numOps; i++) { if (randomBoolean()) { - client().prepareIndex("index").setId(randomFrom("1", "2")).setSource("{}", XContentType.JSON).get(); + client().prepareIndex("index").setId(randomFrom("1", "2")).setSource("{}", MediaTypeRegistry.JSON).get(); } else { client().prepareDelete("index", randomFrom("1", "2")).get(); } @@ -850,7 +850,7 @@ public void testLimitNumberOfRetainedTranslogFiles() throws Exception { } }; for (int i = 0; i < 100; i++) { - client().prepareIndex(indexName).setId(Integer.toString(i)).setSource("{}", XContentType.JSON).get(); + client().prepareIndex(indexName).setId(Integer.toString(i)).setSource("{}", MediaTypeRegistry.JSON).get(); if (randomInt(100) < 10) { client().admin().indices().prepareFlush(indexName).setWaitIfOngoing(true).get(); checkTranslog.run(); diff --git a/server/src/internalClusterTest/java/org/opensearch/index/shard/SearchIdleIT.java b/server/src/internalClusterTest/java/org/opensearch/index/shard/SearchIdleIT.java index 9382960b906e3..7a02f7831fb59 100644 --- a/server/src/internalClusterTest/java/org/opensearch/index/shard/SearchIdleIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/index/shard/SearchIdleIT.java @@ -38,7 +38,7 @@ import org.opensearch.action.index.IndexResponse; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.IndexSettings; import org.opensearch.test.OpenSearchSingleNodeTestCase; @@ -102,7 +102,7 @@ private void runTestAutomaticRefresh(final IntToLongFunction count) throws Inter int numDocs = scaledRandomIntBetween(25, 100); totalNumDocs.set(numDocs); CountDownLatch indexingDone = new CountDownLatch(numDocs); - client().prepareIndex("test").setId("0").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("0").setSource("{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON).get(); indexingDone.countDown(); // one doc is indexed above blocking IndexShard shard = indexService.getShard(0); boolean hasRefreshed = shard.scheduledRefresh(); @@ -135,7 +135,7 @@ private void runTestAutomaticRefresh(final IntToLongFunction count) throws Inter for (int i = 1; i < numDocs; i++) { client().prepareIndex("test") .setId("" + i) - .setSource("{\"foo\" : \"bar\"}", XContentType.JSON) + .setSource("{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON) .execute(new ActionListener() { @Override public void onResponse(IndexResponse indexResponse) { @@ -159,7 +159,7 @@ public void testPendingRefreshWithIntervalChange() throws Exception { IndexService indexService = createIndex("test", builder.build()); assertFalse(indexService.getIndexSettings().isExplicitRefresh()); ensureGreen(); - client().prepareIndex("test").setId("0").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("0").setSource("{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON).get(); IndexShard shard = indexService.getShard(0); assertFalse(shard.scheduledRefresh()); assertTrue(shard.isSearchIdle()); @@ -167,7 +167,7 @@ public void testPendingRefreshWithIntervalChange() throws Exception { client().admin().indices().prepareRefresh().execute(ActionListener.wrap(refreshLatch::countDown));// async on purpose to make sure // it happens concurrently assertHitCount(client().prepareSearch().get(), 1); - client().prepareIndex("test").setId("1").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON).get(); assertFalse(shard.scheduledRefresh()); assertTrue(shard.hasRefreshPending()); @@ -186,7 +186,7 @@ public void testPendingRefreshWithIntervalChange() throws Exception { // We need to ensure a `scheduledRefresh` triggered by the internal refresh setting update is executed before we index a new doc; // otherwise, it will compete to call `Engine#maybeRefresh` with the `scheduledRefresh` that we are going to verify. ensureNoPendingScheduledRefresh(indexService.getThreadPool()); - client().prepareIndex("test").setId("2").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("2").setSource("{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON).get(); assertTrue(shard.scheduledRefresh()); assertFalse(shard.hasRefreshPending()); assertTrue(shard.isSearchIdle()); diff --git a/server/src/internalClusterTest/java/org/opensearch/indices/DateMathIndexExpressionsIntegrationIT.java b/server/src/internalClusterTest/java/org/opensearch/indices/DateMathIndexExpressionsIntegrationIT.java index 7236c32697384..b7024ff091e66 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indices/DateMathIndexExpressionsIntegrationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indices/DateMathIndexExpressionsIntegrationIT.java @@ -41,7 +41,7 @@ import org.opensearch.action.search.SearchResponse; import org.opensearch.cluster.ClusterState; import org.opensearch.cluster.metadata.IndexMetadata; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchIntegTestCase; import org.joda.time.DateTime; @@ -71,9 +71,9 @@ public void testIndexNameDateMathExpressions() { String dateMathExp1 = "<.marvel-{now/d}>"; String dateMathExp2 = "<.marvel-{now/d-1d}>"; String dateMathExp3 = "<.marvel-{now/d-2d}>"; - client().prepareIndex(dateMathExp1).setId("1").setSource("{}", XContentType.JSON).get(); - client().prepareIndex(dateMathExp2).setId("2").setSource("{}", XContentType.JSON).get(); - client().prepareIndex(dateMathExp3).setId("3").setSource("{}", XContentType.JSON).get(); + client().prepareIndex(dateMathExp1).setId("1").setSource("{}", MediaTypeRegistry.JSON).get(); + client().prepareIndex(dateMathExp2).setId("2").setSource("{}", MediaTypeRegistry.JSON).get(); + client().prepareIndex(dateMathExp3).setId("3").setSource("{}", MediaTypeRegistry.JSON).get(); refresh(); SearchResponse searchResponse = client().prepareSearch(dateMathExp1, dateMathExp2, dateMathExp3).get(); @@ -131,9 +131,9 @@ public void testAutoCreateIndexWithDateMathExpression() throws Exception { String dateMathExp1 = "<.marvel-{now/d}>"; String dateMathExp2 = "<.marvel-{now/d-1d}>"; String dateMathExp3 = "<.marvel-{now/d-2d}>"; - client().prepareIndex(dateMathExp1).setId("1").setSource("{}", XContentType.JSON).get(); - client().prepareIndex(dateMathExp2).setId("2").setSource("{}", XContentType.JSON).get(); - client().prepareIndex(dateMathExp3).setId("3").setSource("{}", XContentType.JSON).get(); + client().prepareIndex(dateMathExp1).setId("1").setSource("{}", MediaTypeRegistry.JSON).get(); + client().prepareIndex(dateMathExp2).setId("2").setSource("{}", MediaTypeRegistry.JSON).get(); + client().prepareIndex(dateMathExp3).setId("3").setSource("{}", MediaTypeRegistry.JSON).get(); refresh(); SearchResponse searchResponse = client().prepareSearch(dateMathExp1, dateMathExp2, dateMathExp3).get(); diff --git a/server/src/internalClusterTest/java/org/opensearch/indices/mapping/UpdateMappingIntegrationIT.java b/server/src/internalClusterTest/java/org/opensearch/indices/mapping/UpdateMappingIntegrationIT.java index da3dcdc6b750e..78011e4dd4beb 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indices/mapping/UpdateMappingIntegrationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indices/mapping/UpdateMappingIntegrationIT.java @@ -43,9 +43,9 @@ import org.opensearch.common.Priority; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.common.xcontent.support.XContentMapValues; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.MappedFieldType; import org.opensearch.index.mapper.MapperService; @@ -153,7 +153,7 @@ public void testUpdateMappingWithoutType() { AcknowledgedResponse putMappingResponse = client().admin() .indices() .preparePutMapping("test") - .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}", XContentType.JSON) + .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}", MediaTypeRegistry.JSON) .execute() .actionGet(); @@ -178,7 +178,7 @@ public void testUpdateMappingWithoutTypeMultiObjects() { AcknowledgedResponse putMappingResponse = client().admin() .indices() .preparePutMapping("test") - .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}", XContentType.JSON) + .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}", MediaTypeRegistry.JSON) .execute() .actionGet(); @@ -207,7 +207,7 @@ public void testUpdateMappingWithConflicts() { .preparePutMapping("test") .setSource( "{\"" + MapperService.SINGLE_MAPPING_NAME + "\":{\"properties\":{\"body\":{\"type\":\"integer\"}}}}", - XContentType.JSON + MediaTypeRegistry.JSON ) .execute() .actionGet(); @@ -230,7 +230,7 @@ public void testUpdateMappingWithNormsConflicts() { .preparePutMapping("test") .setSource( "{\"" + MapperService.SINGLE_MAPPING_NAME + "\":{\"properties\":{\"body\":{\"type\":\"text\", \"norms\": true }}}}", - XContentType.JSON + MediaTypeRegistry.JSON ) .execute() .actionGet(); @@ -256,7 +256,7 @@ public void testUpdateMappingNoChanges() { AcknowledgedResponse putMappingResponse = client().admin() .indices() .preparePutMapping("test") - .setSource("{\"properties\":{\"body\":{\"type\":\"text\"}}}", XContentType.JSON) + .setSource("{\"properties\":{\"body\":{\"type\":\"text\"}}}", MediaTypeRegistry.JSON) .execute() .actionGet(); @@ -347,7 +347,7 @@ public void testPutMappingsWithBlocks() { client().admin() .indices() .preparePutMapping("test") - .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}", XContentType.JSON) + .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}", MediaTypeRegistry.JSON) ); } finally { disableIndexBlock("test", block); @@ -361,7 +361,7 @@ public void testPutMappingsWithBlocks() { client().admin() .indices() .preparePutMapping("test") - .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}", XContentType.JSON) + .setSource("{\"properties\":{\"date\":{\"type\":\"integer\"}}}", MediaTypeRegistry.JSON) ); } finally { disableIndexBlock("test", block); diff --git a/server/src/internalClusterTest/java/org/opensearch/indices/recovery/IndexRecoveryIT.java b/server/src/internalClusterTest/java/org/opensearch/indices/recovery/IndexRecoveryIT.java index efd43ec5ad82d..6b3e8a227118f 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indices/recovery/IndexRecoveryIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indices/recovery/IndexRecoveryIT.java @@ -82,7 +82,7 @@ import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.gateway.ReplicaShardAllocatorIT; import org.opensearch.core.index.Index; import org.opensearch.index.IndexService; @@ -899,14 +899,14 @@ public void testTransientErrorsDuringRecoveryAreRetried() throws Exception { // is a mix of file chunks and translog ops int threeFourths = (int) (numDocs * 0.75); for (int i = 0; i < threeFourths; i++) { - requests.add(client().prepareIndex(indexName).setSource("{}", XContentType.JSON)); + requests.add(client().prepareIndex(indexName).setSource("{}", MediaTypeRegistry.JSON)); } indexRandom(true, requests); flush(indexName); requests.clear(); for (int i = threeFourths; i < numDocs; i++) { - requests.add(client().prepareIndex(indexName).setSource("{}", XContentType.JSON)); + requests.add(client().prepareIndex(indexName).setSource("{}", MediaTypeRegistry.JSON)); } indexRandom(true, requests); ensureSearchable(indexName); @@ -1098,7 +1098,7 @@ public void testDisconnectsWhileRecovering() throws Exception { List requests = new ArrayList<>(); int numDocs = scaledRandomIntBetween(25, 250); for (int i = 0; i < numDocs; i++) { - requests.add(client().prepareIndex(indexName).setSource("{}", XContentType.JSON)); + requests.add(client().prepareIndex(indexName).setSource("{}", MediaTypeRegistry.JSON)); } indexRandom(true, requests); ensureSearchable(indexName); @@ -1252,7 +1252,7 @@ public void testDisconnectsDuringRecovery() throws Exception { List requests = new ArrayList<>(); int numDocs = scaledRandomIntBetween(25, 250); for (int i = 0; i < numDocs; i++) { - requests.add(client().prepareIndex(indexName).setSource("{}", XContentType.JSON)); + requests.add(client().prepareIndex(indexName).setSource("{}", MediaTypeRegistry.JSON)); } indexRandom(true, requests); ensureSearchable(indexName); @@ -1395,7 +1395,7 @@ public void testHistoryRetention() throws Exception { final List requests = new ArrayList<>(); final int replicatedDocCount = scaledRandomIntBetween(25, 250); while (requests.size() < replicatedDocCount) { - requests.add(client().prepareIndex(indexName).setSource("{}", XContentType.JSON)); + requests.add(client().prepareIndex(indexName).setSource("{}", MediaTypeRegistry.JSON)); } indexRandom(true, requests); if (randomBoolean()) { @@ -1417,7 +1417,7 @@ public void testHistoryRetention() throws Exception { final int numNewDocs = scaledRandomIntBetween(25, 250); for (int i = 0; i < numNewDocs; i++) { - client().prepareIndex(indexName).setSource("{}", XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE).get(); + client().prepareIndex(indexName).setSource("{}", MediaTypeRegistry.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE).get(); } // Flush twice to update the safe commit's local checkpoint assertThat(client().admin().indices().prepareFlush(indexName).setForce(true).execute().get().getFailedShards(), equalTo(0)); @@ -1458,7 +1458,7 @@ public void testDoNotInfinitelyWaitForMapping() { for (int i = 0; i < numDocs; i++) { client().prepareIndex("test") .setId("u" + i) - .setSource(singletonMap("test_field", Integer.toString(i)), XContentType.JSON) + .setSource(singletonMap("test_field", Integer.toString(i)), MediaTypeRegistry.JSON) .get(); } Semaphore recoveryBlocked = new Semaphore(1); @@ -1610,7 +1610,7 @@ public void testRecoverLocallyUpToGlobalCheckpoint() throws Exception { throw new AssertionError( "expect an operation-based recovery:" + "retention leases" - + Strings.toString(XContentType.JSON, retentionLeases) + + Strings.toString(MediaTypeRegistry.JSON, retentionLeases) + "]" ); } @@ -2187,7 +2187,10 @@ public void testPeerRecoveryTrimsLocalTranslog() throws Exception { while (stopped.get() == false) { try { IndexResponse response = client().prepareIndex(indexName) - .setSource(Collections.singletonMap("f" + randomIntBetween(1, 10), randomNonNegativeLong()), XContentType.JSON) + .setSource( + Collections.singletonMap("f" + randomIntBetween(1, 10), randomNonNegativeLong()), + MediaTypeRegistry.JSON + ) .get(); assertThat(response.getResult(), isOneOf(CREATED, UPDATED)); } catch (IllegalStateException | OpenSearchException ignored) {} diff --git a/server/src/internalClusterTest/java/org/opensearch/indices/stats/IndexStatsIT.java b/server/src/internalClusterTest/java/org/opensearch/indices/stats/IndexStatsIT.java index 35f2b99c94625..233c8811ca6f4 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indices/stats/IndexStatsIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indices/stats/IndexStatsIT.java @@ -55,8 +55,8 @@ import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.io.stream.StreamOutput; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexModule; import org.opensearch.index.IndexService; import org.opensearch.index.IndexSettings; @@ -1012,7 +1012,10 @@ public void testCompletionFieldsParam() throws Exception { ); ensureGreen(); - client().prepareIndex("test1").setId(Integer.toString(1)).setSource("{\"bar\":\"bar\",\"baz\":\"baz\"}", XContentType.JSON).get(); + client().prepareIndex("test1") + .setId(Integer.toString(1)) + .setSource("{\"bar\":\"bar\",\"baz\":\"baz\"}", MediaTypeRegistry.JSON) + .get(); refresh(); IndicesStatsRequestBuilder builder = client().admin().indices().prepareStats(); @@ -1357,7 +1360,7 @@ public void testConcurrentIndexingAndStatsRequests() throws BrokenBarrierExcepti } while (!stop.get()) { final String id = Integer.toString(idGenerator.incrementAndGet()); - final IndexResponse response = client().prepareIndex("test").setId(id).setSource("{}", XContentType.JSON).get(); + final IndexResponse response = client().prepareIndex("test").setId(id).setSource("{}", MediaTypeRegistry.JSON).get(); assertThat(response.getResult(), equalTo(DocWriteResponse.Result.CREATED)); } }); diff --git a/server/src/internalClusterTest/java/org/opensearch/indices/template/SimpleIndexTemplateIT.java b/server/src/internalClusterTest/java/org/opensearch/indices/template/SimpleIndexTemplateIT.java index a6381b4450010..3be234b393a7a 100644 --- a/server/src/internalClusterTest/java/org/opensearch/indices/template/SimpleIndexTemplateIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/indices/template/SimpleIndexTemplateIT.java @@ -50,7 +50,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.settings.SettingsException; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.mapper.MapperParsingException; import org.opensearch.index.query.QueryBuilders; import org.opensearch.indices.InvalidAliasNameException; @@ -478,7 +478,7 @@ public void testBrokenMapping() throws Exception { .indices() .preparePutTemplate("template_1") .setPatterns(Collections.singletonList("te*")) - .setMapping("{\"foo\": \"abcde\"}", XContentType.JSON) + .setMapping("{\"foo\": \"abcde\"}", MediaTypeRegistry.JSON) .get() ); assertThat(e.getMessage(), containsString("Failed to parse mapping ")); @@ -591,7 +591,7 @@ public void testIndexTemplateWithAliasesInSource() { + " }\n" + "}" ), - XContentType.JSON + MediaTypeRegistry.JSON ) .get(); @@ -803,8 +803,8 @@ public void testStrictAliasParsingInIndicesCreatedViaTemplates() throws Exceptio .addAlias(new Alias("alias4").filter(termQuery("field", "value"))) .get(); - client().prepareIndex("a1").setId("test").setSource("{}", XContentType.JSON).get(); - BulkResponse response = client().prepareBulk().add(new IndexRequest("a2").id("test").source("{}", XContentType.JSON)).get(); + client().prepareIndex("a1").setId("test").setSource("{}", MediaTypeRegistry.JSON).get(); + BulkResponse response = client().prepareBulk().add(new IndexRequest("a2").id("test").source("{}", MediaTypeRegistry.JSON)).get(); assertThat(response.hasFailures(), is(false)); assertThat(response.getItems()[0].isFailed(), equalTo(false)); assertThat(response.getItems()[0].getIndex(), equalTo("a2")); @@ -819,9 +819,9 @@ public void testStrictAliasParsingInIndicesCreatedViaTemplates() throws Exceptio // So the aliases defined in the index template for this index will not fail // even though the fields in the alias fields don't exist yet and indexing into // an index that doesn't exist yet will succeed - client().prepareIndex("b1").setId("test").setSource("{}", XContentType.JSON).get(); + client().prepareIndex("b1").setId("test").setSource("{}", MediaTypeRegistry.JSON).get(); - response = client().prepareBulk().add(new IndexRequest("b2").id("test").source("{}", XContentType.JSON)).get(); + response = client().prepareBulk().add(new IndexRequest("b2").id("test").source("{}", MediaTypeRegistry.JSON)).get(); assertThat(response.hasFailures(), is(false)); assertThat(response.getItems()[0].isFailed(), equalTo(false)); assertThat(response.getItems()[0].getId(), equalTo("test")); @@ -854,7 +854,7 @@ public void testCombineTemplates() throws Exception { + " }\n" + " }\n" + " }\n", - XContentType.JSON + MediaTypeRegistry.JSON ) .get(); @@ -992,7 +992,7 @@ public void testPartitionedTemplate() throws Exception { .indices() .preparePutTemplate("template_2") .setPatterns(Collections.singletonList("te*")) - .setMapping("{\"_routing\":{\"required\":false}}", XContentType.JSON) + .setMapping("{\"_routing\":{\"required\":false}}", MediaTypeRegistry.JSON) .setSettings(Settings.builder().put("index.number_of_shards", "6").put("index.routing_partition_size", "3")) .get() ); diff --git a/server/src/internalClusterTest/java/org/opensearch/ingest/IngestClientIT.java b/server/src/internalClusterTest/java/org/opensearch/ingest/IngestClientIT.java index 49d09cada59b3..17fd54ff8fdb6 100644 --- a/server/src/internalClusterTest/java/org/opensearch/ingest/IngestClientIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/ingest/IngestClientIT.java @@ -53,8 +53,8 @@ import org.opensearch.client.Requests; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.plugins.Plugin; import org.opensearch.test.OpenSearchIntegTestCase; @@ -100,7 +100,7 @@ public void testSimulate() throws Exception { .endArray() .endObject() ); - client().admin().cluster().preparePutPipeline("_id", pipelineSource, XContentType.JSON).get(); + client().admin().cluster().preparePutPipeline("_id", pipelineSource, MediaTypeRegistry.JSON).get(); GetPipelineResponse getResponse = client().admin().cluster().prepareGetPipeline("_id").get(); assertThat(getResponse.isFound(), is(true)); assertThat(getResponse.pipelines().size(), equalTo(1)); @@ -122,9 +122,9 @@ public void testSimulate() throws Exception { ); SimulatePipelineResponse response; if (randomBoolean()) { - response = client().admin().cluster().prepareSimulatePipeline(bytes, XContentType.JSON).setId("_id").get(); + response = client().admin().cluster().prepareSimulatePipeline(bytes, MediaTypeRegistry.JSON).setId("_id").get(); } else { - SimulatePipelineRequest request = new SimulatePipelineRequest(bytes, XContentType.JSON); + SimulatePipelineRequest request = new SimulatePipelineRequest(bytes, MediaTypeRegistry.JSON); request.setId("_id"); response = client().admin().cluster().simulatePipeline(request).get(); } @@ -160,7 +160,7 @@ public void testBulkWithIngestFailures() throws Exception { .endArray() .endObject() ); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id", source, XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id", source, MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); int numRequests = scaledRandomIntBetween(32, 128); @@ -211,7 +211,7 @@ public void testBulkWithUpsert() throws Exception { .endArray() .endObject() ); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id", source, XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id", source, MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); BulkRequest bulkRequest = new BulkRequest(); @@ -220,7 +220,7 @@ public void testBulkWithUpsert() throws Exception { bulkRequest.add(indexRequest); UpdateRequest updateRequest = new UpdateRequest("index", "2"); updateRequest.doc("{}", Requests.INDEX_CONTENT_TYPE); - updateRequest.upsert("{\"field1\":\"upserted_val\"}", XContentType.JSON).upsertRequest().setPipeline("_id"); + updateRequest.upsert("{\"field1\":\"upserted_val\"}", MediaTypeRegistry.JSON).upsertRequest().setPipeline("_id"); bulkRequest.add(updateRequest); BulkResponse response = client().bulk(bulkRequest).actionGet(); @@ -246,7 +246,7 @@ public void test() throws Exception { .endArray() .endObject() ); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id", source, XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id", source, MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); GetPipelineRequest getPipelineRequest = new GetPipelineRequest("_id"); @@ -290,7 +290,7 @@ public void testPutWithPipelineFactoryError() throws Exception { .endArray() .endObject() ); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id2", source, XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id2", source, MediaTypeRegistry.JSON); Exception e = expectThrows( OpenSearchParseException.class, () -> client().admin().cluster().putPipeline(putPipelineRequest).actionGet() @@ -314,7 +314,7 @@ public void testWithDedicatedClusterManager() throws Exception { .endArray() .endObject() ); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id", source, XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("_id", source, MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); BulkItemResponse item = client(clusterManagerOnlyNode).prepareBulk() @@ -340,7 +340,7 @@ public void testPipelineOriginHeader() throws Exception { source.endArray(); } source.endObject(); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("1", BytesReference.bytes(source), XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("1", BytesReference.bytes(source), MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); } { @@ -357,7 +357,7 @@ public void testPipelineOriginHeader() throws Exception { source.endArray(); } source.endObject(); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("2", BytesReference.bytes(source), XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("2", BytesReference.bytes(source), MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); } { @@ -373,13 +373,13 @@ public void testPipelineOriginHeader() throws Exception { source.endArray(); } source.endObject(); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("3", BytesReference.bytes(source), XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("3", BytesReference.bytes(source), MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); } Exception e = expectThrows(Exception.class, () -> { IndexRequest indexRequest = new IndexRequest("test"); - indexRequest.source("{}", XContentType.JSON); + indexRequest.source("{}", MediaTypeRegistry.JSON); indexRequest.setPipeline("1"); client().index(indexRequest).get(); }); @@ -413,7 +413,7 @@ public void testPipelineProcessorOnFailure() throws Exception { source.endArray(); } source.endObject(); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("1", BytesReference.bytes(source), XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("1", BytesReference.bytes(source), MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); } { @@ -430,7 +430,7 @@ public void testPipelineProcessorOnFailure() throws Exception { source.endArray(); } source.endObject(); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("2", BytesReference.bytes(source), XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("2", BytesReference.bytes(source), MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); } { @@ -446,11 +446,11 @@ public void testPipelineProcessorOnFailure() throws Exception { source.endArray(); } source.endObject(); - PutPipelineRequest putPipelineRequest = new PutPipelineRequest("3", BytesReference.bytes(source), XContentType.JSON); + PutPipelineRequest putPipelineRequest = new PutPipelineRequest("3", BytesReference.bytes(source), MediaTypeRegistry.JSON); client().admin().cluster().putPipeline(putPipelineRequest).get(); } - client().prepareIndex("test").setId("1").setSource("{}", XContentType.JSON).setPipeline("1").get(); + client().prepareIndex("test").setId("1").setSource("{}", MediaTypeRegistry.JSON).setPipeline("1").get(); Map inserted = client().prepareGet("test", "1").get().getSourceAsMap(); assertThat(inserted.get("readme"), equalTo("pipeline with id [3] is a bad pipeline")); } diff --git a/server/src/internalClusterTest/java/org/opensearch/ingest/IngestProcessorNotInstalledOnAllNodesIT.java b/server/src/internalClusterTest/java/org/opensearch/ingest/IngestProcessorNotInstalledOnAllNodesIT.java index 4b4a0d9d0157c..38f1375bc7504 100644 --- a/server/src/internalClusterTest/java/org/opensearch/ingest/IngestProcessorNotInstalledOnAllNodesIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/ingest/IngestProcessorNotInstalledOnAllNodesIT.java @@ -35,7 +35,7 @@ import org.opensearch.OpenSearchParseException; import org.opensearch.action.support.master.AcknowledgedResponse; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.node.NodeService; import org.opensearch.plugins.Plugin; import org.opensearch.test.OpenSearchIntegTestCase; @@ -84,7 +84,7 @@ public void testFailPipelineCreation() throws Exception { ensureStableCluster(2, node2); try { - client().admin().cluster().preparePutPipeline("_id", pipelineSource, XContentType.JSON).get(); + client().admin().cluster().preparePutPipeline("_id", pipelineSource, MediaTypeRegistry.JSON).get(); fail("exception expected"); } catch (OpenSearchParseException e) { assertThat(e.getMessage(), containsString("Processor type [test] is not installed on node")); @@ -97,7 +97,7 @@ public void testFailPipelineCreationProcessorNotInstalledOnClusterManagerNode() internalCluster().startNode(); try { - client().admin().cluster().preparePutPipeline("_id", pipelineSource, XContentType.JSON).get(); + client().admin().cluster().preparePutPipeline("_id", pipelineSource, MediaTypeRegistry.JSON).get(); fail("exception expected"); } catch (OpenSearchParseException e) { assertThat(e.getMessage(), equalTo("No processor type exists with name [test]")); @@ -110,7 +110,7 @@ public void testFailStartNode() throws Exception { installPlugin = true; String node1 = internalCluster().startNode(); - AcknowledgedResponse response = client().admin().cluster().preparePutPipeline("_id", pipelineSource, XContentType.JSON).get(); + AcknowledgedResponse response = client().admin().cluster().preparePutPipeline("_id", pipelineSource, MediaTypeRegistry.JSON).get(); assertThat(response.isAcknowledged(), is(true)); Pipeline pipeline = internalCluster().getInstance(NodeService.class, node1).getIngestService().getPipeline("_id"); assertThat(pipeline, notNullValue()); diff --git a/server/src/internalClusterTest/java/org/opensearch/mget/SimpleMgetIT.java b/server/src/internalClusterTest/java/org/opensearch/mget/SimpleMgetIT.java index 7109d8e331ce3..3b72ff251c4fa 100644 --- a/server/src/internalClusterTest/java/org/opensearch/mget/SimpleMgetIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/mget/SimpleMgetIT.java @@ -41,7 +41,7 @@ import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.search.fetch.subphase.FetchSourceContext; import org.opensearch.test.OpenSearchIntegTestCase; @@ -159,7 +159,7 @@ public void testThatSourceFilteringIsSupported() throws Exception { .endObject() ); for (int i = 0; i < 100; i++) { - client().prepareIndex("test").setId(Integer.toString(i)).setSource(sourceBytesRef, XContentType.JSON).get(); + client().prepareIndex("test").setId(Integer.toString(i)).setSource(sourceBytesRef, MediaTypeRegistry.JSON).get(); } MultiGetRequestBuilder request = client().prepareMultiGet(); diff --git a/server/src/internalClusterTest/java/org/opensearch/recovery/RelocationIT.java b/server/src/internalClusterTest/java/org/opensearch/recovery/RelocationIT.java index b3821c7896b8e..796f253990bcb 100644 --- a/server/src/internalClusterTest/java/org/opensearch/recovery/RelocationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/recovery/RelocationIT.java @@ -54,7 +54,7 @@ import org.opensearch.common.Priority; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.env.NodeEnvironment; import org.opensearch.index.IndexService; import org.opensearch.index.IndexSettings; @@ -374,12 +374,12 @@ public void indexShardStateChanged( List builders1 = new ArrayList<>(); for (int numDocs = randomIntBetween(10, 30); numDocs > 0; numDocs--) { - builders1.add(client().prepareIndex("test").setSource("{}", XContentType.JSON)); + builders1.add(client().prepareIndex("test").setSource("{}", MediaTypeRegistry.JSON)); } List builders2 = new ArrayList<>(); for (int numDocs = randomIntBetween(10, 30); numDocs > 0; numDocs--) { - builders2.add(client().prepareIndex("test").setSource("{}", XContentType.JSON)); + builders2.add(client().prepareIndex("test").setSource("{}", MediaTypeRegistry.JSON)); } logger.info("--> START relocate the shard from {} to {}", nodes[fromNode], nodes[toNode]); @@ -439,7 +439,7 @@ public void testCancellationCleansTempFiles() throws Exception { List requests = new ArrayList<>(); int numDocs = scaledRandomIntBetween(25, 250); for (int i = 0; i < numDocs; i++) { - requests.add(client().prepareIndex(indexName).setSource("{}", XContentType.JSON)); + requests.add(client().prepareIndex(indexName).setSource("{}", MediaTypeRegistry.JSON)); } indexRandom(true, requests); assertFalse(client().admin().cluster().prepareHealth().setWaitForNodes("3").setWaitForGreenStatus().get().isTimedOut()); diff --git a/server/src/internalClusterTest/java/org/opensearch/recovery/SimpleRecoveryIT.java b/server/src/internalClusterTest/java/org/opensearch/recovery/SimpleRecoveryIT.java index 4ebb840c600d2..ef4f5c3eeea86 100644 --- a/server/src/internalClusterTest/java/org/opensearch/recovery/SimpleRecoveryIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/recovery/SimpleRecoveryIT.java @@ -36,7 +36,7 @@ import org.opensearch.action.admin.indices.refresh.RefreshResponse; import org.opensearch.action.get.GetResponse; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchIntegTestCase; import static org.opensearch.client.Requests.flushRequest; @@ -67,12 +67,12 @@ public void testSimpleRecovery() throws Exception { NumShards numShards = getNumShards("test"); - client().index(indexRequest("test").id("1").source(source("1", "test"), XContentType.JSON)).actionGet(); + client().index(indexRequest("test").id("1").source(source("1", "test"), MediaTypeRegistry.JSON)).actionGet(); FlushResponse flushResponse = client().admin().indices().flush(flushRequest("test")).actionGet(); assertThat(flushResponse.getTotalShards(), equalTo(numShards.totalNumShards)); assertThat(flushResponse.getSuccessfulShards(), equalTo(numShards.numPrimaries)); assertThat(flushResponse.getFailedShards(), equalTo(0)); - client().index(indexRequest("test").id("2").source(source("2", "test"), XContentType.JSON)).actionGet(); + client().index(indexRequest("test").id("2").source(source("2", "test"), MediaTypeRegistry.JSON)).actionGet(); RefreshResponse refreshResponse = client().admin().indices().refresh(refreshRequest("test")).actionGet(); assertThat(refreshResponse.getTotalShards(), equalTo(numShards.totalNumShards)); assertThat(refreshResponse.getSuccessfulShards(), equalTo(numShards.numPrimaries)); diff --git a/server/src/internalClusterTest/java/org/opensearch/remotestore/PrimaryTermValidationIT.java b/server/src/internalClusterTest/java/org/opensearch/remotestore/PrimaryTermValidationIT.java index ee32c880257d1..9e42e5b4d8565 100644 --- a/server/src/internalClusterTest/java/org/opensearch/remotestore/PrimaryTermValidationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/remotestore/PrimaryTermValidationIT.java @@ -21,7 +21,7 @@ import org.opensearch.common.UUIDs; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.shard.ShardNotFoundException; import org.opensearch.plugins.Plugin; import org.opensearch.test.OpenSearchIntegTestCase; @@ -163,7 +163,7 @@ public void testPrimaryTermValidation() throws Exception { private IndexResponse indexSameDoc(String nodeName, String indexName) { return client(nodeName).prepareIndex(indexName) .setId(UUIDs.randomBase64UUID()) - .setSource("{\"foo\" : \"bar\"}", XContentType.JSON) + .setSource("{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON) .get(); } } diff --git a/server/src/internalClusterTest/java/org/opensearch/remotestore/RemoteStoreBackpressureIT.java b/server/src/internalClusterTest/java/org/opensearch/remotestore/RemoteStoreBackpressureIT.java index 9641c013bf226..703cb7da3d009 100644 --- a/server/src/internalClusterTest/java/org/opensearch/remotestore/RemoteStoreBackpressureIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/remotestore/RemoteStoreBackpressureIT.java @@ -13,10 +13,10 @@ import org.opensearch.action.admin.cluster.settings.ClusterUpdateSettingsResponse; import org.opensearch.common.settings.Settings; import org.opensearch.core.common.unit.ByteSizeUnit; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.remote.RemoteSegmentTransferTracker; import org.opensearch.repositories.RepositoriesService; import org.opensearch.snapshots.mockstore.MockRepository; @@ -128,7 +128,7 @@ private RemoteSegmentTransferTracker.Stats stats() { private void indexDocAndRefresh(BytesReference source, int iterations) { for (int i = 0; i < iterations; i++) { - client().prepareIndex(INDEX_NAME).setSource(source, XContentType.JSON).get(); + client().prepareIndex(INDEX_NAME).setSource(source, MediaTypeRegistry.JSON).get(); refresh(INDEX_NAME); } } diff --git a/server/src/internalClusterTest/java/org/opensearch/script/StoredScriptsIT.java b/server/src/internalClusterTest/java/org/opensearch/script/StoredScriptsIT.java index 448bbf5e883ec..583693741f3dd 100644 --- a/server/src/internalClusterTest/java/org/opensearch/script/StoredScriptsIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/script/StoredScriptsIT.java @@ -33,7 +33,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.plugins.Plugin; import org.opensearch.test.OpenSearchIntegTestCase; @@ -69,7 +69,7 @@ public void testBasics() { .cluster() .preparePutStoredScript() .setId("foobar") - .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"1\"} }"), XContentType.JSON) + .setContent(new BytesArray("{\"script\": {\"lang\": \"" + LANG + "\", \"source\": \"1\"} }"), MediaTypeRegistry.JSON) ); String script = client().admin().cluster().prepareGetStoredScript("foobar").get().getSource().getSource(); assertNotNull(script); @@ -81,7 +81,12 @@ public void testBasics() { IllegalArgumentException e = expectThrows( IllegalArgumentException.class, - () -> client().admin().cluster().preparePutStoredScript().setId("id#").setContent(new BytesArray("{}"), XContentType.JSON).get() + () -> client().admin() + .cluster() + .preparePutStoredScript() + .setId("id#") + .setContent(new BytesArray("{}"), MediaTypeRegistry.JSON) + .get() ); assertEquals("Validation Failed: 1: id cannot contain '#' for stored script;", e.getMessage()); } @@ -95,7 +100,7 @@ public void testMaxScriptSize() { .setId("foobar") .setContent( new BytesArray("{\"script\": { \"lang\": \"" + LANG + "\"," + " \"source\":\"0123456789abcdef\"} }"), - XContentType.JSON + MediaTypeRegistry.JSON ) .get() ); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/SearchCancellationIT.java b/server/src/internalClusterTest/java/org/opensearch/search/SearchCancellationIT.java index eedd9328826a5..7fb0bc45fb084 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/SearchCancellationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/SearchCancellationIT.java @@ -50,8 +50,8 @@ import org.opensearch.action.support.WriteRequest; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.plugins.Plugin; import org.opensearch.plugins.PluginsService; import org.opensearch.script.MockScriptPlugin; @@ -229,7 +229,7 @@ public void testCancellationDuringQueryPhase() throws Exception { awaitForBlock(plugins); cancelSearch(SearchAction.NAME); disableBlocks(plugins); - logger.info("Segments {}", Strings.toString(XContentType.JSON, client().admin().indices().prepareSegments("test").get())); + logger.info("Segments {}", Strings.toString(MediaTypeRegistry.JSON, client().admin().indices().prepareSegments("test").get())); ensureSearchWasCancelled(searchResponse); } @@ -283,7 +283,7 @@ public void testCancellationDuringFetchPhase() throws Exception { awaitForBlock(plugins); cancelSearch(SearchAction.NAME); disableBlocks(plugins); - logger.info("Segments {}", Strings.toString(XContentType.JSON, client().admin().indices().prepareSegments("test").get())); + logger.info("Segments {}", Strings.toString(MediaTypeRegistry.JSON, client().admin().indices().prepareSegments("test").get())); ensureSearchWasCancelled(searchResponse); } diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/NestedIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/NestedIT.java index ed3edc8c624f8..0579fa8aa63c0 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/NestedIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/NestedIT.java @@ -38,8 +38,8 @@ import org.opensearch.action.search.SearchRequestBuilder; import org.opensearch.action.search.SearchResponse; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.query.InnerHitBuilder; import org.opensearch.core.rest.RestStatus; import org.opensearch.search.aggregations.Aggregator.SubAggCollectionMode; @@ -461,7 +461,7 @@ public void testParentFilterResolvedCorrectly() throws Exception { "{\"dates\": {\"month\": {\"label\": \"2014-11\", \"end\": \"2014-11-30\", \"start\": \"2014-11-01\"}, " + "\"day\": \"2014-11-30\"}, \"comments\": [{\"cid\": 3,\"identifier\": \"29111\"}, {\"cid\": 4,\"tags\": [" + "{\"tid\" :44,\"name\": \"Roles\"}], \"identifier\": \"29101\"}]}", - XContentType.JSON + MediaTypeRegistry.JSON ) ); indexRequests.add( @@ -471,7 +471,7 @@ public void testParentFilterResolvedCorrectly() throws Exception { "{\"dates\": {\"month\": {\"label\": \"2014-12\", \"end\": \"2014-12-31\", \"start\": \"2014-12-01\"}, " + "\"day\": \"2014-12-03\"}, \"comments\": [{\"cid\": 1, \"identifier\": \"29111\"}, {\"cid\": 2,\"tags\": [" + "{\"tid\" : 22, \"name\": \"DataChannels\"}], \"identifier\": \"29101\"}]}", - XContentType.JSON + MediaTypeRegistry.JSON ) ); indexRandom(true, indexRequests); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/SignificantTermsSignificanceScoreIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/SignificantTermsSignificanceScoreIT.java index 0854faf6c515c..4f067a48875b3 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/SignificantTermsSignificanceScoreIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/SignificantTermsSignificanceScoreIT.java @@ -36,10 +36,10 @@ import org.opensearch.action.search.SearchRequestBuilder; import org.opensearch.action.search.SearchResponse; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.query.QueryBuilder; import org.opensearch.index.query.QueryBuilders; import org.opensearch.index.query.TermQueryBuilder; @@ -242,7 +242,7 @@ public void testConsistencyWithDifferentShardCounts() throws Exception { public void testPopularTermManyDeletedDocs() throws Exception { String settings = "{\"index.number_of_shards\": 1, \"index.number_of_replicas\": 0}"; assertAcked( - prepareCreate(INDEX_NAME).setSettings(settings, XContentType.JSON) + prepareCreate(INDEX_NAME).setSettings(settings, MediaTypeRegistry.JSON) .setMapping("text", "type=keyword", CLASS_FIELD, "type=keyword") ); String[] cat1v1 = { "constant", "one" }; diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/TermsShardMinDocCountIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/TermsShardMinDocCountIT.java index 852c3760751b3..e7e826d981c84 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/TermsShardMinDocCountIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/TermsShardMinDocCountIT.java @@ -34,7 +34,7 @@ import org.opensearch.action.index.IndexRequestBuilder; import org.opensearch.action.search.SearchResponse; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.QueryBuilders; import org.opensearch.search.aggregations.BucketOrder; import org.opensearch.search.aggregations.bucket.filter.InternalFilter; @@ -124,10 +124,10 @@ private void addTermsDocs(String term, int numInClass, int numNotInClass, List builders) { String sourceClass = "{\"text\": \"" + term + "\"}"; for (int i = 0; i < numDocs; i++) { - builders.add(client().prepareIndex(index).setSource(sourceClass, XContentType.JSON)); + builders.add(client().prepareIndex(index).setSource(sourceClass, MediaTypeRegistry.JSON)); } } } diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/metrics/ScriptedMetricIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/metrics/ScriptedMetricIT.java index 2034bbb7e13bc..e762801f51ef5 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/metrics/ScriptedMetricIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/metrics/ScriptedMetricIT.java @@ -38,8 +38,8 @@ import org.opensearch.action.search.SearchResponse; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.support.XContentMapValues; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.plugins.Plugin; import org.opensearch.script.MockScriptPlugin; import org.opensearch.script.Script; @@ -332,7 +332,7 @@ public void setupSuiteScopeCluster() throws Exception { new BytesArray( "{\"script\": {\"lang\": \"" + MockScriptPlugin.NAME + "\"," + " \"source\": \"vars.multiplier = 3\"} }" ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -345,7 +345,7 @@ public void setupSuiteScopeCluster() throws Exception { new BytesArray( "{\"script\": {\"lang\": \"" + MockScriptPlugin.NAME + "\"," + " \"source\": \"state.list.add(vars.multiplier)\"} }" ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -361,7 +361,7 @@ public void setupSuiteScopeCluster() throws Exception { + "\"," + " \"source\": \"sum state values as a new aggregation\"} }" ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -377,7 +377,7 @@ public void setupSuiteScopeCluster() throws Exception { + "\"," + " \"source\": \"sum all states (lists) values as a new aggregation\"} }" ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/BucketScriptIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/BucketScriptIT.java index e8e21d3580e1c..32d86072393f9 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/BucketScriptIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/BucketScriptIT.java @@ -35,9 +35,9 @@ import org.opensearch.action.index.IndexRequestBuilder; import org.opensearch.action.search.SearchResponse; import org.opensearch.core.common.bytes.BytesArray; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.plugins.Plugin; import org.opensearch.script.MockScriptPlugin; import org.opensearch.script.Script; @@ -551,7 +551,7 @@ public void testStoredScript() { // Script source is not interpreted but it references a pre-defined script from CustomScriptPlugin .setContent( new BytesArray("{ \"script\": {\"lang\": \"" + CustomScriptPlugin.NAME + "\"," + " \"source\": \"my_script\" } }"), - XContentType.JSON + MediaTypeRegistry.JSON ) ); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/BucketSelectorIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/BucketSelectorIT.java index 8fe8876c7593b..7b802478a46d8 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/BucketSelectorIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/BucketSelectorIT.java @@ -35,8 +35,8 @@ import org.opensearch.action.index.IndexRequestBuilder; import org.opensearch.action.search.SearchResponse; import org.opensearch.core.common.bytes.BytesArray; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.plugins.Plugin; import org.opensearch.script.MockScriptPlugin; import org.opensearch.script.Script; @@ -488,7 +488,7 @@ public void testStoredScript() { + "\", " + "\"source\": \"Double.isNaN(_value0) ? false : (_value0 + _value1 > 100)\" } }" ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/MaxBucketIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/MaxBucketIT.java index bb7aa9514564a..9e183248eabbd 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/MaxBucketIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/MaxBucketIT.java @@ -36,9 +36,9 @@ import org.opensearch.action.search.SearchResponse; import org.opensearch.action.support.WriteRequest; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.search.aggregations.AggregationBuilders; import org.opensearch.search.aggregations.BucketOrder; import org.opensearch.search.aggregations.PipelineAggregatorBuilders; @@ -585,7 +585,7 @@ public void testFieldIsntWrittenOutTwice() throws Exception { groupByLicenseAgg.subAggregation(peakPipelineAggBuilder); SearchResponse response = client().prepareSearch("foo_*").setSize(0).addAggregation(groupByLicenseAgg).get(); - BytesReference bytes = XContentHelper.toXContent(response, XContentType.JSON, false); - XContentHelper.convertToMap(bytes, false, XContentType.JSON); + BytesReference bytes = org.opensearch.core.xcontent.XContentHelper.toXContent(response, MediaTypeRegistry.JSON, false); + XContentHelper.convertToMap(bytes, false, MediaTypeRegistry.JSON); } } diff --git a/server/src/internalClusterTest/java/org/opensearch/search/fetch/subphase/MatchedQueriesIT.java b/server/src/internalClusterTest/java/org/opensearch/search/fetch/subphase/MatchedQueriesIT.java index d83f1eb776b20..2d38d4531fede 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/fetch/subphase/MatchedQueriesIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/fetch/subphase/MatchedQueriesIT.java @@ -34,8 +34,8 @@ import org.opensearch.action.search.SearchResponse; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.XContentHelper; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.MatchQueryBuilder; import org.opensearch.index.query.QueryBuilder; import org.opensearch.index.query.QueryBuilders; @@ -354,9 +354,9 @@ public void testMatchedWithWrapperQuery() throws Exception { refresh(); MatchQueryBuilder matchQueryBuilder = matchQuery("content", "amet").queryName("abc"); - BytesReference matchBytes = XContentHelper.toXContent(matchQueryBuilder, XContentType.JSON, false); + BytesReference matchBytes = XContentHelper.toXContent(matchQueryBuilder, MediaTypeRegistry.JSON, false); TermQueryBuilder termQueryBuilder = termQuery("content", "amet").queryName("abc"); - BytesReference termBytes = XContentHelper.toXContent(termQueryBuilder, XContentType.JSON, false); + BytesReference termBytes = XContentHelper.toXContent(termQueryBuilder, MediaTypeRegistry.JSON, false); QueryBuilder[] queries = new QueryBuilder[] { wrapperQuery(matchBytes), constantScoreQuery(wrapperQuery(termBytes)) }; for (QueryBuilder query : queries) { SearchResponse searchResponse = client().prepareSearch().setQuery(query).get(); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/fields/SearchFieldsIT.java b/server/src/internalClusterTest/java/org/opensearch/search/fields/SearchFieldsIT.java index 53eb290e1edbf..20dede0d78799 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/fields/SearchFieldsIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/fields/SearchFieldsIT.java @@ -43,9 +43,9 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.time.DateFormatter; import org.opensearch.common.time.DateUtils; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.support.XContentMapValues; import org.opensearch.index.fielddata.ScriptDocValues; import org.opensearch.index.mapper.MapperService; @@ -221,7 +221,7 @@ public void testStoredFields() throws Exception { .endObject() .toString(); - client().admin().indices().preparePutMapping().setSource(mapping, XContentType.JSON).get(); + client().admin().indices().preparePutMapping().setSource(mapping, MediaTypeRegistry.JSON).get(); client().prepareIndex("test") .setId("1") @@ -315,7 +315,7 @@ public void testScriptDocAndFields() throws Exception { .endObject() .toString(); - client().admin().indices().preparePutMapping().setSource(mapping, XContentType.JSON).get(); + client().admin().indices().preparePutMapping().setSource(mapping, MediaTypeRegistry.JSON).get(); client().prepareIndex("test") .setId("1") @@ -416,7 +416,7 @@ public void testScriptWithUnsignedLong() throws Exception { .endObject() .toString(); - client().admin().indices().preparePutMapping().setSource(mapping, XContentType.JSON).get(); + client().admin().indices().preparePutMapping().setSource(mapping, MediaTypeRegistry.JSON).get(); client().prepareIndex("test") .setId("1") @@ -517,7 +517,7 @@ public void testScriptFieldWithNanos() throws Exception { .endObject() .toString(); - client().admin().indices().preparePutMapping().setSource(mapping, XContentType.JSON).get(); + client().admin().indices().preparePutMapping().setSource(mapping, MediaTypeRegistry.JSON).get(); String date = "2019-01-31T10:00:00.123456789Z"; indexRandom( true, @@ -753,7 +753,7 @@ public void testStoredFieldsWithoutSource() throws Exception { .endObject() .toString(); - client().admin().indices().preparePutMapping().setSource(mapping, XContentType.JSON).get(); + client().admin().indices().preparePutMapping().setSource(mapping, MediaTypeRegistry.JSON).get(); ZonedDateTime date = ZonedDateTime.of(2012, 3, 22, 0, 0, 0, 0, ZoneOffset.UTC); client().prepareIndex("test") @@ -911,7 +911,7 @@ public void testGetFieldsComplexField() throws Exception { .endObject() ); - client().prepareIndex("my-index").setId("1").setRefreshPolicy(IMMEDIATE).setSource(source, XContentType.JSON).get(); + client().prepareIndex("my-index").setId("1").setRefreshPolicy(IMMEDIATE).setSource(source, MediaTypeRegistry.JSON).get(); String field = "field1.field2.field3.field4"; @@ -991,7 +991,7 @@ public void testDocValueFields() throws Exception { .endObject() .toString(); - client().admin().indices().preparePutMapping().setSource(mapping, XContentType.JSON).get(); + client().admin().indices().preparePutMapping().setSource(mapping, MediaTypeRegistry.JSON).get(); ZonedDateTime date = ZonedDateTime.of(2012, 3, 22, 0, 0, 0, 0, ZoneOffset.UTC); client().prepareIndex("test") diff --git a/server/src/internalClusterTest/java/org/opensearch/search/geo/GeoFilterIT.java b/server/src/internalClusterTest/java/org/opensearch/search/geo/GeoFilterIT.java index d4467b49d1c18..9be9e712fcca0 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/geo/GeoFilterIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/geo/GeoFilterIT.java @@ -56,9 +56,9 @@ import org.opensearch.common.geo.builders.PointBuilder; import org.opensearch.common.geo.builders.PolygonBuilder; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.Streams; import org.opensearch.index.query.QueryBuilders; import org.opensearch.search.SearchHit; @@ -242,7 +242,7 @@ public void testShapeRelations() throws Exception { ); BytesReference data = BytesReference.bytes(jsonBuilder().startObject().field("area", polygon).endObject()); - client().prepareIndex("shapes").setId("1").setSource(data, XContentType.JSON).get(); + client().prepareIndex("shapes").setId("1").setSource(data, MediaTypeRegistry.JSON).get(); client().admin().indices().prepareRefresh().get(); // Point in polygon @@ -305,7 +305,7 @@ public void testShapeRelations() throws Exception { ); data = BytesReference.bytes(jsonBuilder().startObject().field("area", inverse).endObject()); - client().prepareIndex("shapes").setId("2").setSource(data, XContentType.JSON).get(); + client().prepareIndex("shapes").setId("2").setSource(data, MediaTypeRegistry.JSON).get(); client().admin().indices().prepareRefresh().get(); // re-check point on polygon hole @@ -344,7 +344,7 @@ public void testShapeRelations() throws Exception { ); data = BytesReference.bytes(jsonBuilder().startObject().field("area", builder).endObject()); - client().prepareIndex("shapes").setId("1").setSource(data, XContentType.JSON).get(); + client().prepareIndex("shapes").setId("1").setSource(data, MediaTypeRegistry.JSON).get(); client().admin().indices().prepareRefresh().get(); // Create a polygon crossing longitude 180 with hole. @@ -357,7 +357,7 @@ public void testShapeRelations() throws Exception { ); data = BytesReference.bytes(jsonBuilder().startObject().field("area", builder).endObject()); - client().prepareIndex("shapes").setId("1").setSource(data, XContentType.JSON).get(); + client().prepareIndex("shapes").setId("1").setSource(data, MediaTypeRegistry.JSON).get(); client().admin().indices().prepareRefresh().get(); result = client().prepareSearch() diff --git a/server/src/internalClusterTest/java/org/opensearch/search/geo/GeoShapeIntegrationIT.java b/server/src/internalClusterTest/java/org/opensearch/search/geo/GeoShapeIntegrationIT.java index cf1a1f82d7200..aef9c0714f6da 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/geo/GeoShapeIntegrationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/geo/GeoShapeIntegrationIT.java @@ -40,7 +40,7 @@ import org.opensearch.common.geo.builders.ShapeBuilder; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.GeoShapeFieldMapper; import org.opensearch.index.mapper.MappedFieldType; @@ -196,7 +196,7 @@ public void testMappingUpdate() throws Exception { IllegalArgumentException e = expectThrows( IllegalArgumentException.class, - () -> client().admin().indices().preparePutMapping("test").setSource(update, XContentType.JSON).get() + () -> client().admin().indices().preparePutMapping("test").setSource(update, MediaTypeRegistry.JSON).get() ); assertThat(e.getMessage(), containsString("using [BKD] strategy cannot be merged with")); } @@ -227,7 +227,7 @@ public void testIndexShapeRouting() throws Exception { + " }\n" + "}"; - indexRandom(true, client().prepareIndex("test").setId("0").setSource(source, XContentType.JSON).setRouting("ABC")); + indexRandom(true, client().prepareIndex("test").setId("0").setSource(source, MediaTypeRegistry.JSON).setRouting("ABC")); SearchResponse searchResponse = client().prepareSearch("test") .setQuery(geoShapeQuery("shape", "0").indexedShapeIndex("test").indexedShapeRouting("ABC")) @@ -263,8 +263,8 @@ public void testIndexPolygonDateLine() throws Exception { String source = "{\n" + " \"shape\" : \"POLYGON((179 0, -179 0, -179 2, 179 2, 179 0))\"" + "}"; - indexRandom(true, client().prepareIndex("quad").setId("0").setSource(source, XContentType.JSON)); - indexRandom(true, client().prepareIndex("vector").setId("0").setSource(source, XContentType.JSON)); + indexRandom(true, client().prepareIndex("quad").setId("0").setSource(source, MediaTypeRegistry.JSON)); + indexRandom(true, client().prepareIndex("vector").setId("0").setSource(source, MediaTypeRegistry.JSON)); try { ClusterUpdateSettingsRequest updateSettingsRequest = new ClusterUpdateSettingsRequest(); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/geo/LegacyGeoShapeIntegrationIT.java b/server/src/internalClusterTest/java/org/opensearch/search/geo/LegacyGeoShapeIntegrationIT.java index 6332e2b94750d..1a40471ca2d51 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/geo/LegacyGeoShapeIntegrationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/geo/LegacyGeoShapeIntegrationIT.java @@ -39,9 +39,9 @@ import org.opensearch.cluster.routing.IndexShardRoutingTable; import org.opensearch.common.geo.builders.ShapeBuilder; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.geometry.Circle; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.LegacyGeoShapeFieldMapper; @@ -203,7 +203,7 @@ public void testIndexShapeRouting() throws Exception { + " }\n" + "}"; - indexRandom(true, client().prepareIndex("test").setId("0").setSource(source, XContentType.JSON).setRouting("ABC")); + indexRandom(true, client().prepareIndex("test").setId("0").setSource(source, MediaTypeRegistry.JSON).setRouting("ABC")); SearchResponse searchResponse = client().prepareSearch("test") .setQuery(geoShapeQuery("shape", "0").indexedShapeIndex("test").indexedShapeRouting("ABC")) diff --git a/server/src/internalClusterTest/java/org/opensearch/search/msearch/MultiSearchIT.java b/server/src/internalClusterTest/java/org/opensearch/search/msearch/MultiSearchIT.java index 8226663abf49e..9c2ddbba89903 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/msearch/MultiSearchIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/msearch/MultiSearchIT.java @@ -34,7 +34,7 @@ import org.opensearch.action.search.MultiSearchRequest; import org.opensearch.action.search.MultiSearchResponse; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.query.QueryBuilders; import org.opensearch.test.OpenSearchIntegTestCase; @@ -73,7 +73,7 @@ public void testSimpleMultiSearchMoreRequests() { createIndex("test"); int numDocs = randomIntBetween(0, 16); for (int i = 0; i < numDocs; i++) { - client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", XContentType.JSON).get(); + client().prepareIndex("test").setId(Integer.toString(i)).setSource("{}", MediaTypeRegistry.JSON).get(); } refresh(); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/nested/SimpleNestedIT.java b/server/src/internalClusterTest/java/org/opensearch/search/nested/SimpleNestedIT.java index bd67f5f83375e..b5ffb13918259 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/nested/SimpleNestedIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/nested/SimpleNestedIT.java @@ -45,9 +45,9 @@ import org.opensearch.action.search.SearchType; import org.opensearch.cluster.health.ClusterHealthStatus; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.query.QueryBuilders; import org.opensearch.search.sort.NestedSortBuilder; import org.opensearch.search.sort.SortBuilders; @@ -783,7 +783,7 @@ public void testNestedSortWithMultiLevelFiltering() throws Exception { + " }\n" + " ]\n" + "}", - XContentType.JSON + MediaTypeRegistry.JSON ) .get(); @@ -835,7 +835,7 @@ public void testNestedSortWithMultiLevelFiltering() throws Exception { + " }\n" + " ]\n" + "}", - XContentType.JSON + MediaTypeRegistry.JSON ) .get(); refresh(); @@ -987,7 +987,7 @@ public void testLeakingSortValues() throws Exception { + " }\n" + " ]\n" + "}", - XContentType.JSON + MediaTypeRegistry.JSON ) .get(); @@ -1006,7 +1006,7 @@ public void testLeakingSortValues() throws Exception { + " } \n" + " ]\n" + "}", - XContentType.JSON + MediaTypeRegistry.JSON ) .get(); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/preference/SearchPreferenceIT.java b/server/src/internalClusterTest/java/org/opensearch/search/preference/SearchPreferenceIT.java index 55a2a1fdde2b5..a5084ec2d2e2d 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/preference/SearchPreferenceIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/preference/SearchPreferenceIT.java @@ -42,8 +42,8 @@ import org.opensearch.cluster.routing.OperationRouting; import org.opensearch.cluster.routing.allocation.decider.EnableAllocationDecider; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.node.Node; import org.opensearch.core.rest.RestStatus; import org.opensearch.test.OpenSearchIntegTestCase; @@ -136,7 +136,7 @@ public void testNoPreferenceRandom() { } public void testSimplePreference() { - client().admin().indices().prepareCreate("test").setSettings("{\"number_of_replicas\": 1}", XContentType.JSON).get(); + client().admin().indices().prepareCreate("test").setSettings("{\"number_of_replicas\": 1}", MediaTypeRegistry.JSON).get(); ensureGreen(); client().prepareIndex("test").setSource("field1", "value1").get(); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/query/QueryStringIT.java b/server/src/internalClusterTest/java/org/opensearch/search/query/QueryStringIT.java index 36de3f7ebaa60..53a41af46790b 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/query/QueryStringIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/query/QueryStringIT.java @@ -36,8 +36,8 @@ import org.opensearch.action.index.IndexRequestBuilder; import org.opensearch.action.search.SearchResponse; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.MapperService; import org.opensearch.index.query.Operator; import org.opensearch.index.query.QueryStringQueryBuilder; @@ -76,7 +76,7 @@ public static void createRandomClusterSetting() { @Before public void setup() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - prepareCreate("test").setSource(indexBody, XContentType.JSON).get(); + prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON).get(); ensureGreen("test"); } @@ -161,7 +161,7 @@ public void testWithLotsOfTypes() throws Exception { public void testDocWithAllTypes() throws Exception { List reqs = new ArrayList<>(); String docBody = copyToStringFromClasspath("/org/opensearch/search/query/all-example-document.json"); - reqs.add(client().prepareIndex("test").setId("1").setSource(docBody, XContentType.JSON)); + reqs.add(client().prepareIndex("test").setId("1").setSource(docBody, MediaTypeRegistry.JSON)); indexRandom(true, false, reqs); SearchResponse resp = client().prepareSearch("test").setQuery(queryStringQuery("foo")).get(); @@ -253,7 +253,7 @@ public void testAllFields() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); Settings.Builder settings = Settings.builder().put("index.query.default_field", "*"); - prepareCreate("test_1").setSource(indexBody, XContentType.JSON).setSettings(settings).get(); + prepareCreate("test_1").setSource(indexBody, MediaTypeRegistry.JSON).setSettings(settings).get(); ensureGreen("test_1"); List reqs = new ArrayList<>(); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/query/SearchQueryIT.java b/server/src/internalClusterTest/java/org/opensearch/search/query/SearchQueryIT.java index 0e0f4873297ba..e8167471f074a 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/query/SearchQueryIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/query/SearchQueryIT.java @@ -50,9 +50,9 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.time.DateFormatter; import org.opensearch.common.unit.Fuzziness; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.analysis.CharFilterFactory; import org.opensearch.index.analysis.NormalizingCharFilterFactory; import org.opensearch.index.analysis.TokenizerFactory; @@ -1897,8 +1897,8 @@ public void testRangeQueryWithLocaleMapping() throws Exception { } public void testSearchEmptyDoc() { - assertAcked(prepareCreate("test").setSettings("{\"index.analysis.analyzer.default.type\":\"keyword\"}", XContentType.JSON)); - client().prepareIndex("test").setId("1").setSource("{}", XContentType.JSON).get(); + assertAcked(prepareCreate("test").setSettings("{\"index.analysis.analyzer.default.type\":\"keyword\"}", MediaTypeRegistry.JSON)); + client().prepareIndex("test").setId("1").setSource("{}", MediaTypeRegistry.JSON).get(); refresh(); assertHitCount(client().prepareSearch().setQuery(matchAllQuery()).get(), 1L); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/query/SimpleQueryStringIT.java b/server/src/internalClusterTest/java/org/opensearch/search/query/SimpleQueryStringIT.java index e2491600a9261..3e49186c4dda8 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/query/SimpleQueryStringIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/query/SimpleQueryStringIT.java @@ -42,9 +42,9 @@ import org.opensearch.action.search.SearchPhaseExecutionException; import org.opensearch.action.search.SearchResponse; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.analysis.PreConfiguredTokenFilter; import org.opensearch.index.mapper.MapperService; import org.opensearch.index.query.BoolQueryBuilder; @@ -441,7 +441,7 @@ public void testEmptySimpleQueryStringWithAnalysis() throws Exception { public void testBasicAllQuery() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - prepareCreate("test").setSource(indexBody, XContentType.JSON).get(); + prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON).get(); ensureGreen("test"); List reqs = new ArrayList<>(); @@ -465,7 +465,7 @@ public void testBasicAllQuery() throws Exception { public void testWithDate() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - prepareCreate("test").setSource(indexBody, XContentType.JSON).get(); + prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON).get(); ensureGreen("test"); List reqs = new ArrayList<>(); @@ -492,7 +492,7 @@ public void testWithDate() throws Exception { public void testWithLotsOfTypes() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - prepareCreate("test").setSource(indexBody, XContentType.JSON).get(); + prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON).get(); ensureGreen("test"); List reqs = new ArrayList<>(); @@ -523,12 +523,12 @@ public void testWithLotsOfTypes() throws Exception { public void testDocWithAllTypes() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - prepareCreate("test").setSource(indexBody, XContentType.JSON).get(); + prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON).get(); ensureGreen("test"); List reqs = new ArrayList<>(); String docBody = copyToStringFromClasspath("/org/opensearch/search/query/all-example-document.json"); - reqs.add(client().prepareIndex("test").setId("1").setSource(docBody, XContentType.JSON)); + reqs.add(client().prepareIndex("test").setId("1").setSource(docBody, MediaTypeRegistry.JSON)); indexRandom(true, false, reqs); SearchResponse resp = client().prepareSearch("test").setQuery(simpleQueryStringQuery("foo")).get(); @@ -568,7 +568,7 @@ public void testDocWithAllTypes() throws Exception { public void testKeywordWithWhitespace() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - prepareCreate("test").setSource(indexBody, XContentType.JSON).get(); + prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON).get(); ensureGreen("test"); List reqs = new ArrayList<>(); @@ -588,7 +588,7 @@ public void testKeywordWithWhitespace() throws Exception { public void testAllFieldsWithSpecifiedLeniency() throws IOException { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - prepareCreate("test").setSource(indexBody, XContentType.JSON).get(); + prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON).get(); ensureGreen("test"); SearchPhaseExecutionException e = expectThrows( @@ -635,7 +635,7 @@ private void doAssertLimitExceededException(String field, int exceedingFieldCoun public void testFieldAlias() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - assertAcked(prepareCreate("test").setSource(indexBody, XContentType.JSON)); + assertAcked(prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON)); ensureGreen("test"); List indexRequests = new ArrayList<>(); @@ -653,7 +653,7 @@ public void testFieldAlias() throws Exception { public void testFieldAliasWithWildcardField() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - assertAcked(prepareCreate("test").setSource(indexBody, XContentType.JSON)); + assertAcked(prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON)); ensureGreen("test"); List indexRequests = new ArrayList<>(); @@ -671,7 +671,7 @@ public void testFieldAliasWithWildcardField() throws Exception { public void testFieldAliasOnDisallowedFieldType() throws Exception { String indexBody = copyToStringFromClasspath("/org/opensearch/search/query/all-query-index.json"); - assertAcked(prepareCreate("test").setSource(indexBody, XContentType.JSON)); + assertAcked(prepareCreate("test").setSource(indexBody, MediaTypeRegistry.JSON)); ensureGreen("test"); List indexRequests = new ArrayList<>(); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/simple/SimpleSearchIT.java b/server/src/internalClusterTest/java/org/opensearch/search/simple/SimpleSearchIT.java index 5d7c6d5891b83..6e1b38792d635 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/simple/SimpleSearchIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/simple/SimpleSearchIT.java @@ -39,8 +39,8 @@ import org.opensearch.action.support.WriteRequest.RefreshPolicy; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentFactory; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.index.IndexSettings; import org.opensearch.index.mapper.MapperService; @@ -326,7 +326,7 @@ public void testSimpleIndexSortEarlyTerminate() throws Exception { public void testInsaneFromAndSize() throws Exception { createIndex("idx"); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertWindowFails(client().prepareSearch("idx").setFrom(Integer.MAX_VALUE)); assertWindowFails(client().prepareSearch("idx").setSize(Integer.MAX_VALUE)); @@ -334,7 +334,7 @@ public void testInsaneFromAndSize() throws Exception { public void testTooLargeFromAndSize() throws Exception { createIndex("idx"); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertWindowFails(client().prepareSearch("idx").setFrom(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY))); assertWindowFails(client().prepareSearch("idx").setSize(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY) + 1)); @@ -347,7 +347,7 @@ public void testTooLargeFromAndSize() throws Exception { public void testLargeFromAndSizeSucceeds() throws Exception { createIndex("idx"); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertHitCount(client().prepareSearch("idx").setFrom(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY) - 10).get(), 1); assertHitCount(client().prepareSearch("idx").setSize(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY)).get(), 1); @@ -365,7 +365,7 @@ public void testTooLargeFromAndSizeOkBySetting() throws Exception { Settings.builder() .put(IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey(), IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY) * 2) ).get(); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertHitCount(client().prepareSearch("idx").setFrom(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY)).get(), 1); assertHitCount(client().prepareSearch("idx").setSize(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY) + 1).get(), 1); @@ -393,7 +393,7 @@ public void testTooLargeFromAndSizeOkByDynamicSetting() throws Exception { ) .get() ); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertHitCount(client().prepareSearch("idx").setFrom(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY)).get(), 1); assertHitCount(client().prepareSearch("idx").setSize(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY) + 1).get(), 1); @@ -408,7 +408,7 @@ public void testTooLargeFromAndSizeOkByDynamicSetting() throws Exception { public void testTooLargeFromAndSizeBackwardsCompatibilityRecommendation() throws Exception { prepareCreate("idx").setSettings(Settings.builder().put(IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey(), Integer.MAX_VALUE)).get(); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertHitCount(client().prepareSearch("idx").setFrom(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY) * 10).get(), 1); assertHitCount(client().prepareSearch("idx").setSize(IndexSettings.MAX_RESULT_WINDOW_SETTING.get(Settings.EMPTY) * 10).get(), 1); @@ -423,7 +423,7 @@ public void testTooLargeFromAndSizeBackwardsCompatibilityRecommendation() throws public void testTooLargeRescoreWindow() throws Exception { createIndex("idx"); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertRescoreWindowFails(Integer.MAX_VALUE); assertRescoreWindowFails(IndexSettings.MAX_RESCORE_WINDOW_SETTING.get(Settings.EMPTY) + 1); @@ -433,7 +433,7 @@ public void testTooLargeRescoreOkBySetting() throws Exception { int defaultMaxWindow = IndexSettings.MAX_RESCORE_WINDOW_SETTING.get(Settings.EMPTY); prepareCreate("idx").setSettings(Settings.builder().put(IndexSettings.MAX_RESCORE_WINDOW_SETTING.getKey(), defaultMaxWindow * 2)) .get(); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertHitCount( client().prepareSearch("idx").addRescorer(new QueryRescorerBuilder(matchAllQuery()).windowSize(defaultMaxWindow + 1)).get(), @@ -450,7 +450,7 @@ public void testTooLargeRescoreOkByResultWindowSetting() throws Exception { defaultMaxWindow * 2 ) ).get(); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertHitCount( client().prepareSearch("idx").addRescorer(new QueryRescorerBuilder(matchAllQuery()).windowSize(defaultMaxWindow + 1)).get(), @@ -468,7 +468,7 @@ public void testTooLargeRescoreOkByDynamicSetting() throws Exception { .setSettings(Settings.builder().put(IndexSettings.MAX_RESCORE_WINDOW_SETTING.getKey(), defaultMaxWindow * 2)) .get() ); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertHitCount( client().prepareSearch("idx").addRescorer(new QueryRescorerBuilder(matchAllQuery()).windowSize(defaultMaxWindow + 1)).get(), @@ -489,7 +489,7 @@ public void testTooLargeRescoreOkByDynamicResultWindowSetting() throws Exception ) .get() ); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); assertHitCount( client().prepareSearch("idx").addRescorer(new QueryRescorerBuilder(matchAllQuery()).windowSize(defaultMaxWindow + 1)).get(), @@ -515,7 +515,7 @@ public void testTermQueryBigInt() throws Exception { client().prepareIndex("idx") .setId("1") - .setSource("{\"field\" : 80315953321748200608 }", XContentType.JSON) + .setSource("{\"field\" : 80315953321748200608 }", MediaTypeRegistry.JSON) .setRefreshPolicy(RefreshPolicy.IMMEDIATE) .get(); @@ -529,7 +529,7 @@ public void testTermQueryBigInt() throws Exception { public void testTooLongRegexInRegexpQuery() throws Exception { createIndex("idx"); - indexRandom(true, client().prepareIndex("idx").setSource("{}", XContentType.JSON)); + indexRandom(true, client().prepareIndex("idx").setSource("{}", MediaTypeRegistry.JSON)); int defaultMaxRegexLength = IndexSettings.MAX_REGEX_LENGTH_SETTING.get(Settings.EMPTY); StringBuilder regexp = new StringBuilder(defaultMaxRegexLength); diff --git a/server/src/internalClusterTest/java/org/opensearch/search/sort/FieldSortIT.java b/server/src/internalClusterTest/java/org/opensearch/search/sort/FieldSortIT.java index 83e732b39103e..69424954d6511 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/sort/FieldSortIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/sort/FieldSortIT.java @@ -46,9 +46,9 @@ import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.Numbers; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.fielddata.ScriptDocValues; import org.opensearch.index.query.QueryBuilders; import org.opensearch.index.query.functionscore.ScoreFunctionBuilders; @@ -145,7 +145,7 @@ public void testIssue8226() { assertAcked(prepareCreate("test_" + i).addAlias(new Alias("test"))); } if (i > 0) { - client().prepareIndex("test_" + i).setId("" + i).setSource("{\"entry\": " + i + "}", XContentType.JSON).get(); + client().prepareIndex("test_" + i).setId("" + i).setSource("{\"entry\": " + i + "}", MediaTypeRegistry.JSON).get(); } } refresh(); @@ -497,9 +497,9 @@ public void testScoreSortDirectionWithFunctionScore() throws Exception { public void testIssue2986() { assertAcked(client().admin().indices().prepareCreate("test").setMapping("field1", "type=keyword").get()); - client().prepareIndex("test").setId("1").setSource("{\"field1\":\"value1\"}", XContentType.JSON).get(); - client().prepareIndex("test").setId("2").setSource("{\"field1\":\"value2\"}", XContentType.JSON).get(); - client().prepareIndex("test").setId("3").setSource("{\"field1\":\"value3\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{\"field1\":\"value1\"}", MediaTypeRegistry.JSON).get(); + client().prepareIndex("test").setId("2").setSource("{\"field1\":\"value2\"}", MediaTypeRegistry.JSON).get(); + client().prepareIndex("test").setId("3").setSource("{\"field1\":\"value3\"}", MediaTypeRegistry.JSON).get(); refresh(); SearchResponse result = client().prepareSearch("test") .setQuery(matchAllQuery()) @@ -2259,7 +2259,7 @@ public void testLongSortOptimizationCorrectResults() { bulkBuilder = client().prepareBulk(); } String source = "{\"long_field\":" + randomLong() + "}"; - bulkBuilder.add(client().prepareIndex("test1").setId(Integer.toString(i)).setSource(source, XContentType.JSON)); + bulkBuilder.add(client().prepareIndex("test1").setId(Integer.toString(i)).setSource(source, MediaTypeRegistry.JSON)); } refresh(); diff --git a/server/src/internalClusterTest/java/org/opensearch/snapshots/SnapshotCustomPluginStateIT.java b/server/src/internalClusterTest/java/org/opensearch/snapshots/SnapshotCustomPluginStateIT.java index 85fedead80a85..eae7a92bf304e 100644 --- a/server/src/internalClusterTest/java/org/opensearch/snapshots/SnapshotCustomPluginStateIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/snapshots/SnapshotCustomPluginStateIT.java @@ -43,7 +43,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.ingest.IngestTestPlugin; import org.opensearch.plugins.Plugin; import org.opensearch.script.MockScriptEngine; @@ -115,7 +115,7 @@ public void testIncludeGlobalState() throws Exception { .endArray() .endObject() ); - assertAcked(clusterAdmin().preparePutPipeline("barbaz", pipelineSource, XContentType.JSON).get()); + assertAcked(clusterAdmin().preparePutPipeline("barbaz", pipelineSource, MediaTypeRegistry.JSON).get()); } if (testScript) { @@ -125,7 +125,7 @@ public void testIncludeGlobalState() throws Exception { .setId("foobar") .setContent( new BytesArray("{\"script\": { \"lang\": \"" + MockScriptEngine.NAME + "\", \"source\": \"1\"} }"), - XContentType.JSON + MediaTypeRegistry.JSON ) ); } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/health/ClusterHealthResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/health/ClusterHealthResponse.java index 019a1e1417510..f5bfa5b256069 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/health/ClusterHealthResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/health/ClusterHealthResponse.java @@ -45,9 +45,9 @@ import org.opensearch.common.settings.ClusterSettings; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.xcontent.StatusToXContentObject; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -421,7 +421,7 @@ public void writeTo(StreamOutput out) throws IOException { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/cancel/CancelTasksResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/cancel/CancelTasksResponse.java index f2ebde642d2be..979489999cc6e 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/cancel/CancelTasksResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/cancel/CancelTasksResponse.java @@ -37,8 +37,8 @@ import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse; import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.tasks.TaskInfo; @@ -81,6 +81,6 @@ public static CancelTasksResponse fromXContent(XContentParser parser) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/get/GetTaskResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/get/GetTaskResponse.java index 36bec88109cf1..96fb65a9a1391 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/get/GetTaskResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/get/GetTaskResponse.java @@ -36,7 +36,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.tasks.TaskResult; @@ -85,6 +85,6 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/list/ListTasksResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/list/ListTasksResponse.java index 1e2e432882623..99b4d3dd006c8 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/list/ListTasksResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/node/tasks/list/ListTasksResponse.java @@ -43,8 +43,8 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -262,6 +262,6 @@ public static ListTasksResponse fromXContent(XContentParser parser) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/remotestore/restore/RestoreRemoteStoreRequest.java b/server/src/main/java/org/opensearch/action/admin/cluster/remotestore/restore/RestoreRemoteStoreRequest.java index fd29c324d51a1..e2dfba791f752 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/remotestore/restore/RestoreRemoteStoreRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/remotestore/restore/RestoreRemoteStoreRequest.java @@ -13,8 +13,8 @@ import org.opensearch.action.support.clustermanager.ClusterManagerNodeRequest; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -205,7 +205,7 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/remotestore/stats/RemoteStoreStatsResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/remotestore/stats/RemoteStoreStatsResponse.java index 4f0832816fd8a..91dd0483f2df5 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/remotestore/stats/RemoteStoreStatsResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/remotestore/stats/RemoteStoreStatsResponse.java @@ -13,7 +13,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import java.io.IOException; @@ -89,7 +89,7 @@ protected void addCustomXContentFields(XContentBuilder builder, Params params) t @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, false); + return Strings.toString(MediaTypeRegistry.JSON, this, true, false); } static final class Fields { diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/repositories/put/PutRepositoryRequest.java b/server/src/main/java/org/opensearch/action/admin/cluster/repositories/put/PutRepositoryRequest.java index b001e9456e78c..c8ebcb6e6fcd3 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/repositories/put/PutRepositoryRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/repositories/put/PutRepositoryRequest.java @@ -37,9 +37,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.Map; @@ -164,11 +164,11 @@ public PutRepositoryRequest settings(Settings.Builder settings) { * Sets the repository settings. * * @param source repository settings in json or yaml format - * @param xContentType the content type of the source + * @param mediaType the content type of the source * @return this request */ - public PutRepositoryRequest settings(String source, XContentType xContentType) { - this.settings = Settings.builder().loadFromSource(source, xContentType).build(); + public PutRepositoryRequest settings(String source, final MediaType mediaType) { + this.settings = Settings.builder().loadFromSource(source, mediaType).build(); return this; } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/repositories/verify/VerifyRepositoryResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/repositories/verify/VerifyRepositoryResponse.java index 9a97b67e1c2b7..f01854fc5d29d 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/repositories/verify/VerifyRepositoryResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/repositories/verify/VerifyRepositoryResponse.java @@ -39,7 +39,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -196,7 +196,7 @@ public static VerifyRepositoryResponse fromXContent(XContentParser parser) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterGetSettingsResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterGetSettingsResponse.java index 9a8206a4cfdba..521ba824e6e57 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterGetSettingsResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterGetSettingsResponse.java @@ -38,11 +38,11 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.settings.Settings; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.action.admin.cluster.state.ClusterStateResponse; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.Objects; @@ -176,7 +176,7 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java b/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java index aaa89ee269fd8..628d6e972f82c 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsRequest.java @@ -38,11 +38,11 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.Map; @@ -120,8 +120,8 @@ public ClusterUpdateSettingsRequest transientSettings(Settings.Builder settings) /** * Sets the source containing the transient settings to be updated. They will not survive a full cluster restart */ - public ClusterUpdateSettingsRequest transientSettings(String source, XContentType xContentType) { - this.transientSettings = Settings.builder().loadFromSource(source, xContentType).build(); + public ClusterUpdateSettingsRequest transientSettings(String source, final MediaType mediaType) { + this.transientSettings = Settings.builder().loadFromSource(source, mediaType).build(); return this; } @@ -152,8 +152,8 @@ public ClusterUpdateSettingsRequest persistentSettings(Settings.Builder settings /** * Sets the source containing the persistent settings to be updated. They will get applied cross restarts */ - public ClusterUpdateSettingsRequest persistentSettings(String source, XContentType xContentType) { - this.persistentSettings = Settings.builder().loadFromSource(source, xContentType).build(); + public ClusterUpdateSettingsRequest persistentSettings(String source, final MediaType mediaType) { + this.persistentSettings = Settings.builder().loadFromSource(source, mediaType).build(); return this; } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/clone/CloneSnapshotRequest.java b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/clone/CloneSnapshotRequest.java index 5729386259df1..694b13e37bb03 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/clone/CloneSnapshotRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/clone/CloneSnapshotRequest.java @@ -39,7 +39,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -187,6 +187,6 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/create/CreateSnapshotRequest.java b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/create/CreateSnapshotRequest.java index 9736d99b9f886..cb6136b84ba18 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/create/CreateSnapshotRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/create/CreateSnapshotRequest.java @@ -48,7 +48,6 @@ import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.Arrays; @@ -388,7 +387,7 @@ public CreateSnapshotRequest settings(String source, MediaType mediaType) { */ public CreateSnapshotRequest settings(Map source) { try { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.map(source); settings(builder.toString(), builder.contentType()); } catch (IOException e) { diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/get/GetSnapshotsResponse.java b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/get/GetSnapshotsResponse.java index b8b4d972c95f7..12f441960ccaf 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/get/GetSnapshotsResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/get/GetSnapshotsResponse.java @@ -36,9 +36,9 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -128,6 +128,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequest.java b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequest.java index 0f9aa65afe3c2..767b68bc4ac52 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequest.java @@ -43,6 +43,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.util.FeatureFlags; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentType; @@ -749,6 +750,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/status/SnapshotStats.java b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/status/SnapshotStats.java index c7690ea0d7817..6289dc95484cc 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/status/SnapshotStats.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/status/SnapshotStats.java @@ -38,12 +38,12 @@ import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.xcontent.XContentParserUtils; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; @@ -357,7 +357,7 @@ void add(SnapshotStats stats, boolean updateTimestamps) { time = endTime - startTime; } assert time >= 0 : "Update with [" - + Strings.toString(XContentType.JSON, stats) + + Strings.toString(MediaTypeRegistry.JSON, stats) + "][" + updateTimestamps + "] resulted in negative total time [" diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/status/SnapshotStatus.java b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/status/SnapshotStatus.java index d1e25c1f1bdc4..5f2afa24c4ab7 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/status/SnapshotStatus.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/snapshots/status/SnapshotStatus.java @@ -39,9 +39,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -206,7 +206,7 @@ public void writeTo(StreamOutput out) throws IOException { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, false); + return Strings.toString(MediaTypeRegistry.JSON, this, true, false); } /** diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/stats/AnalysisStats.java b/server/src/main/java/org/opensearch/action/admin/cluster/stats/AnalysisStats.java index 84b093f9bb238..9190cae4c49d8 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/stats/AnalysisStats.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/stats/AnalysisStats.java @@ -40,7 +40,7 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; @@ -347,6 +347,6 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/stats/MappingStats.java b/server/src/main/java/org/opensearch/action/admin/cluster/stats/MappingStats.java index 66d1fc6a52295..64218765a57e6 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/stats/MappingStats.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/stats/MappingStats.java @@ -39,7 +39,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; @@ -131,7 +131,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } @Override diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequest.java b/server/src/main/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequest.java index 8b328bc3879dd..bbbec60036b0b 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequest.java @@ -140,10 +140,10 @@ public StoredScriptSource source() { /** * Set the script source and the content type of the bytes. */ - public PutStoredScriptRequest content(BytesReference content, XContentType xContentType) { + public PutStoredScriptRequest content(BytesReference content, MediaType mediaType) { this.content = content; - this.mediaType = Objects.requireNonNull(xContentType); - this.source = StoredScriptSource.parse(content, xContentType); + this.mediaType = Objects.requireNonNull(mediaType); + this.source = StoredScriptSource.parse(content, mediaType); return this; } diff --git a/server/src/main/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequestBuilder.java b/server/src/main/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequestBuilder.java index ed46b12d96106..2a06cd23c10b6 100644 --- a/server/src/main/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequestBuilder.java +++ b/server/src/main/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequestBuilder.java @@ -36,7 +36,7 @@ import org.opensearch.action.support.master.AcknowledgedResponse; import org.opensearch.client.OpenSearchClient; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaType; /** * Transport request builder for putting stored script @@ -60,8 +60,8 @@ public PutStoredScriptRequestBuilder setId(String id) { /** * Set the source of the script along with the content type of the source */ - public PutStoredScriptRequestBuilder setContent(BytesReference source, XContentType xContentType) { - request.content(source, xContentType); + public PutStoredScriptRequestBuilder setContent(BytesReference source, MediaType mediaType) { + request.content(source, mediaType); return this; } } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/alias/IndicesAliasesRequest.java b/server/src/main/java/org/opensearch/action/admin/indices/alias/IndicesAliasesRequest.java index cd99a1067a8a4..5e011409e8f9c 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/alias/IndicesAliasesRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/alias/IndicesAliasesRequest.java @@ -45,7 +45,6 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.ConstructingObjectParser; import org.opensearch.core.xcontent.MediaTypeRegistry; @@ -429,7 +428,7 @@ public AliasActions filter(Map filter) { return this; } try { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder(); builder.map(filter); this.filter = builder.toString(); return this; @@ -533,7 +532,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws } if (false == Strings.isEmpty(filter)) { try (InputStream stream = new BytesArray(filter).streamInput()) { - builder.rawField(FILTER.getPreferredName(), stream, XContentType.JSON); + builder.rawField(FILTER.getPreferredName(), stream, MediaTypeRegistry.JSON); } } if (false == Strings.isEmpty(routing)) { diff --git a/server/src/main/java/org/opensearch/action/admin/indices/analyze/AnalyzeAction.java b/server/src/main/java/org/opensearch/action/admin/indices/analyze/AnalyzeAction.java index 00144eedc438f..b4499f9cd71f8 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/analyze/AnalyzeAction.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/analyze/AnalyzeAction.java @@ -40,8 +40,8 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.ToXContentObject; @@ -386,7 +386,7 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } /** diff --git a/server/src/main/java/org/opensearch/action/admin/indices/close/CloseIndexResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/close/CloseIndexResponse.java index c069cd17b8c51..8a6210defeb66 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/close/CloseIndexResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/close/CloseIndexResponse.java @@ -40,7 +40,7 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.common.util.CollectionUtils; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.index.Index; @@ -93,7 +93,7 @@ protected void addCustomFields(final XContentBuilder builder, final Params param @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** @@ -192,7 +192,7 @@ public XContentBuilder toXContent(final XContentBuilder builder, final Params pa @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } @@ -251,7 +251,7 @@ public XContentBuilder toXContent(final XContentBuilder builder, final Params pa @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** @@ -297,7 +297,7 @@ public XContentBuilder innerToXContent(final XContentBuilder builder, final Para @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } static Failure readFailure(final StreamInput in) throws IOException { diff --git a/server/src/main/java/org/opensearch/action/admin/indices/create/CreateIndexRequest.java b/server/src/main/java/org/opensearch/action/admin/indices/create/CreateIndexRequest.java index 001b466fc47e5..1ea76ff055fac 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/create/CreateIndexRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/create/CreateIndexRequest.java @@ -220,7 +220,7 @@ public CreateIndexRequest settings(String source, XContentType xContentType) { /** * The settings to create the index with (using a generic MediaType) */ - private CreateIndexRequest settings(String source, MediaType mediaType) { + public CreateIndexRequest settings(String source, MediaType mediaType) { this.settings = Settings.builder().loadFromSource(source, mediaType).build(); return this; } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilder.java b/server/src/main/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilder.java index 27f20f028ea74..aff56905ddadb 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilder.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilder.java @@ -98,8 +98,8 @@ public CreateIndexRequestBuilder setSettings(XContentBuilder builder) { /** * The settings to create the index with (either json or yaml format) */ - public CreateIndexRequestBuilder setSettings(String source, XContentType xContentType) { - request.settings(source, xContentType); + public CreateIndexRequestBuilder setSettings(String source, MediaType mediaType) { + request.settings(source, mediaType); return this; } @@ -209,16 +209,16 @@ public CreateIndexRequestBuilder setSource(String source, MediaType mediaType) { /** * Sets the settings and mappings as a single source. */ - public CreateIndexRequestBuilder setSource(BytesReference source, XContentType xContentType) { - request.source(source, xContentType); + public CreateIndexRequestBuilder setSource(BytesReference source, MediaType mediaType) { + request.source(source, mediaType); return this; } /** * Sets the settings and mappings as a single source. */ - public CreateIndexRequestBuilder setSource(byte[] source, XContentType xContentType) { - request.source(source, xContentType); + public CreateIndexRequestBuilder setSource(byte[] source, MediaType mediaType) { + request.source(source, mediaType); return this; } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/get/GetIndexResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/get/GetIndexResponse.java index b0fc6856eb43c..edfc7b1bf4fc9 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/get/GetIndexResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/get/GetIndexResponse.java @@ -40,7 +40,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.index.mapper.MapperService; @@ -328,7 +328,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/GetFieldMappingsResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/GetFieldMappingsResponse.java index a06121b1d448d..2c6e1814f57d3 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/GetFieldMappingsResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/GetFieldMappingsResponse.java @@ -39,13 +39,13 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.Mapper; import org.opensearch.index.mapper.MapperService; @@ -214,7 +214,7 @@ public String fullName() { /** Returns the mappings as a map. Note that the returned map has a single key which is always the field's {@link Mapper#name}. */ public Map sourceAsMap() { - return XContentHelper.convertToMap(source, true, XContentType.JSON).v2(); + return XContentHelper.convertToMap(source, true, MediaTypeRegistry.JSON).v2(); } // pkg-private for testing @@ -233,7 +233,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws builder.field("mapping", sourceAsMap()); } else { try (InputStream stream = source.streamInput()) { - builder.rawField(MAPPING.getPreferredName(), stream, XContentType.JSON); + builder.rawField(MAPPING.getPreferredName(), stream, MediaTypeRegistry.JSON); } } return builder; diff --git a/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/GetMappingsResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/GetMappingsResponse.java index 6b3fff19d532f..e5ac85b713ed9 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/GetMappingsResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/GetMappingsResponse.java @@ -38,8 +38,8 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.index.mapper.MapperService; @@ -132,7 +132,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/TransportGetFieldMappingsIndexAction.java b/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/TransportGetFieldMappingsIndexAction.java index 435034c77b921..40becceef53dd 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/TransportGetFieldMappingsIndexAction.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/mapping/get/TransportGetFieldMappingsIndexAction.java @@ -46,9 +46,9 @@ import org.opensearch.common.inject.Inject; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.regex.Regex; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; -import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.XContentHelper; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.MappingLookup; import org.opensearch.index.mapper.DocumentMapper; @@ -220,7 +220,7 @@ private static void addFieldMapper( try { BytesReference bytes = XContentHelper.toXContent( fieldMapper, - XContentType.JSON, + MediaTypeRegistry.JSON, includeDefaults ? includeDefaultsParams : ToXContent.EMPTY_PARAMS, false ); diff --git a/server/src/main/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequest.java b/server/src/main/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequest.java index 373331eb1554b..5c8bcbb1e92a7 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequest.java @@ -46,7 +46,6 @@ import org.opensearch.core.common.util.CollectionUtils; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.MediaTypeRegistry; @@ -299,7 +298,7 @@ public PutMappingRequest source(XContentBuilder mappingBuilder) { */ public PutMappingRequest source(Map mappingSource) { try { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.map(mappingSource); return source(BytesReference.bytes(builder), builder.contentType()); } catch (IOException e) { @@ -310,8 +309,8 @@ public PutMappingRequest source(Map mappingSource) { /** * The mapping source definition. */ - public PutMappingRequest source(String mappingSource, XContentType xContentType) { - return source(new BytesArray(mappingSource), xContentType); + public PutMappingRequest source(String mappingSource, MediaType mediaType) { + return source(new BytesArray(mappingSource), mediaType); } /** @@ -354,7 +353,7 @@ public void writeTo(StreamOutput out) throws IOException { public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { if (source != null) { try (InputStream stream = new BytesArray(source).streamInput()) { - builder.rawValue(stream, XContentType.JSON); + builder.rawValue(stream, MediaTypeRegistry.JSON); } } else { builder.startObject().endObject(); diff --git a/server/src/main/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequestBuilder.java b/server/src/main/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequestBuilder.java index a1300b5859ce5..5b0e74eb1f435 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequestBuilder.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequestBuilder.java @@ -36,8 +36,8 @@ import org.opensearch.action.support.master.AcknowledgedRequestBuilder; import org.opensearch.action.support.master.AcknowledgedResponse; import org.opensearch.client.OpenSearchClient; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.Index; import java.util.Map; @@ -95,8 +95,8 @@ public PutMappingRequestBuilder setSource(Map mappingSource) { /** * The mapping source definition. */ - public PutMappingRequestBuilder setSource(String mappingSource, XContentType xContentType) { - request.source(mappingSource, xContentType); + public PutMappingRequestBuilder setSource(String mappingSource, MediaType mediaType) { + request.source(mappingSource, mediaType); return this; } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/readonly/AddIndexBlockResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/readonly/AddIndexBlockResponse.java index 42dacfdb3ca2d..ce08997de443f 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/readonly/AddIndexBlockResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/readonly/AddIndexBlockResponse.java @@ -40,7 +40,7 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.common.util.CollectionUtils; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.index.Index; @@ -93,7 +93,7 @@ protected void addCustomFields(final XContentBuilder builder, final Params param @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** @@ -192,7 +192,7 @@ public XContentBuilder toXContent(final XContentBuilder builder, final Params pa @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } @@ -252,7 +252,7 @@ public XContentBuilder toXContent(final XContentBuilder builder, final Params pa @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** @@ -298,7 +298,7 @@ public XContentBuilder innerToXContent(final XContentBuilder builder, final Para @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } static Failure readFailure(final StreamInput in) throws IOException { diff --git a/server/src/main/java/org/opensearch/action/admin/indices/recovery/RecoveryResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/recovery/RecoveryResponse.java index a7015a9d580df..4fc8788711f73 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/recovery/RecoveryResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/recovery/RecoveryResponse.java @@ -37,7 +37,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.indices.recovery.RecoveryState; @@ -120,6 +120,6 @@ public void writeTo(StreamOutput out) throws IOException { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/replication/SegmentReplicationStatsResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/replication/SegmentReplicationStatsResponse.java index 99ff501c1eed8..bf0eb54e6c519 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/replication/SegmentReplicationStatsResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/replication/SegmentReplicationStatsResponse.java @@ -13,7 +13,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.index.SegmentReplicationPerGroupStats; @@ -91,6 +91,6 @@ public void writeTo(StreamOutput out) throws IOException { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/rollover/RolloverInfo.java b/server/src/main/java/org/opensearch/action/admin/indices/rollover/RolloverInfo.java index 8503c9b882c93..a4d4644fd12c0 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/rollover/RolloverInfo.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/rollover/RolloverInfo.java @@ -38,9 +38,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -149,6 +149,6 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/settings/put/UpdateSettingsRequest.java b/server/src/main/java/org/opensearch/action/admin/indices/settings/put/UpdateSettingsRequest.java index 3c12f3eb8b728..707429f65fe42 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/settings/put/UpdateSettingsRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/settings/put/UpdateSettingsRequest.java @@ -40,10 +40,11 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.Arrays; @@ -157,8 +158,8 @@ public UpdateSettingsRequest settings(Settings.Builder settings) { /** * Sets the settings to be updated (either json or yaml format) */ - public UpdateSettingsRequest settings(String source, XContentType xContentType) { - this.settings = Settings.builder().loadFromSource(source, xContentType).build(); + public UpdateSettingsRequest settings(String source, MediaType mediaType) { + this.settings = Settings.builder().loadFromSource(source, mediaType).build(); return this; } @@ -221,7 +222,7 @@ public UpdateSettingsRequest fromXContent(XContentParser parser) throws IOExcept @Override public String toString() { - return "indices : " + Arrays.toString(indices) + "," + Strings.toString(XContentType.JSON, this); + return "indices : " + Arrays.toString(indices) + "," + Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/action/admin/indices/stats/IndicesStatsResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/stats/IndicesStatsResponse.java index b262835dc2f2a..8ba924f28f08c 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/stats/IndicesStatsResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/stats/IndicesStatsResponse.java @@ -39,7 +39,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.index.Index; @@ -226,6 +226,6 @@ static final class Fields { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, false); + return Strings.toString(MediaTypeRegistry.JSON, this, true, false); } } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/template/put/PutIndexTemplateRequest.java b/server/src/main/java/org/opensearch/action/admin/indices/template/put/PutIndexTemplateRequest.java index 011f10bfaf6d6..ccb6efe332f45 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/template/put/PutIndexTemplateRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/template/put/PutIndexTemplateRequest.java @@ -225,8 +225,8 @@ public PutIndexTemplateRequest settings(Settings.Builder settings) { /** * The settings to create the index template with (either json/yaml format). */ - public PutIndexTemplateRequest settings(String source, XContentType xContentType) { - this.settings = Settings.builder().loadFromSource(source, xContentType).build(); + public PutIndexTemplateRequest settings(String source, MediaType mediaType) { + this.settings = Settings.builder().loadFromSource(source, mediaType).build(); return this; } @@ -397,15 +397,15 @@ public PutIndexTemplateRequest source(String templateSource, XContentType xConte /** * The template source definition. */ - public PutIndexTemplateRequest source(byte[] source, XContentType xContentType) { - return source(source, 0, source.length, xContentType); + public PutIndexTemplateRequest source(byte[] source, MediaType mediaType) { + return source(source, 0, source.length, mediaType); } /** * The template source definition. */ - public PutIndexTemplateRequest source(byte[] source, int offset, int length, XContentType xContentType) { - return source(new BytesArray(source, offset, length), xContentType); + public PutIndexTemplateRequest source(byte[] source, int offset, int length, MediaType mediaType) { + return source(new BytesArray(source, offset, length), mediaType); } /** diff --git a/server/src/main/java/org/opensearch/action/admin/indices/template/put/PutIndexTemplateRequestBuilder.java b/server/src/main/java/org/opensearch/action/admin/indices/template/put/PutIndexTemplateRequestBuilder.java index eae2f9d9c94e0..65df611983caf 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/template/put/PutIndexTemplateRequestBuilder.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/template/put/PutIndexTemplateRequestBuilder.java @@ -37,6 +37,7 @@ import org.opensearch.client.OpenSearchClient; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentType; @@ -113,8 +114,8 @@ public PutIndexTemplateRequestBuilder setSettings(Settings.Builder settings) { /** * The settings to crete the index template with (either json or yaml format) */ - public PutIndexTemplateRequestBuilder setSettings(String source, XContentType xContentType) { - request.settings(source, xContentType); + public PutIndexTemplateRequestBuilder setSettings(String source, MediaType mediaType) { + request.settings(source, mediaType); return this; } @@ -130,10 +131,10 @@ public PutIndexTemplateRequestBuilder setSettings(Map source) { * Adds mapping that will be added when the index template gets created. * * @param source The mapping source - * @param xContentType The type/format of the source + * @param mediaType The type/format of the source */ - public PutIndexTemplateRequestBuilder setMapping(String source, XContentType xContentType) { - request.mapping(source, xContentType); + public PutIndexTemplateRequestBuilder setMapping(String source, MediaType mediaType) { + request.mapping(source, mediaType); return this; } @@ -226,16 +227,16 @@ public PutIndexTemplateRequestBuilder setSource(Map templateSour /** * The template source definition. */ - public PutIndexTemplateRequestBuilder setSource(BytesReference templateSource, XContentType xContentType) { - request.source(templateSource, xContentType); + public PutIndexTemplateRequestBuilder setSource(BytesReference templateSource, MediaType mediaType) { + request.source(templateSource, mediaType); return this; } /** * The template source definition. */ - public PutIndexTemplateRequestBuilder setSource(byte[] templateSource, XContentType xContentType) { - request.source(templateSource, xContentType); + public PutIndexTemplateRequestBuilder setSource(byte[] templateSource, MediaType mediaType) { + request.source(templateSource, mediaType); return this; } diff --git a/server/src/main/java/org/opensearch/action/bulk/BulkItemRequest.java b/server/src/main/java/org/opensearch/action/bulk/BulkItemRequest.java index bbf887b71cbb2..c0e0a5d8532b6 100644 --- a/server/src/main/java/org/opensearch/action/bulk/BulkItemRequest.java +++ b/server/src/main/java/org/opensearch/action/bulk/BulkItemRequest.java @@ -40,8 +40,8 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.shard.ShardId; +import org.opensearch.core.xcontent.MediaTypeRegistry; import java.io.IOException; import java.util.Objects; @@ -114,7 +114,7 @@ public void abort(String index, Exception cause) { setPrimaryResponse(new BulkItemResponse(id, request.opType(), failure)); } else { assert primaryResponse.isFailed() && primaryResponse.getFailure().isAborted() : "response [" - + Strings.toString(XContentType.JSON, primaryResponse) + + Strings.toString(MediaTypeRegistry.JSON, primaryResponse) + "]; cause [" + cause + "]"; diff --git a/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java b/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java index 08a8e7b6d7865..c6228d7ec854e 100644 --- a/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java +++ b/server/src/main/java/org/opensearch/action/bulk/BulkItemResponse.java @@ -46,9 +46,9 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.xcontent.StatusToXContentObject; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -368,7 +368,7 @@ public static Failure fromXContent(XContentParser parser) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/bulk/BulkProcessor.java b/server/src/main/java/org/opensearch/action/bulk/BulkProcessor.java index a01fc82fffd01..e99d09de89b74 100644 --- a/server/src/main/java/org/opensearch/action/bulk/BulkProcessor.java +++ b/server/src/main/java/org/opensearch/action/bulk/BulkProcessor.java @@ -45,6 +45,7 @@ import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.threadpool.Scheduler; import org.opensearch.threadpool.ThreadPool; @@ -457,17 +458,13 @@ public BulkProcessor add(BytesReference data, @Nullable String defaultIndex, XCo /** * Adds the data from the bytes to be processed by the bulk processor */ - public BulkProcessor add( - BytesReference data, - @Nullable String defaultIndex, - @Nullable String defaultPipeline, - XContentType xContentType - ) throws Exception { + public BulkProcessor add(BytesReference data, @Nullable String defaultIndex, @Nullable String defaultPipeline, MediaType mediaType) + throws Exception { Tuple bulkRequestToExecute = null; lock.lock(); try { ensureOpen(); - bulkRequest.add(data, defaultIndex, null, null, defaultPipeline, null, true, xContentType); + bulkRequest.add(data, defaultIndex, null, null, defaultPipeline, null, true, mediaType); bulkRequestToExecute = newBulkRequestIfNeeded(); } finally { lock.unlock(); diff --git a/server/src/main/java/org/opensearch/action/bulk/BulkRequestParser.java b/server/src/main/java/org/opensearch/action/bulk/BulkRequestParser.java index 3a86ccd578991..481638028b95d 100644 --- a/server/src/main/java/org/opensearch/action/bulk/BulkRequestParser.java +++ b/server/src/main/java/org/opensearch/action/bulk/BulkRequestParser.java @@ -43,6 +43,7 @@ import org.opensearch.common.lucene.uid.Versions; import org.opensearch.common.xcontent.LoggingDeprecationHandler; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContent; import org.opensearch.core.xcontent.XContentParser; @@ -105,7 +106,7 @@ private static BytesReference sliceTrimmingCarriageReturn( MediaType mediaType ) { final int length; - if (XContentType.JSON == mediaType && bytesReference.get(nextMarker - 1) == (byte) '\r') { + if (MediaTypeRegistry.JSON == mediaType && bytesReference.get(nextMarker - 1) == (byte) '\r') { length = nextMarker - from - 1; } else { length = nextMarker - from; diff --git a/server/src/main/java/org/opensearch/action/fieldcaps/FieldCapabilities.java b/server/src/main/java/org/opensearch/action/fieldcaps/FieldCapabilities.java index c4298e75f8302..3a5b687f19dac 100644 --- a/server/src/main/java/org/opensearch/action/fieldcaps/FieldCapabilities.java +++ b/server/src/main/java/org/opensearch/action/fieldcaps/FieldCapabilities.java @@ -36,9 +36,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -289,7 +289,7 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** diff --git a/server/src/main/java/org/opensearch/action/fieldcaps/FieldCapabilitiesResponse.java b/server/src/main/java/org/opensearch/action/fieldcaps/FieldCapabilitiesResponse.java index 5b14a0d5a40b4..641cb4ae20e3e 100644 --- a/server/src/main/java/org/opensearch/action/fieldcaps/FieldCapabilitiesResponse.java +++ b/server/src/main/java/org/opensearch/action/fieldcaps/FieldCapabilitiesResponse.java @@ -39,11 +39,11 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.xcontent.XContentParserUtils; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.Arrays; @@ -213,6 +213,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/get/GetResponse.java b/server/src/main/java/org/opensearch/action/get/GetResponse.java index abb1ddfe041c9..c3ae5d9cf2007 100644 --- a/server/src/main/java/org/opensearch/action/get/GetResponse.java +++ b/server/src/main/java/org/opensearch/action/get/GetResponse.java @@ -40,7 +40,7 @@ import org.opensearch.common.document.DocumentField; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -238,6 +238,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/get/MultiGetRequest.java b/server/src/main/java/org/opensearch/action/get/MultiGetRequest.java index 3a28b123b6539..5549d44c1e7ac 100644 --- a/server/src/main/java/org/opensearch/action/get/MultiGetRequest.java +++ b/server/src/main/java/org/opensearch/action/get/MultiGetRequest.java @@ -48,8 +48,8 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.lucene.uid.Versions; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -261,7 +261,7 @@ public int hashCode() { } public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/action/index/IndexRequestBuilder.java b/server/src/main/java/org/opensearch/action/index/IndexRequestBuilder.java index ca25409556398..4bf7634dcb7e1 100644 --- a/server/src/main/java/org/opensearch/action/index/IndexRequestBuilder.java +++ b/server/src/main/java/org/opensearch/action/index/IndexRequestBuilder.java @@ -38,8 +38,8 @@ import org.opensearch.client.OpenSearchClient; import org.opensearch.common.Nullable; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.VersionType; import java.util.Map; @@ -82,8 +82,8 @@ public IndexRequestBuilder setRouting(String routing) { /** * Sets the source. */ - public IndexRequestBuilder setSource(BytesReference source, XContentType xContentType) { - request.source(source, xContentType); + public IndexRequestBuilder setSource(BytesReference source, MediaType mediaType) { + request.source(source, mediaType); return this; } @@ -102,7 +102,7 @@ public IndexRequestBuilder setSource(Map source) { * * @param source The map to index */ - public IndexRequestBuilder setSource(Map source, XContentType contentType) { + public IndexRequestBuilder setSource(Map source, MediaType contentType) { request.source(source, contentType); return this; } @@ -111,10 +111,10 @@ public IndexRequestBuilder setSource(Map source, XContentType content * Sets the document source to index. *

* Note, its preferable to either set it using {@link #setSource(XContentBuilder)} - * or using the {@link #setSource(byte[], XContentType)}. + * or using the {@link #setSource(byte[], MediaType)}. */ - public IndexRequestBuilder setSource(String source, XContentType xContentType) { - request.source(source, xContentType); + public IndexRequestBuilder setSource(String source, MediaType mediaType) { + request.source(source, mediaType); return this; } @@ -129,8 +129,8 @@ public IndexRequestBuilder setSource(XContentBuilder sourceBuilder) { /** * Sets the document to index in bytes form. */ - public IndexRequestBuilder setSource(byte[] source, XContentType xContentType) { - request.source(source, xContentType); + public IndexRequestBuilder setSource(byte[] source, MediaType mediaType) { + request.source(source, mediaType); return this; } @@ -141,10 +141,10 @@ public IndexRequestBuilder setSource(byte[] source, XContentType xContentType) { * @param source The source to index * @param offset The offset in the byte array * @param length The length of the data - * @param xContentType The type/format of the source + * @param mediaType The type/format of the source */ - public IndexRequestBuilder setSource(byte[] source, int offset, int length, XContentType xContentType) { - request.source(source, offset, length, xContentType); + public IndexRequestBuilder setSource(byte[] source, int offset, int length, MediaType mediaType) { + request.source(source, offset, length, mediaType); return this; } @@ -169,8 +169,8 @@ public IndexRequestBuilder setSource(Object... source) { * valid String representation. *

*/ - public IndexRequestBuilder setSource(XContentType xContentType, Object... source) { - request.source(xContentType, source); + public IndexRequestBuilder setSource(MediaType mediaType, Object... source) { + request.source(mediaType, source); return this; } diff --git a/server/src/main/java/org/opensearch/action/index/IndexResponse.java b/server/src/main/java/org/opensearch/action/index/IndexResponse.java index c7c2138a63b4e..69b38be93663a 100644 --- a/server/src/main/java/org/opensearch/action/index/IndexResponse.java +++ b/server/src/main/java/org/opensearch/action/index/IndexResponse.java @@ -35,7 +35,7 @@ import org.opensearch.action.DocWriteResponse; import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.index.shard.ShardId; import org.opensearch.core.rest.RestStatus; @@ -90,7 +90,7 @@ public String toString() { builder.append(",result=").append(getResult().getLowercase()); builder.append(",seqNo=").append(getSeqNo()); builder.append(",primaryTerm=").append(getPrimaryTerm()); - builder.append(",shards=").append(Strings.toString(XContentType.JSON, getShardInfo())); + builder.append(",shards=").append(Strings.toString(MediaTypeRegistry.JSON, getShardInfo())); return builder.append("]").toString(); } diff --git a/server/src/main/java/org/opensearch/action/ingest/GetPipelineResponse.java b/server/src/main/java/org/opensearch/action/ingest/GetPipelineResponse.java index a22f499c4add4..cd87bbf02f75a 100644 --- a/server/src/main/java/org/opensearch/action/ingest/GetPipelineResponse.java +++ b/server/src/main/java/org/opensearch/action/ingest/GetPipelineResponse.java @@ -38,7 +38,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.xcontent.StatusToXContentObject; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.xcontent.XContentParser.Token; @@ -172,7 +172,7 @@ public boolean equals(Object other) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/action/ingest/PutPipelineRequestBuilder.java b/server/src/main/java/org/opensearch/action/ingest/PutPipelineRequestBuilder.java index d69165b280063..e734abb6d7969 100644 --- a/server/src/main/java/org/opensearch/action/ingest/PutPipelineRequestBuilder.java +++ b/server/src/main/java/org/opensearch/action/ingest/PutPipelineRequestBuilder.java @@ -36,7 +36,7 @@ import org.opensearch.action.support.master.AcknowledgedResponse; import org.opensearch.client.OpenSearchClient; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaType; /** * Transport request builder to put a pipeline @@ -54,8 +54,8 @@ public PutPipelineRequestBuilder( PutPipelineAction action, String id, BytesReference source, - XContentType xContentType + MediaType mediaType ) { - super(client, action, new PutPipelineRequest(id, source, xContentType)); + super(client, action, new PutPipelineRequest(id, source, mediaType)); } } diff --git a/server/src/main/java/org/opensearch/action/ingest/SimulatePipelineRequestBuilder.java b/server/src/main/java/org/opensearch/action/ingest/SimulatePipelineRequestBuilder.java index b2eda0e9485e4..55e6d95fde65c 100644 --- a/server/src/main/java/org/opensearch/action/ingest/SimulatePipelineRequestBuilder.java +++ b/server/src/main/java/org/opensearch/action/ingest/SimulatePipelineRequestBuilder.java @@ -35,7 +35,7 @@ import org.opensearch.action.ActionRequestBuilder; import org.opensearch.client.OpenSearchClient; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaType; /** * Transport request builder to simulate a pipeline @@ -58,9 +58,9 @@ public SimulatePipelineRequestBuilder( OpenSearchClient client, SimulatePipelineAction action, BytesReference source, - XContentType xContentType + MediaType mediaType ) { - super(client, action, new SimulatePipelineRequest(source, xContentType)); + super(client, action, new SimulatePipelineRequest(source, mediaType)); } /** diff --git a/server/src/main/java/org/opensearch/action/search/GetSearchPipelineResponse.java b/server/src/main/java/org/opensearch/action/search/GetSearchPipelineResponse.java index cf8d9cec779c8..d25a084058fa0 100644 --- a/server/src/main/java/org/opensearch/action/search/GetSearchPipelineResponse.java +++ b/server/src/main/java/org/opensearch/action/search/GetSearchPipelineResponse.java @@ -14,7 +14,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.xcontent.StatusToXContentObject; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.rest.RestStatus; @@ -129,7 +129,7 @@ private static Map toMap(List updatedSourceAsMap; - private final XContentType updateSourceContentType; + private final MediaType updateSourceContentType; public Result( Writeable action, DocWriteResponse.Result result, Map updatedSourceAsMap, - XContentType updateSourceContentType + MediaType updateSourceContentType ) { this.action = action; this.result = result; @@ -428,7 +429,7 @@ public Map updatedSourceAsMap() { return updatedSourceAsMap; } - public XContentType updateSourceContentType() { + public MediaType updateSourceContentType() { return updateSourceContentType; } } diff --git a/server/src/main/java/org/opensearch/action/update/UpdateRequest.java b/server/src/main/java/org/opensearch/action/update/UpdateRequest.java index 86ebc0d9b69d6..adb42050556f3 100644 --- a/server/src/main/java/org/opensearch/action/update/UpdateRequest.java +++ b/server/src/main/java/org/opensearch/action/update/UpdateRequest.java @@ -56,7 +56,6 @@ import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.VersionType; import org.opensearch.index.mapper.MapperService; import org.opensearch.core.index.shard.ShardId; @@ -663,32 +662,32 @@ public UpdateRequest doc(Map source) { /** * Sets the doc to use for updates when a script is not specified. */ - public UpdateRequest doc(Map source, XContentType contentType) { - safeDoc().source(source, contentType); + public UpdateRequest doc(Map source, MediaType mediaType) { + safeDoc().source(source, mediaType); return this; } /** * Sets the doc to use for updates when a script is not specified. */ - public UpdateRequest doc(String source, XContentType xContentType) { - safeDoc().source(source, xContentType); + public UpdateRequest doc(String source, MediaType mediaType) { + safeDoc().source(source, mediaType); return this; } /** * Sets the doc to use for updates when a script is not specified. */ - public UpdateRequest doc(byte[] source, XContentType xContentType) { - safeDoc().source(source, xContentType); + public UpdateRequest doc(byte[] source, MediaType mediaType) { + safeDoc().source(source, mediaType); return this; } /** * Sets the doc to use for updates when a script is not specified. */ - public UpdateRequest doc(byte[] source, int offset, int length, XContentType xContentType) { - safeDoc().source(source, offset, length, xContentType); + public UpdateRequest doc(byte[] source, int offset, int length, MediaType mediaType) { + safeDoc().source(source, offset, length, mediaType); return this; } @@ -705,8 +704,8 @@ public UpdateRequest doc(Object... source) { * Sets the doc to use for updates when a script is not specified, the doc provided * is a field and value pairs. */ - public UpdateRequest doc(XContentType xContentType, Object... source) { - safeDoc().source(xContentType, source); + public UpdateRequest doc(MediaType mediaType, Object... source) { + safeDoc().source(mediaType, source); return this; } @@ -749,32 +748,32 @@ public UpdateRequest upsert(Map source) { /** * Sets the doc source of the update request to be used when the document does not exists. */ - public UpdateRequest upsert(Map source, XContentType contentType) { - safeUpsertRequest().source(source, contentType); + public UpdateRequest upsert(Map source, MediaType mediaType) { + safeUpsertRequest().source(source, mediaType); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ - public UpdateRequest upsert(String source, XContentType xContentType) { - safeUpsertRequest().source(source, xContentType); + public UpdateRequest upsert(String source, MediaType mediaType) { + safeUpsertRequest().source(source, mediaType); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ - public UpdateRequest upsert(byte[] source, XContentType xContentType) { - safeUpsertRequest().source(source, xContentType); + public UpdateRequest upsert(byte[] source, MediaType mediaType) { + safeUpsertRequest().source(source, mediaType); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ - public UpdateRequest upsert(byte[] source, int offset, int length, XContentType xContentType) { - safeUpsertRequest().source(source, offset, length, xContentType); + public UpdateRequest upsert(byte[] source, int offset, int length, MediaType mediaType) { + safeUpsertRequest().source(source, offset, length, mediaType); return this; } @@ -791,8 +790,8 @@ public UpdateRequest upsert(Object... source) { * Sets the doc source of the update request to be used when the document does not exists. The doc * includes field and value pairs. */ - public UpdateRequest upsert(XContentType xContentType, Object... source) { - safeUpsertRequest().source(xContentType, source); + public UpdateRequest upsert(MediaType mediaType, Object... source) { + safeUpsertRequest().source(mediaType, source); return this; } diff --git a/server/src/main/java/org/opensearch/action/update/UpdateRequestBuilder.java b/server/src/main/java/org/opensearch/action/update/UpdateRequestBuilder.java index 4fdcac0f6927a..c97d0b4f5d13d 100644 --- a/server/src/main/java/org/opensearch/action/update/UpdateRequestBuilder.java +++ b/server/src/main/java/org/opensearch/action/update/UpdateRequestBuilder.java @@ -39,8 +39,8 @@ import org.opensearch.action.support.single.instance.InstanceShardOperationRequestBuilder; import org.opensearch.client.OpenSearchClient; import org.opensearch.common.Nullable; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.VersionType; import org.opensearch.script.Script; @@ -230,7 +230,7 @@ public UpdateRequestBuilder setDoc(Map source) { /** * Sets the doc to use for updates when a script is not specified. */ - public UpdateRequestBuilder setDoc(Map source, XContentType contentType) { + public UpdateRequestBuilder setDoc(Map source, MediaType contentType) { request.doc(source, contentType); return this; } @@ -238,24 +238,24 @@ public UpdateRequestBuilder setDoc(Map source, XContentType cont /** * Sets the doc to use for updates when a script is not specified. */ - public UpdateRequestBuilder setDoc(String source, XContentType xContentType) { - request.doc(source, xContentType); + public UpdateRequestBuilder setDoc(String source, MediaType mediaType) { + request.doc(source, mediaType); return this; } /** * Sets the doc to use for updates when a script is not specified. */ - public UpdateRequestBuilder setDoc(byte[] source, XContentType xContentType) { - request.doc(source, xContentType); + public UpdateRequestBuilder setDoc(byte[] source, MediaType mediaType) { + request.doc(source, mediaType); return this; } /** * Sets the doc to use for updates when a script is not specified. */ - public UpdateRequestBuilder setDoc(byte[] source, int offset, int length, XContentType xContentType) { - request.doc(source, offset, length, xContentType); + public UpdateRequestBuilder setDoc(byte[] source, int offset, int length, MediaType mediaType) { + request.doc(source, offset, length, mediaType); return this; } @@ -272,8 +272,8 @@ public UpdateRequestBuilder setDoc(Object... source) { * Sets the doc to use for updates when a script is not specified, the doc provided * is a field and value pairs. */ - public UpdateRequestBuilder setDoc(XContentType xContentType, Object... source) { - request.doc(xContentType, source); + public UpdateRequestBuilder setDoc(MediaType mediaType, Object... source) { + request.doc(mediaType, source); return this; } @@ -305,32 +305,32 @@ public UpdateRequestBuilder setUpsert(Map source) { /** * Sets the doc source of the update request to be used when the document does not exists. */ - public UpdateRequestBuilder setUpsert(Map source, XContentType contentType) { - request.upsert(source, contentType); + public UpdateRequestBuilder setUpsert(Map source, MediaType mediaType) { + request.upsert(source, mediaType); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ - public UpdateRequestBuilder setUpsert(String source, XContentType xContentType) { - request.upsert(source, xContentType); + public UpdateRequestBuilder setUpsert(String source, MediaType mediaType) { + request.upsert(source, mediaType); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ - public UpdateRequestBuilder setUpsert(byte[] source, XContentType xContentType) { - request.upsert(source, xContentType); + public UpdateRequestBuilder setUpsert(byte[] source, MediaType mediaType) { + request.upsert(source, mediaType); return this; } /** * Sets the doc source of the update request to be used when the document does not exists. */ - public UpdateRequestBuilder setUpsert(byte[] source, int offset, int length, XContentType xContentType) { - request.upsert(source, offset, length, xContentType); + public UpdateRequestBuilder setUpsert(byte[] source, int offset, int length, MediaType mediaType) { + request.upsert(source, offset, length, mediaType); return this; } @@ -347,8 +347,8 @@ public UpdateRequestBuilder setUpsert(Object... source) { * Sets the doc source of the update request to be used when the document does not exists. The doc * includes field and value pairs. */ - public UpdateRequestBuilder setUpsert(XContentType xContentType, Object... source) { - request.upsert(xContentType, source); + public UpdateRequestBuilder setUpsert(MediaType mediaType, Object... source) { + request.upsert(mediaType, source); return this; } diff --git a/server/src/main/java/org/opensearch/client/ClusterAdminClient.java b/server/src/main/java/org/opensearch/client/ClusterAdminClient.java index f3c04b23dfd54..b93bf0cdb4429 100644 --- a/server/src/main/java/org/opensearch/client/ClusterAdminClient.java +++ b/server/src/main/java/org/opensearch/client/ClusterAdminClient.java @@ -159,7 +159,7 @@ import org.opensearch.action.search.PutSearchPipelineRequest; import org.opensearch.action.support.master.AcknowledgedResponse; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.tasks.TaskId; /** @@ -669,7 +669,7 @@ public interface ClusterAdminClient extends OpenSearchClient { /** * Stores an ingest pipeline */ - PutPipelineRequestBuilder preparePutPipeline(String id, BytesReference source, XContentType xContentType); + PutPipelineRequestBuilder preparePutPipeline(String id, BytesReference source, MediaType mediaType); /** * Deletes a stored ingest pipeline @@ -719,7 +719,7 @@ public interface ClusterAdminClient extends OpenSearchClient { /** * Simulates an ingest pipeline */ - SimulatePipelineRequestBuilder prepareSimulatePipeline(BytesReference source, XContentType xContentType); + SimulatePipelineRequestBuilder prepareSimulatePipeline(BytesReference source, MediaType mediaType); /** * Explain the allocation of a shard diff --git a/server/src/main/java/org/opensearch/client/Requests.java b/server/src/main/java/org/opensearch/client/Requests.java index cad5bac8acf0d..3f4a191fa76d5 100644 --- a/server/src/main/java/org/opensearch/client/Requests.java +++ b/server/src/main/java/org/opensearch/client/Requests.java @@ -82,6 +82,8 @@ import org.opensearch.action.search.SearchRequest; import org.opensearch.action.search.SearchScrollRequest; import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; /** * A handy one stop shop for creating requests (make sure to import static this class). @@ -98,7 +100,7 @@ public class Requests { /** * The default content type to use to generate source documents when indexing. */ - public static XContentType INDEX_CONTENT_TYPE = XContentType.JSON; + public static MediaType INDEX_CONTENT_TYPE = MediaTypeRegistry.JSON; public static IndexRequest indexRequest() { return new IndexRequest(); diff --git a/server/src/main/java/org/opensearch/client/support/AbstractClient.java b/server/src/main/java/org/opensearch/client/support/AbstractClient.java index 40489e29ed9b5..beedea1dd477e 100644 --- a/server/src/main/java/org/opensearch/client/support/AbstractClient.java +++ b/server/src/main/java/org/opensearch/client/support/AbstractClient.java @@ -413,7 +413,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.concurrent.ThreadContext; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.tasks.TaskId; import org.opensearch.threadpool.ThreadPool; @@ -1224,8 +1224,8 @@ public ActionFuture putPipeline(PutPipelineRequest request } @Override - public PutPipelineRequestBuilder preparePutPipeline(String id, BytesReference source, XContentType xContentType) { - return new PutPipelineRequestBuilder(this, PutPipelineAction.INSTANCE, id, source, xContentType); + public PutPipelineRequestBuilder preparePutPipeline(String id, BytesReference source, MediaType mediaType) { + return new PutPipelineRequestBuilder(this, PutPipelineAction.INSTANCE, id, source, mediaType); } @Override @@ -1274,8 +1274,8 @@ public ActionFuture simulatePipeline(SimulatePipelineR } @Override - public SimulatePipelineRequestBuilder prepareSimulatePipeline(BytesReference source, XContentType xContentType) { - return new SimulatePipelineRequestBuilder(this, SimulatePipelineAction.INSTANCE, source, xContentType); + public SimulatePipelineRequestBuilder prepareSimulatePipeline(BytesReference source, MediaType mediaType) { + return new SimulatePipelineRequestBuilder(this, SimulatePipelineAction.INSTANCE, source, mediaType); } @Override diff --git a/server/src/main/java/org/opensearch/cluster/RepositoryCleanupInProgress.java b/server/src/main/java/org/opensearch/cluster/RepositoryCleanupInProgress.java index be471ab6a68ec..72a3519aca6f8 100644 --- a/server/src/main/java/org/opensearch/cluster/RepositoryCleanupInProgress.java +++ b/server/src/main/java/org/opensearch/cluster/RepositoryCleanupInProgress.java @@ -37,7 +37,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.repositories.RepositoryOperation; @@ -110,7 +110,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/cluster/SnapshotsInProgress.java b/server/src/main/java/org/opensearch/cluster/SnapshotsInProgress.java index 5f9c93ff254c9..be660755ff052 100644 --- a/server/src/main/java/org/opensearch/cluster/SnapshotsInProgress.java +++ b/server/src/main/java/org/opensearch/cluster/SnapshotsInProgress.java @@ -40,7 +40,7 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.index.shard.ShardId; @@ -699,7 +699,7 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/cluster/action/index/MappingUpdatedAction.java b/server/src/main/java/org/opensearch/cluster/action/index/MappingUpdatedAction.java index c589d9bfeeab2..46d0d7fcbed74 100644 --- a/server/src/main/java/org/opensearch/cluster/action/index/MappingUpdatedAction.java +++ b/server/src/main/java/org/opensearch/cluster/action/index/MappingUpdatedAction.java @@ -48,8 +48,8 @@ import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.concurrent.RunOnce; import org.opensearch.common.util.concurrent.UncategorizedExecutionException; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.Index; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.mapper.Mapping; import java.util.concurrent.Semaphore; @@ -153,7 +153,7 @@ int blockedThreads() { protected void sendUpdateMapping(Index index, Mapping mappingUpdate, ActionListener listener) { PutMappingRequest putMappingRequest = new PutMappingRequest(); putMappingRequest.setConcreteIndex(index); - putMappingRequest.source(mappingUpdate.toString(), XContentType.JSON); + putMappingRequest.source(mappingUpdate.toString(), MediaTypeRegistry.JSON); putMappingRequest.clusterManagerNodeTimeout(dynamicMappingUpdateTimeout); putMappingRequest.timeout(TimeValue.ZERO); client.execute( diff --git a/server/src/main/java/org/opensearch/cluster/awarenesshealth/ClusterAwarenessAttributeValueHealth.java b/server/src/main/java/org/opensearch/cluster/awarenesshealth/ClusterAwarenessAttributeValueHealth.java index 1520a293d2741..eae79e2ac0986 100644 --- a/server/src/main/java/org/opensearch/cluster/awarenesshealth/ClusterAwarenessAttributeValueHealth.java +++ b/server/src/main/java/org/opensearch/cluster/awarenesshealth/ClusterAwarenessAttributeValueHealth.java @@ -18,7 +18,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -293,7 +293,7 @@ private void setWeightInfo(ClusterState clusterState) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/cluster/awarenesshealth/ClusterAwarenessAttributesHealth.java b/server/src/main/java/org/opensearch/cluster/awarenesshealth/ClusterAwarenessAttributesHealth.java index 08832cb1e8807..01d9cfc4438e3 100644 --- a/server/src/main/java/org/opensearch/cluster/awarenesshealth/ClusterAwarenessAttributesHealth.java +++ b/server/src/main/java/org/opensearch/cluster/awarenesshealth/ClusterAwarenessAttributesHealth.java @@ -15,7 +15,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -279,7 +279,7 @@ public static ClusterAwarenessAttributesHealth fromXContent(XContentParser parse @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/cluster/coordination/Coordinator.java b/server/src/main/java/org/opensearch/cluster/coordination/Coordinator.java index 4429136525534..89f45129dcd22 100644 --- a/server/src/main/java/org/opensearch/cluster/coordination/Coordinator.java +++ b/server/src/main/java/org/opensearch/cluster/coordination/Coordinator.java @@ -72,9 +72,9 @@ import org.opensearch.common.util.concurrent.OpenSearchExecutors; import org.opensearch.common.util.concurrent.ListenableFuture; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.common.lease.Releasable; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.discovery.Discovery; import org.opensearch.discovery.DiscoveryModule; import org.opensearch.discovery.DiscoveryStats; @@ -1320,20 +1320,24 @@ assert getLocalNode().equals(clusterState.getNodes().get(getLocalNode().getId()) // deserialized from the resulting JSON private boolean assertPreviousStateConsistency(ClusterChangedEvent event) { assert event.previousState() == coordinationState.get().getLastAcceptedState() - || XContentHelper.convertToMap(JsonXContent.jsonXContent, Strings.toString(XContentType.JSON, event.previousState()), false) + || XContentHelper.convertToMap( + JsonXContent.jsonXContent, + Strings.toString(MediaTypeRegistry.JSON, event.previousState()), + false + ) .equals( XContentHelper.convertToMap( JsonXContent.jsonXContent, Strings.toString( - XContentType.JSON, + MediaTypeRegistry.JSON, clusterStateWithNoClusterManagerBlock(coordinationState.get().getLastAcceptedState()) ), false ) - ) : Strings.toString(XContentType.JSON, event.previousState()) + ) : Strings.toString(MediaTypeRegistry.JSON, event.previousState()) + " vs " + Strings.toString( - XContentType.JSON, + MediaTypeRegistry.JSON, clusterStateWithNoClusterManagerBlock(coordinationState.get().getLastAcceptedState()) ); return true; diff --git a/server/src/main/java/org/opensearch/cluster/decommission/DecommissionAttributeMetadata.java b/server/src/main/java/org/opensearch/cluster/decommission/DecommissionAttributeMetadata.java index 5a9c82a3849e9..3df807a4f94d3 100644 --- a/server/src/main/java/org/opensearch/cluster/decommission/DecommissionAttributeMetadata.java +++ b/server/src/main/java/org/opensearch/cluster/decommission/DecommissionAttributeMetadata.java @@ -17,7 +17,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -282,6 +282,6 @@ public static void toXContent( @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/cluster/health/ClusterShardHealth.java b/server/src/main/java/org/opensearch/cluster/health/ClusterShardHealth.java index 32b54ac947ebd..ae0abdf40ad5a 100644 --- a/server/src/main/java/org/opensearch/cluster/health/ClusterShardHealth.java +++ b/server/src/main/java/org/opensearch/cluster/health/ClusterShardHealth.java @@ -41,9 +41,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -275,7 +275,7 @@ public static ClusterShardHealth fromXContent(XContentParser parser) throws IOEx @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/cluster/metadata/AliasMetadata.java b/server/src/main/java/org/opensearch/cluster/metadata/AliasMetadata.java index 5e4de1be71214..5558756b56541 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/AliasMetadata.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/AliasMetadata.java @@ -43,7 +43,6 @@ import org.opensearch.common.util.set.Sets; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; @@ -260,7 +259,7 @@ public static Diff readDiffFrom(StreamInput in) throws IOExceptio @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } @Override diff --git a/server/src/main/java/org/opensearch/cluster/metadata/ComponentTemplate.java b/server/src/main/java/org/opensearch/cluster/metadata/ComponentTemplate.java index 7c5e0f664df4e..4cb25074e9353 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/ComponentTemplate.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/ComponentTemplate.java @@ -38,9 +38,9 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -152,7 +152,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/cluster/metadata/ComponentTemplateMetadata.java b/server/src/main/java/org/opensearch/cluster/metadata/ComponentTemplateMetadata.java index 2e700389e4fc9..874e9c496f4bc 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/ComponentTemplateMetadata.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/ComponentTemplateMetadata.java @@ -39,9 +39,9 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -155,7 +155,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** diff --git a/server/src/main/java/org/opensearch/cluster/metadata/ComposableIndexTemplate.java b/server/src/main/java/org/opensearch/cluster/metadata/ComposableIndexTemplate.java index b9b7c132ba2cf..3e1246724fb62 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/ComposableIndexTemplate.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/ComposableIndexTemplate.java @@ -40,9 +40,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -278,7 +278,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** diff --git a/server/src/main/java/org/opensearch/cluster/metadata/ComposableIndexTemplateMetadata.java b/server/src/main/java/org/opensearch/cluster/metadata/ComposableIndexTemplateMetadata.java index b72c0fdf81e41..89098bb0a6466 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/ComposableIndexTemplateMetadata.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/ComposableIndexTemplateMetadata.java @@ -40,8 +40,8 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.ParseField; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -156,7 +156,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** diff --git a/server/src/main/java/org/opensearch/cluster/metadata/DataStreamMetadata.java b/server/src/main/java/org/opensearch/cluster/metadata/DataStreamMetadata.java index c7854355ea5cc..094e16c18aba8 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/DataStreamMetadata.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/DataStreamMetadata.java @@ -39,9 +39,9 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -160,7 +160,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** diff --git a/server/src/main/java/org/opensearch/cluster/metadata/MetadataIndexTemplateService.java b/server/src/main/java/org/opensearch/cluster/metadata/MetadataIndexTemplateService.java index 0779f61d97bf0..71237ad916ecc 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/MetadataIndexTemplateService.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/MetadataIndexTemplateService.java @@ -60,8 +60,8 @@ import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.set.Sets; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.index.Index; @@ -1155,7 +1155,7 @@ public static List collectMappings(final ClusterState state, Optional.ofNullable(template.getDataStreamTemplate()) .map(ComposableIndexTemplate.DataStreamTemplate::getDataStreamMappingSnippet) .map(mapping -> { - try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) { + try (XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder()) { builder.value(mapping); return new CompressedXContent(BytesReference.bytes(builder)); } catch (IOException e) { diff --git a/server/src/main/java/org/opensearch/cluster/metadata/RepositoriesMetadata.java b/server/src/main/java/org/opensearch/cluster/metadata/RepositoriesMetadata.java index 9123e4a8d2de3..d7b8c12eb9120 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/RepositoriesMetadata.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/RepositoriesMetadata.java @@ -42,7 +42,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -292,6 +292,6 @@ public static void toXContent(RepositoryMetadata repository, XContentBuilder bui @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/cluster/metadata/TemplateUpgradeService.java b/server/src/main/java/org/opensearch/cluster/metadata/TemplateUpgradeService.java index c8c28c5db67c5..eaa249d5cd341 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/TemplateUpgradeService.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/TemplateUpgradeService.java @@ -49,9 +49,9 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.collect.Tuple; import org.opensearch.common.unit.TimeValue; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; -import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.XContentHelper; import org.opensearch.gateway.GatewayService; import org.opensearch.indices.IndexTemplateMissingException; import org.opensearch.plugins.Plugin; @@ -162,7 +162,10 @@ void upgradeTemplates(Map changes, Set deletions } for (Map.Entry change : changes.entrySet()) { - PutIndexTemplateRequest request = new PutIndexTemplateRequest(change.getKey()).source(change.getValue(), XContentType.JSON); + PutIndexTemplateRequest request = new PutIndexTemplateRequest(change.getKey()).source( + change.getValue(), + MediaTypeRegistry.JSON + ); request.clusterManagerNodeTimeout(TimeValue.timeValueMinutes(1)); client.admin().indices().putTemplate(request, new ActionListener() { @Override @@ -269,7 +272,7 @@ private BytesReference toBytesReference(IndexTemplateMetadata templateMetadata) return XContentHelper.toXContent((builder, params) -> { IndexTemplateMetadata.Builder.toInnerXContentWithTypes(templateMetadata, builder, params); return builder; - }, XContentType.JSON, PARAMS, false); + }, MediaTypeRegistry.JSON, PARAMS, false); } catch (IOException ex) { throw new IllegalStateException("Cannot serialize template [" + templateMetadata.getName() + "]", ex); } diff --git a/server/src/main/java/org/opensearch/cluster/metadata/WeightedRoutingMetadata.java b/server/src/main/java/org/opensearch/cluster/metadata/WeightedRoutingMetadata.java index f4602e357cdbb..cc56a0daf6db7 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/WeightedRoutingMetadata.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/WeightedRoutingMetadata.java @@ -18,7 +18,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -192,6 +192,6 @@ public static void toXContent(WeightedRouting weightedRouting, XContentBuilder b @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/cluster/routing/allocation/command/AllocationCommands.java b/server/src/main/java/org/opensearch/cluster/routing/allocation/command/AllocationCommands.java index 0bae1bb8ee913..ac804819443a5 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/allocation/command/AllocationCommands.java +++ b/server/src/main/java/org/opensearch/cluster/routing/allocation/command/AllocationCommands.java @@ -39,7 +39,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -217,6 +217,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/common/geo/builders/ShapeBuilder.java b/server/src/main/java/org/opensearch/common/geo/builders/ShapeBuilder.java index 54d913b961f9a..54ddeda7e70aa 100644 --- a/server/src/main/java/org/opensearch/common/geo/builders/ShapeBuilder.java +++ b/server/src/main/java/org/opensearch/common/geo/builders/ShapeBuilder.java @@ -45,13 +45,13 @@ import org.opensearch.core.common.io.stream.NamedWriteable; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.locationtech.spatial4j.context.jts.JtsSpatialContext; import org.locationtech.spatial4j.exception.InvalidShapeException; import org.locationtech.spatial4j.shape.Shape; import org.locationtech.spatial4j.shape.jts.JtsGeometry; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.ArrayList; @@ -521,6 +521,6 @@ public String getWriteableName() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/common/settings/Setting.java b/server/src/main/java/org/opensearch/common/settings/Setting.java index adb3840bd7e00..6549a00ea1fdc 100644 --- a/server/src/main/java/org/opensearch/common/settings/Setting.java +++ b/server/src/main/java/org/opensearch/common/settings/Setting.java @@ -43,7 +43,6 @@ import org.opensearch.common.unit.MemorySizeValue; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.core.common.io.stream.StreamInput; @@ -51,6 +50,7 @@ import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -603,7 +603,7 @@ public final XContentBuilder toXContent(XContentBuilder builder, Params params) @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } /** @@ -2338,7 +2338,7 @@ public static Setting> listSetting( private static List parseableStringToList(String parsableString) { // fromXContent doesn't use named xcontent or deprecation. try ( - XContentParser xContentParser = XContentType.JSON.xContent() + XContentParser xContentParser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, parsableString) ) { XContentParser.Token token = xContentParser.nextToken(); @@ -2360,7 +2360,7 @@ private static List parseableStringToList(String parsableString) { private static String arrayToParsableString(List array) { try { - XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder builder = XContentBuilder.builder(MediaTypeRegistry.JSON.xContent()); builder.startArray(); for (String element : array) { builder.value(element); diff --git a/server/src/main/java/org/opensearch/common/settings/Settings.java b/server/src/main/java/org/opensearch/common/settings/Settings.java index da53e41ec4cb1..dec0dc2617a54 100644 --- a/server/src/main/java/org/opensearch/common/settings/Settings.java +++ b/server/src/main/java/org/opensearch/common/settings/Settings.java @@ -1081,7 +1081,7 @@ private void processLegacyLists(Map map) { */ public Builder loadFromMap(Map map) { // TODO: do this without a serialization round-trip - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.map(map); return loadFromSource(builder.toString(), builder.contentType()); } catch (IOException e) { @@ -1092,9 +1092,9 @@ public Builder loadFromMap(Map map) { /** * Loads settings from the actual string content that represents them using {@link #fromXContent(XContentParser)} */ - public Builder loadFromSource(String source, MediaType xContentType) { + public Builder loadFromSource(String source, MediaType mediaType) { try ( - XContentParser parser = xContentType.xContent() + XContentParser parser = mediaType.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source) ) { this.put(fromXContent(parser, true, true)); @@ -1117,17 +1117,17 @@ public Builder loadFromPath(Path path) throws IOException { * Loads settings from a stream that represents them using {@link #fromXContent(XContentParser)} */ public Builder loadFromStream(String resourceName, InputStream is, boolean acceptNullValues) throws IOException { - final XContentType xContentType; + final MediaType mediaType; if (resourceName.endsWith(".json")) { - xContentType = XContentType.JSON; + mediaType = MediaTypeRegistry.JSON; } else if (resourceName.endsWith(".yml") || resourceName.endsWith(".yaml")) { - xContentType = XContentType.YAML; + mediaType = XContentType.YAML; } else { throw new IllegalArgumentException("unable to detect content type from resource name [" + resourceName + "]"); } // fromXContent doesn't use named xcontent or deprecation. try ( - XContentParser parser = xContentType.xContent() + XContentParser parser = mediaType.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, is) ) { if (parser.currentToken() == null) { @@ -1427,7 +1427,7 @@ public void close() throws IOException { @Override public String toString() { - try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) { + try (XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder()) { builder.startObject(); toXContent(builder, new MapParams(Collections.singletonMap("flat_settings", "true"))); builder.endObject(); diff --git a/server/src/main/java/org/opensearch/common/settings/SettingsModule.java b/server/src/main/java/org/opensearch/common/settings/SettingsModule.java index 82c56608e7b26..becf5944171c5 100644 --- a/server/src/main/java/org/opensearch/common/settings/SettingsModule.java +++ b/server/src/main/java/org/opensearch/common/settings/SettingsModule.java @@ -37,9 +37,9 @@ import org.opensearch.common.inject.Binder; import org.opensearch.common.inject.Module; import org.opensearch.common.util.FeatureFlags; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.Arrays; @@ -156,7 +156,7 @@ public SettingsModule( builder.append(System.lineSeparator()); builder.append(System.lineSeparator()); builder.append("curl -XPUT 'http://localhost:9200/_all/_settings?preserve_existing=true' -d '"); - try (XContentBuilder xContentBuilder = XContentBuilder.builder(XContentType.JSON.xContent())) { + try (XContentBuilder xContentBuilder = MediaTypeRegistry.JSON.contentBuilder()) { xContentBuilder.prettyPrint(); xContentBuilder.startObject(); indexSettings.toXContent(xContentBuilder, new ToXContent.MapParams(Collections.singletonMap("flat_settings", "true"))); diff --git a/server/src/main/java/org/opensearch/common/xcontent/JsonToStringXContentParser.java b/server/src/main/java/org/opensearch/common/xcontent/JsonToStringXContentParser.java index 7510c712e3b4b..02ee911a2c400 100644 --- a/server/src/main/java/org/opensearch/common/xcontent/JsonToStringXContentParser.java +++ b/server/src/main/java/org/opensearch/common/xcontent/JsonToStringXContentParser.java @@ -12,6 +12,8 @@ import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.core.xcontent.AbstractXContentParser; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentLocation; @@ -70,7 +72,7 @@ public XContentParser parseObject() throws IOException { builder.field(this.fieldTypeName + VALUE_SUFFIX, valueList); builder.field(this.fieldTypeName + VALUE_AND_PATH_SUFFIX, valueAndPathList); builder.endObject(); - String jString = XContentHelper.convertToJson(BytesReference.bytes(builder), false, XContentType.JSON); + String jString = XContentHelper.convertToJson(BytesReference.bytes(builder), false, MediaTypeRegistry.JSON); return JsonXContent.jsonXContent.createParser(this.xContentRegistry, this.deprecationHandler, String.valueOf(jString)); } @@ -132,8 +134,8 @@ private void parseValue(StringBuilder parsedFields) throws IOException { } @Override - public XContentType contentType() { - return XContentType.JSON; + public MediaType contentType() { + return MediaTypeRegistry.JSON; } @Override diff --git a/server/src/main/java/org/opensearch/common/xcontent/XContentHelper.java b/server/src/main/java/org/opensearch/common/xcontent/XContentHelper.java index 9e5e1aa585d70..35d5188143450 100644 --- a/server/src/main/java/org/opensearch/common/xcontent/XContentHelper.java +++ b/server/src/main/java/org/opensearch/common/xcontent/XContentHelper.java @@ -158,11 +158,8 @@ public static Tuple> convertToMap(BytesReferen /** * Converts the given bytes into a map that is optionally ordered. The provided {@link XContentType} must be non-null. */ - public static Tuple> convertToMap( - BytesReference bytes, - boolean ordered, - MediaType xContentType - ) throws OpenSearchParseException { + public static Tuple> convertToMap(BytesReference bytes, boolean ordered, MediaType mediaType) + throws OpenSearchParseException { try { final MediaType contentType; InputStream input; @@ -178,13 +175,13 @@ public static Tuple> convertToMap( final byte[] raw = arr.array(); final int offset = arr.offset(); final int length = arr.length(); - contentType = xContentType != null ? xContentType : MediaTypeRegistry.mediaTypeFromBytes(raw, offset, length); + contentType = mediaType != null ? mediaType : MediaTypeRegistry.mediaTypeFromBytes(raw, offset, length); return new Tuple<>(Objects.requireNonNull(contentType), convertToMap(contentType.xContent(), raw, offset, length, ordered)); } else { input = bytes.streamInput(); } try (InputStream stream = input) { - contentType = xContentType != null ? xContentType : MediaTypeRegistry.xContentType(stream); + contentType = mediaType != null ? mediaType : MediaTypeRegistry.xContentType(stream); return new Tuple<>(Objects.requireNonNull(contentType), convertToMap(contentType.xContent(), stream, ordered)); } } catch (IOException e) { @@ -262,8 +259,8 @@ public static String convertToJson(BytesReference bytes, boolean reformatJson, b return convertToJson(bytes, reformatJson, prettyPrint, MediaTypeRegistry.xContent(bytes.toBytesRef().bytes)); } - public static String convertToJson(BytesReference bytes, boolean reformatJson, MediaType xContentType) throws IOException { - return convertToJson(bytes, reformatJson, false, xContentType); + public static String convertToJson(BytesReference bytes, boolean reformatJson, MediaType mediaType) throws IOException { + return convertToJson(bytes, reformatJson, false, mediaType); } /** @@ -276,7 +273,7 @@ public static String convertToJson(BytesReference bytes, boolean reformatJson, M * @throws IOException if the reformatting fails, e.g. because the JSON is not well-formed */ public static String stripWhitespace(String json) throws IOException { - return convertToJson(new BytesArray(json), true, XContentType.JSON); + return convertToJson(new BytesArray(json), true, MediaTypeRegistry.JSON); } /** @@ -296,7 +293,7 @@ public static String convertToJson(BytesReference bytes, boolean reformatJson, b public static String convertToJson(BytesReference bytes, boolean reformatJson, boolean prettyPrint, MediaType mediaType) throws IOException { Objects.requireNonNull(mediaType); - if (mediaType == XContentType.JSON && !reformatJson) { + if (mediaType == MediaTypeRegistry.JSON && !reformatJson) { return bytes.utf8ToString(); } @@ -492,19 +489,23 @@ public static void writeRawField(String field, BytesReference source, XContentTy */ @Deprecated public static BytesReference toXContent(ToXContent toXContent, XContentType xContentType, boolean humanReadable) throws IOException { - return toXContent(toXContent, xContentType, ToXContent.EMPTY_PARAMS, humanReadable); + return org.opensearch.core.xcontent.XContentHelper.toXContent(toXContent, xContentType, ToXContent.EMPTY_PARAMS, humanReadable); } /** - * Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided - * {@link XContentType}. Wraps the output into a new anonymous object according to the value returned - * by the {@link ToXContent#isFragment()} method returns. - * - * @deprecated use {@link #toXContent(ToXContent, MediaType, Params, boolean)} instead - */ + * Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided + * {@link XContentType}. Wraps the output into a new anonymous object according to the value returned + * by the {@link ToXContent#isFragment()} method returns. + * + * @deprecated use {@link org.opensearch.core.xcontent.XContentHelper#toXContent(ToXContent, MediaType, ToXContent.Params, boolean)} instead + */ @Deprecated - public static BytesReference toXContent(ToXContent toXContent, XContentType xContentType, Params params, boolean humanReadable) - throws IOException { + public static BytesReference toXContent( + ToXContent toXContent, + XContentType xContentType, + ToXContent.Params params, + boolean humanReadable + ) throws IOException { try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) { builder.humanReadable(humanReadable); if (toXContent.isFragment()) { @@ -518,26 +519,6 @@ public static BytesReference toXContent(ToXContent toXContent, XContentType xCon } } - /** - * Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided - * {@link XContentType}. Wraps the output into a new anonymous object according to the value returned - * by the {@link ToXContent#isFragment()} method returns. - */ - public static BytesReference toXContent(ToXContent toXContent, MediaType mediaType, Params params, boolean humanReadable) - throws IOException { - try (XContentBuilder builder = XContentBuilder.builder(mediaType.xContent())) { - builder.humanReadable(humanReadable); - if (toXContent.isFragment()) { - builder.startObject(); - } - toXContent.toXContent(builder, params); - if (toXContent.isFragment()) { - builder.endObject(); - } - return BytesReference.bytes(builder); - } - } - /** * Returns the contents of an object as an unparsed BytesReference * diff --git a/server/src/main/java/org/opensearch/index/get/GetResult.java b/server/src/main/java/org/opensearch/index/get/GetResult.java index 66d74f6651073..6e069e0bd69bd 100644 --- a/server/src/main/java/org/opensearch/index/get/GetResult.java +++ b/server/src/main/java/org/opensearch/index/get/GetResult.java @@ -41,11 +41,11 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.IgnoredFieldMapper; import org.opensearch.index.mapper.MapperService; import org.opensearch.index.mapper.SourceFieldMapper; @@ -477,6 +477,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/index/mapper/AbstractGeometryFieldMapper.java b/server/src/main/java/org/opensearch/index/mapper/AbstractGeometryFieldMapper.java index e0798e74b4f2f..eafd40fa7283e 100644 --- a/server/src/main/java/org/opensearch/index/mapper/AbstractGeometryFieldMapper.java +++ b/server/src/main/java/org/opensearch/index/mapper/AbstractGeometryFieldMapper.java @@ -39,10 +39,10 @@ import org.opensearch.core.ParseField; import org.opensearch.common.geo.GeoJsonGeometryFormat; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.MapXContentParser; import org.opensearch.common.xcontent.support.XContentMapValues; import org.opensearch.index.query.QueryShardContext; @@ -141,7 +141,7 @@ public Object parseAndFormatObject(Object value, String format) { NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, Collections.singletonMap("dummy_field", value), - XContentType.JSON + MediaTypeRegistry.JSON ) ) { parser.nextToken(); // start object diff --git a/server/src/main/java/org/opensearch/index/mapper/DocumentMapper.java b/server/src/main/java/org/opensearch/index/mapper/DocumentMapper.java index 2461a72a2d041..632103a65ee72 100644 --- a/server/src/main/java/org/opensearch/index/mapper/DocumentMapper.java +++ b/server/src/main/java/org/opensearch/index/mapper/DocumentMapper.java @@ -44,10 +44,10 @@ import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.settings.Settings; import org.opensearch.core.common.text.Text; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.IndexSettings; import org.opensearch.index.analysis.IndexAnalyzers; import org.opensearch.index.mapper.MapperService.MergeReason; @@ -249,13 +249,13 @@ public ParsedDocument parse(SourceToParse source) throws MapperParsingException } public ParsedDocument createDeleteTombstoneDoc(String index, String id) throws MapperParsingException { - final SourceToParse emptySource = new SourceToParse(index, id, new BytesArray("{}"), XContentType.JSON); + final SourceToParse emptySource = new SourceToParse(index, id, new BytesArray("{}"), MediaTypeRegistry.JSON); return documentParser.parseDocument(emptySource, deleteTombstoneMetadataFieldMappers).toTombstone(); } public ParsedDocument createNoopTombstoneDoc(String index, String reason) throws MapperParsingException { final String id = ""; // _id won't be used. - final SourceToParse sourceToParse = new SourceToParse(index, id, new BytesArray("{}"), XContentType.JSON); + final SourceToParse sourceToParse = new SourceToParse(index, id, new BytesArray("{}"), MediaTypeRegistry.JSON); final ParsedDocument parsedDoc = documentParser.parseDocument(sourceToParse, noopTombstoneMetadataFieldMappers).toTombstone(); // Store the reason of a noop as a raw string in the _source field final BytesRef byteRef = new BytesRef(reason); diff --git a/server/src/main/java/org/opensearch/index/mapper/DocumentMapperParser.java b/server/src/main/java/org/opensearch/index/mapper/DocumentMapperParser.java index 69775481a3056..1e78b7cf73f9b 100644 --- a/server/src/main/java/org/opensearch/index/mapper/DocumentMapperParser.java +++ b/server/src/main/java/org/opensearch/index/mapper/DocumentMapperParser.java @@ -37,9 +37,9 @@ import org.opensearch.common.collect.Tuple; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.time.DateFormatter; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.IndexSettings; import org.opensearch.index.query.QueryShardContext; import org.opensearch.index.similarity.SimilarityService; @@ -119,7 +119,7 @@ public Mapper.TypeParser.ParserContext parserContext(DateFormatter dateFormatter public DocumentMapper parse(@Nullable String type, CompressedXContent source) throws MapperParsingException { Map mapping = null; if (source != null) { - Map root = XContentHelper.convertToMap(source.compressedReference(), true, XContentType.JSON).v2(); + Map root = XContentHelper.convertToMap(source.compressedReference(), true, MediaTypeRegistry.JSON).v2(); Tuple> t = extractMapping(type, root); type = t.v1(); mapping = t.v2(); diff --git a/server/src/main/java/org/opensearch/index/mapper/GeoShapeParser.java b/server/src/main/java/org/opensearch/index/mapper/GeoShapeParser.java index 128a7faf2791a..8d97469e49c8f 100644 --- a/server/src/main/java/org/opensearch/index/mapper/GeoShapeParser.java +++ b/server/src/main/java/org/opensearch/index/mapper/GeoShapeParser.java @@ -35,9 +35,9 @@ import org.opensearch.common.geo.GeometryFormat; import org.opensearch.common.geo.GeometryParser; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.MapXContentParser; import org.opensearch.geometry.Geometry; @@ -75,7 +75,7 @@ public Object parseAndFormatObject(Object value, String format) { NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, Collections.singletonMap("dummy_field", value), - XContentType.JSON + MediaTypeRegistry.JSON ) ) { parser.nextToken(); // start object diff --git a/server/src/main/java/org/opensearch/index/mapper/MapperService.java b/server/src/main/java/org/opensearch/index/mapper/MapperService.java index 6a44d4dcfd328..ca8da9bfeac01 100644 --- a/server/src/main/java/org/opensearch/index/mapper/MapperService.java +++ b/server/src/main/java/org/opensearch/index/mapper/MapperService.java @@ -48,8 +48,8 @@ import org.opensearch.common.xcontent.LoggingDeprecationHandler; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.index.AbstractIndexComponent; @@ -253,7 +253,7 @@ public DocumentMapperParser documentMapperParser() { */ public static Map parseMapping(NamedXContentRegistry xContentRegistry, String mappingSource) throws IOException { try ( - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(xContentRegistry, LoggingDeprecationHandler.INSTANCE, mappingSource) ) { return parser.map(); @@ -348,7 +348,7 @@ private void assertMappingVersion( + "to be the same as new mapping [" + newSource + "]"; - final CompressedXContent mapperSource = new CompressedXContent(Strings.toString(XContentType.JSON, mapper)); + final CompressedXContent mapperSource = new CompressedXContent(Strings.toString(MediaTypeRegistry.JSON, mapper)); assert currentSource.equals(mapperSource) : "expected current mapping [" + currentSource + "] for type [" @@ -543,7 +543,7 @@ public static boolean isMappingSourceTyped(String type, Map mapp } public static boolean isMappingSourceTyped(String type, CompressedXContent mappingSource) { - Map root = XContentHelper.convertToMap(mappingSource.compressedReference(), true, XContentType.JSON).v2(); + Map root = XContentHelper.convertToMap(mappingSource.compressedReference(), true, MediaTypeRegistry.JSON).v2(); return isMappingSourceTyped(type, root); } diff --git a/server/src/main/java/org/opensearch/index/mapper/RootObjectMapper.java b/server/src/main/java/org/opensearch/index/mapper/RootObjectMapper.java index e6985010b140a..ce3d6eef19af2 100644 --- a/server/src/main/java/org/opensearch/index/mapper/RootObjectMapper.java +++ b/server/src/main/java/org/opensearch/index/mapper/RootObjectMapper.java @@ -37,8 +37,8 @@ import org.opensearch.common.logging.DeprecationLogger; import org.opensearch.common.settings.Settings; import org.opensearch.common.time.DateFormatter; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.index.mapper.DynamicTemplate.XContentFieldType; @@ -459,7 +459,7 @@ private static void validateDynamicTemplate(Mapper.TypeParser.ParserContext pars Locale.ROOT, "dynamic template [%s] has invalid content [%s]", dynamicTemplate.getName(), - Strings.toString(XContentType.JSON, dynamicTemplate) + Strings.toString(MediaTypeRegistry.JSON, dynamicTemplate) ); final String deprecationMessage; diff --git a/server/src/main/java/org/opensearch/index/query/AbstractQueryBuilder.java b/server/src/main/java/org/opensearch/index/query/AbstractQueryBuilder.java index 99253afccb0d2..ef1eb858d11e2 100644 --- a/server/src/main/java/org/opensearch/index/query/AbstractQueryBuilder.java +++ b/server/src/main/java/org/opensearch/index/query/AbstractQueryBuilder.java @@ -42,9 +42,9 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.lucene.BytesRefs; import org.opensearch.common.xcontent.SuggestingErrorOnUnknown; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.AbstractObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedObjectNotFoundException; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentLocation; @@ -395,6 +395,6 @@ protected static void declareStandardFields(AbstractObjectParser fields = new ArrayList<>(); diff --git a/server/src/main/java/org/opensearch/index/query/SpanNearQueryBuilder.java b/server/src/main/java/org/opensearch/index/query/SpanNearQueryBuilder.java index 320ee23d6b4af..6a22490a17011 100644 --- a/server/src/main/java/org/opensearch/index/query/SpanNearQueryBuilder.java +++ b/server/src/main/java/org/opensearch/index/query/SpanNearQueryBuilder.java @@ -39,8 +39,8 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentLocation; import org.opensearch.core.xcontent.XContentParser; @@ -445,7 +445,7 @@ public final int hashCode() { @Override public final String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } // copied from AbstractQueryBuilder diff --git a/server/src/main/java/org/opensearch/index/reindex/BulkByScrollTask.java b/server/src/main/java/org/opensearch/index/reindex/BulkByScrollTask.java index 6fbe30cc0bb74..e1a952d81ead3 100644 --- a/server/src/main/java/org/opensearch/index/reindex/BulkByScrollTask.java +++ b/server/src/main/java/org/opensearch/index/reindex/BulkByScrollTask.java @@ -41,8 +41,8 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -1048,9 +1048,9 @@ public static StatusOrException fromXContent(XContentParser parser) throws IOExc @Override public String toString() { if (exception != null) { - return "BulkByScrollTask{error=" + Strings.toString(XContentType.JSON, this) + "}"; + return "BulkByScrollTask{error=" + Strings.toString(MediaTypeRegistry.JSON, this) + "}"; } else { - return "BulkByScrollTask{status=" + Strings.toString(XContentType.JSON, this) + "}"; + return "BulkByScrollTask{status=" + Strings.toString(MediaTypeRegistry.JSON, this) + "}"; } } diff --git a/server/src/main/java/org/opensearch/index/reindex/ScrollableHitSource.java b/server/src/main/java/org/opensearch/index/reindex/ScrollableHitSource.java index b7a71da2fef9e..59426fd8cc0b8 100644 --- a/server/src/main/java/org/opensearch/index/reindex/ScrollableHitSource.java +++ b/server/src/main/java/org/opensearch/index/reindex/ScrollableHitSource.java @@ -47,9 +47,9 @@ import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.unit.TimeValue; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.seqno.SequenceNumbers; import org.opensearch.core.rest.RestStatus; import org.opensearch.search.SearchHit; @@ -499,7 +499,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } } diff --git a/server/src/main/java/org/opensearch/index/search/stats/SearchStats.java b/server/src/main/java/org/opensearch/index/search/stats/SearchStats.java index b5781de7cbd62..90dfe0a87f6d0 100644 --- a/server/src/main/java/org/opensearch/index/search/stats/SearchStats.java +++ b/server/src/main/java/org/opensearch/index/search/stats/SearchStats.java @@ -39,7 +39,7 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; @@ -414,7 +414,7 @@ public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params par @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } /** diff --git a/server/src/main/java/org/opensearch/index/shard/PrimaryReplicaSyncer.java b/server/src/main/java/org/opensearch/index/shard/PrimaryReplicaSyncer.java index 7c49c08bbc00f..a5d5e7dc545e1 100644 --- a/server/src/main/java/org/opensearch/index/shard/PrimaryReplicaSyncer.java +++ b/server/src/main/java/org/opensearch/index/shard/PrimaryReplicaSyncer.java @@ -47,8 +47,8 @@ import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.util.concurrent.AbstractRunnable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.shard.ShardId; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.util.io.IOUtils; import org.opensearch.index.seqno.SequenceNumbers; @@ -516,7 +516,7 @@ public void writeTo(StreamOutput out) throws IOException { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/index/shard/RemoveCorruptedShardDataCommand.java b/server/src/main/java/org/opensearch/index/shard/RemoveCorruptedShardDataCommand.java index 9a9733d0c5533..f33c56a114179 100644 --- a/server/src/main/java/org/opensearch/index/shard/RemoveCorruptedShardDataCommand.java +++ b/server/src/main/java/org/opensearch/index/shard/RemoveCorruptedShardDataCommand.java @@ -60,9 +60,9 @@ import org.opensearch.common.io.PathUtils; import org.opensearch.common.lucene.Lucene; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.index.shard.ShardId; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.env.Environment; import org.opensearch.env.NodeEnvironment; import org.opensearch.env.NodeMetadata; @@ -514,7 +514,7 @@ private void printRerouteCommand(ShardPath shardPath, Terminal terminal, boolean ); terminal.println(""); - terminal.println("POST /_cluster/reroute\n" + Strings.toString(XContentType.JSON, commands, true, true)); + terminal.println("POST /_cluster/reroute\n" + Strings.toString(MediaTypeRegistry.JSON, commands, true, true)); terminal.println(""); terminal.println("You must accept the possibility of data loss by changing the `accept_data_loss` parameter to `true`."); terminal.println(""); diff --git a/server/src/main/java/org/opensearch/index/translog/TranslogStats.java b/server/src/main/java/org/opensearch/index/translog/TranslogStats.java index 45a07b7125901..cf279334c7557 100644 --- a/server/src/main/java/org/opensearch/index/translog/TranslogStats.java +++ b/server/src/main/java/org/opensearch/index/translog/TranslogStats.java @@ -36,7 +36,7 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.common.unit.ByteSizeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; @@ -146,7 +146,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } @Override diff --git a/server/src/main/java/org/opensearch/indices/IndicesService.java b/server/src/main/java/org/opensearch/indices/IndicesService.java index 844f4fec706f3..f1cd0d1d1f291 100644 --- a/server/src/main/java/org/opensearch/indices/IndicesService.java +++ b/server/src/main/java/org/opensearch/indices/IndicesService.java @@ -82,7 +82,6 @@ import org.opensearch.common.util.iterable.Iterables; import org.opensearch.common.util.set.Sets; import org.opensearch.common.xcontent.LoggingDeprecationHandler; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.common.lease.Releasable; import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException; @@ -950,7 +949,7 @@ public IndexShard createShard( .indices() .preparePutMapping() .setConcreteIndex(shardRouting.index()) // concrete index - no name clash, it uses uuid - .setSource(mapping.source().string(), XContentType.JSON) + .setSource(mapping.source().string(), MediaTypeRegistry.JSON) .get(); }, this); return indexShard; diff --git a/server/src/main/java/org/opensearch/ingest/ConfigurationUtils.java b/server/src/main/java/org/opensearch/ingest/ConfigurationUtils.java index 894d699aee7f5..9fd9a866ee7e3 100644 --- a/server/src/main/java/org/opensearch/ingest/ConfigurationUtils.java +++ b/server/src/main/java/org/opensearch/ingest/ConfigurationUtils.java @@ -39,10 +39,10 @@ import org.opensearch.OpenSearchParseException; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.script.Script; import org.opensearch.script.ScriptService; @@ -578,7 +578,7 @@ private static Script extractConditional(Map config) throws IOEx try ( XContentBuilder builder = XContentBuilder.builder(JsonXContent.jsonXContent).map(normalizeScript(scriptSource)); InputStream stream = BytesReference.bytes(builder).streamInput(); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, stream) ) { return Script.parse(parser); diff --git a/server/src/main/java/org/opensearch/ingest/PipelineConfiguration.java b/server/src/main/java/org/opensearch/ingest/PipelineConfiguration.java index 3603437d25fd2..f18050f211933 100644 --- a/server/src/main/java/org/opensearch/ingest/PipelineConfiguration.java +++ b/server/src/main/java/org/opensearch/ingest/PipelineConfiguration.java @@ -42,6 +42,7 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.xcontent.ContextParser; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -151,7 +152,7 @@ public static Diff readDiffFrom(StreamInput in) throws IO @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/persistent/PersistentTasksCustomMetadata.java b/server/src/main/java/org/opensearch/persistent/PersistentTasksCustomMetadata.java index bb751cccd7d9c..c83362ac2d5ab 100644 --- a/server/src/main/java/org/opensearch/persistent/PersistentTasksCustomMetadata.java +++ b/server/src/main/java/org/opensearch/persistent/PersistentTasksCustomMetadata.java @@ -45,8 +45,8 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ObjectParser.NamedObjectParser; import org.opensearch.core.xcontent.ToXContent; @@ -211,7 +211,7 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } public long getNumberOfTasksOnNode(String nodeId, String taskName) { @@ -429,7 +429,7 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } public String getId() { diff --git a/server/src/main/java/org/opensearch/persistent/PersistentTasksNodeService.java b/server/src/main/java/org/opensearch/persistent/PersistentTasksNodeService.java index a285874e4c116..9f6098e4fae8e 100644 --- a/server/src/main/java/org/opensearch/persistent/PersistentTasksNodeService.java +++ b/server/src/main/java/org/opensearch/persistent/PersistentTasksNodeService.java @@ -41,7 +41,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.gateway.GatewayService; import org.opensearch.persistent.PersistentTasksCustomMetadata.PersistentTask; @@ -364,7 +364,7 @@ public void writeTo(StreamOutput out) throws IOException { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/repositories/RepositoryCleanupResult.java b/server/src/main/java/org/opensearch/repositories/RepositoryCleanupResult.java index aaec824314068..4523a09769276 100644 --- a/server/src/main/java/org/opensearch/repositories/RepositoryCleanupResult.java +++ b/server/src/main/java/org/opensearch/repositories/RepositoryCleanupResult.java @@ -36,8 +36,8 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -105,6 +105,6 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/repositories/RepositoryInfo.java b/server/src/main/java/org/opensearch/repositories/RepositoryInfo.java index f61f6f6ca92bc..8aa86fc46d591 100644 --- a/server/src/main/java/org/opensearch/repositories/RepositoryInfo.java +++ b/server/src/main/java/org/opensearch/repositories/RepositoryInfo.java @@ -37,7 +37,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; @@ -144,6 +144,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/repositories/RepositoryStatsSnapshot.java b/server/src/main/java/org/opensearch/repositories/RepositoryStatsSnapshot.java index 2acb5e3fcf37f..43ef2393b5e1f 100644 --- a/server/src/main/java/org/opensearch/repositories/RepositoryStatsSnapshot.java +++ b/server/src/main/java/org/opensearch/repositories/RepositoryStatsSnapshot.java @@ -36,7 +36,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable;; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -125,6 +125,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/repositories/blobstore/BlobStoreRepository.java b/server/src/main/java/org/opensearch/repositories/blobstore/BlobStoreRepository.java index f8745cf52327d..d66a8a3caa480 100644 --- a/server/src/main/java/org/opensearch/repositories/blobstore/BlobStoreRepository.java +++ b/server/src/main/java/org/opensearch/repositories/blobstore/BlobStoreRepository.java @@ -96,9 +96,9 @@ import org.opensearch.common.util.concurrent.ConcurrentCollections; import org.opensearch.common.xcontent.LoggingDeprecationHandler; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.lease.Releasable; import org.opensearch.core.util.BytesRefUtils; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.index.mapper.MapperService; @@ -1987,7 +1987,7 @@ private void cacheRepositoryData(BytesReference updated, long generation) { private RepositoryData repositoryDataFromCachedEntry(Tuple cacheEntry) throws IOException { try (InputStream input = CompressorFactory.defaultCompressor().threadLocalInputStream(cacheEntry.v2().streamInput())) { return RepositoryData.snapshotsFromXContent( - XContentType.JSON.xContent().createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, input), + MediaTypeRegistry.JSON.xContent().createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, input), cacheEntry.v1() ); } @@ -2080,7 +2080,7 @@ private RepositoryData getRepositoryData(long indexGen) { // EMPTY is safe here because RepositoryData#fromXContent calls namedObject try ( InputStream blob = blobContainer().readBlob(snapshotsIndexBlobName); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, blob) ) { return RepositoryData.snapshotsFromXContent(parser, indexGen); diff --git a/server/src/main/java/org/opensearch/rest/RestController.java b/server/src/main/java/org/opensearch/rest/RestController.java index 1a8bddc094d26..134ec99023dd1 100644 --- a/server/src/main/java/org/opensearch/rest/RestController.java +++ b/server/src/main/java/org/opensearch/rest/RestController.java @@ -48,6 +48,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.rest.RestStatus; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.util.FeatureFlags; import org.opensearch.common.xcontent.XContentType; @@ -288,7 +289,7 @@ private void dispatchRequest(RestRequest request, RestChannel channel, RestHandl sendContentTypeErrorMessage(request.getAllHeaderValues("Content-Type"), channel); return; } - if (handler.supportsContentStream() && mediaType != XContentType.JSON && mediaType != XContentType.SMILE) { + if (handler.supportsContentStream() && mediaType != MediaTypeRegistry.JSON && mediaType != XContentType.SMILE) { channel.sendResponse( BytesRestResponse.createSimpleErrorResponse( channel, diff --git a/server/src/main/java/org/opensearch/rest/RestRequest.java b/server/src/main/java/org/opensearch/rest/RestRequest.java index b61a998276532..66fcfbb5fee2e 100644 --- a/server/src/main/java/org/opensearch/rest/RestRequest.java +++ b/server/src/main/java/org/opensearch/rest/RestRequest.java @@ -117,14 +117,14 @@ private RestRequest( HttpChannel httpChannel, long requestId ) { - final MediaType xContentType; + final MediaType mediaType; try { - xContentType = parseContentType(headers.get("Content-Type")); + mediaType = parseContentType(headers.get("Content-Type")); } catch (final IllegalArgumentException e) { throw new ContentTypeHeaderException(e); } - if (xContentType != null) { - this.mediaType.set(xContentType); + if (mediaType != null) { + this.mediaType.set(mediaType); } this.xContentRegistry = xContentRegistry; this.httpRequest = httpRequest; diff --git a/server/src/main/java/org/opensearch/rest/action/cat/RestTable.java b/server/src/main/java/org/opensearch/rest/action/cat/RestTable.java index ec44b06318695..59838d3c0da02 100644 --- a/server/src/main/java/org/opensearch/rest/action/cat/RestTable.java +++ b/server/src/main/java/org/opensearch/rest/action/cat/RestTable.java @@ -69,8 +69,8 @@ public class RestTable { public static RestResponse buildResponse(Table table, RestChannel channel) throws Exception { RestRequest request = channel.request(); - MediaType xContentType = getXContentType(request); - if (xContentType != null) { + MediaType mediaType = getXContentType(request); + if (mediaType != null) { return buildXContentBuilder(table, channel); } return buildTextPlainResponse(table, channel); diff --git a/server/src/main/java/org/opensearch/script/Script.java b/server/src/main/java/org/opensearch/script/Script.java index d02ddf0387c22..80f68362b5838 100644 --- a/server/src/main/java/org/opensearch/script/Script.java +++ b/server/src/main/java/org/opensearch/script/Script.java @@ -43,6 +43,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.core.xcontent.AbstractObjectParser; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ObjectParser.ValueType; @@ -181,7 +182,7 @@ private void setInline(XContentParser parser) { // this is really for search templates, that need to be converted to json format XContentBuilder builder = XContentFactory.jsonBuilder(); idOrCode = builder.copyCurrentStructure(parser).toString(); - options.put(CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()); + options.put(CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType()); } else { idOrCode = parser.text(); } diff --git a/server/src/main/java/org/opensearch/script/StoredScriptSource.java b/server/src/main/java/org/opensearch/script/StoredScriptSource.java index 1f28e2d4810fd..2d181866c9518 100644 --- a/server/src/main/java/org/opensearch/script/StoredScriptSource.java +++ b/server/src/main/java/org/opensearch/script/StoredScriptSource.java @@ -44,6 +44,7 @@ import org.opensearch.common.logging.DeprecationLogger; import org.opensearch.common.xcontent.LoggingDeprecationHandler; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ObjectParser.ValueType; @@ -52,7 +53,6 @@ import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.xcontent.XContentParser.Token; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.io.InputStream; @@ -125,7 +125,7 @@ private void setSource(XContentParser parser) { // this is really for search templates, that need to be converted to json format XContentBuilder builder = XContentFactory.jsonBuilder(); source = builder.copyCurrentStructure(parser).toString(); - options.put(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()); + options.put(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType()); } else { source = parser.text(); } diff --git a/server/src/main/java/org/opensearch/search/SearchHit.java b/server/src/main/java/org/opensearch/search/SearchHit.java index a75c50a27d7e5..d24e5a1aff6c4 100644 --- a/server/src/main/java/org/opensearch/search/SearchHit.java +++ b/server/src/main/java/org/opensearch/search/SearchHit.java @@ -47,9 +47,10 @@ import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.common.text.Text; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.index.shard.ShardId; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ObjectParser.ValueType; import org.opensearch.core.xcontent.ToXContentFragment; @@ -62,7 +63,6 @@ import org.opensearch.index.mapper.MapperService; import org.opensearch.index.mapper.SourceFieldMapper; import org.opensearch.index.seqno.SequenceNumbers; -import org.opensearch.core.index.shard.ShardId; import org.opensearch.search.fetch.subphase.highlight.HighlightField; import org.opensearch.search.lookup.SourceLookup; import org.opensearch.transport.RemoteClusterAware; @@ -1113,6 +1113,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/search/aggregations/AggregationBuilder.java b/server/src/main/java/org/opensearch/search/aggregations/AggregationBuilder.java index 13faaef53e214..6270b8bd5bbbb 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/AggregationBuilder.java +++ b/server/src/main/java/org/opensearch/search/aggregations/AggregationBuilder.java @@ -33,8 +33,8 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.NamedWriteable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.index.query.QueryRewriteContext; @@ -193,6 +193,6 @@ public static final class CommonFields extends ParseField.CommonFields { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactories.java b/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactories.java index 0a07daebfe4a9..f04dba45a53c2 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactories.java +++ b/server/src/main/java/org/opensearch/search/aggregations/AggregatorFactories.java @@ -38,7 +38,7 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.xcontent.SuggestingErrorOnUnknown; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedObjectNotFoundException; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -591,7 +591,7 @@ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } @Override diff --git a/server/src/main/java/org/opensearch/search/aggregations/BucketOrder.java b/server/src/main/java/org/opensearch/search/aggregations/BucketOrder.java index a146e518c3f76..56f3820a60348 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/BucketOrder.java +++ b/server/src/main/java/org/opensearch/search/aggregations/BucketOrder.java @@ -34,7 +34,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.search.aggregations.bucket.MultiBucketsAggregation.Bucket; import org.opensearch.search.aggregations.support.AggregationPath; @@ -172,6 +172,6 @@ public void writeTo(StreamOutput out) throws IOException { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/search/aggregations/InternalAggregation.java b/server/src/main/java/org/opensearch/search/aggregations/InternalAggregation.java index d1de09cffd674..ee07a36b4a065 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/InternalAggregation.java +++ b/server/src/main/java/org/opensearch/search/aggregations/InternalAggregation.java @@ -36,7 +36,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.common.util.BigArrays; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.rest.action.search.RestSearchAction; import org.opensearch.script.ScriptService; @@ -394,7 +394,7 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** diff --git a/server/src/main/java/org/opensearch/search/aggregations/PipelineAggregationBuilder.java b/server/src/main/java/org/opensearch/search/aggregations/PipelineAggregationBuilder.java index 536ba7c955311..9754498841159 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/PipelineAggregationBuilder.java +++ b/server/src/main/java/org/opensearch/search/aggregations/PipelineAggregationBuilder.java @@ -35,7 +35,7 @@ import org.opensearch.action.ValidateActions; import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.NamedWriteable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.index.query.QueryRewriteContext; import org.opensearch.index.query.Rewriteable; @@ -288,7 +288,7 @@ public PipelineAggregationBuilder subAggregations(Builder subFactories) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } /** diff --git a/server/src/main/java/org/opensearch/search/aggregations/support/BaseMultiValuesSourceFieldConfig.java b/server/src/main/java/org/opensearch/search/aggregations/support/BaseMultiValuesSourceFieldConfig.java index d3fd401b6da16..6faec2399bbc1 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/support/BaseMultiValuesSourceFieldConfig.java +++ b/server/src/main/java/org/opensearch/search/aggregations/support/BaseMultiValuesSourceFieldConfig.java @@ -14,7 +14,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -147,7 +147,7 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } abstract void doXContentBody(XContentBuilder builder, Params params) throws IOException; diff --git a/server/src/main/java/org/opensearch/search/builder/SearchSourceBuilder.java b/server/src/main/java/org/opensearch/search/builder/SearchSourceBuilder.java index 78cb895a0a4c0..2cb369626ef70 100644 --- a/server/src/main/java/org/opensearch/search/builder/SearchSourceBuilder.java +++ b/server/src/main/java/org/opensearch/search/builder/SearchSourceBuilder.java @@ -42,13 +42,13 @@ import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.logging.DeprecationLogger; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; +import org.opensearch.core.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.index.query.QueryBuilder; import org.opensearch.index.query.QueryRewriteContext; @@ -1803,7 +1803,7 @@ public String toString() { public String toString(Params params) { try { - return XContentHelper.toXContent(this, XContentType.JSON, params, true).utf8ToString(); + return XContentHelper.toXContent(this, MediaTypeRegistry.JSON, params, true).utf8ToString(); } catch (IOException e) { throw new OpenSearchException(e); } diff --git a/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/AbstractHighlighterBuilder.java b/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/AbstractHighlighterBuilder.java index ec0ef28714176..9f7900f95ea39 100644 --- a/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/AbstractHighlighterBuilder.java +++ b/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/AbstractHighlighterBuilder.java @@ -40,8 +40,8 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -773,6 +773,6 @@ public final boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/search/pipeline/PipelineConfiguration.java b/server/src/main/java/org/opensearch/search/pipeline/PipelineConfiguration.java index c37856b628483..86b4e13df348b 100644 --- a/server/src/main/java/org/opensearch/search/pipeline/PipelineConfiguration.java +++ b/server/src/main/java/org/opensearch/search/pipeline/PipelineConfiguration.java @@ -20,6 +20,7 @@ import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ContextParser; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -130,7 +131,7 @@ public static Diff readDiffFrom(StreamInput in) throws IO @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } @Override diff --git a/server/src/main/java/org/opensearch/search/rescore/RescorerBuilder.java b/server/src/main/java/org/opensearch/search/rescore/RescorerBuilder.java index 0bfff5ae5cae0..6766e7c8e07a1 100644 --- a/server/src/main/java/org/opensearch/search/rescore/RescorerBuilder.java +++ b/server/src/main/java/org/opensearch/search/rescore/RescorerBuilder.java @@ -37,8 +37,8 @@ import org.opensearch.core.common.io.stream.NamedWriteable; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -170,6 +170,6 @@ public boolean equals(Object obj) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/search/slice/SliceBuilder.java b/server/src/main/java/org/opensearch/search/slice/SliceBuilder.java index 106f6e4222325..06c9a8f2f5cd0 100644 --- a/server/src/main/java/org/opensearch/search/slice/SliceBuilder.java +++ b/server/src/main/java/org/opensearch/search/slice/SliceBuilder.java @@ -46,8 +46,8 @@ import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.logging.DeprecationLogger; import org.opensearch.common.util.set.Sets; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -328,6 +328,6 @@ private GroupShardsIterator buildShardIterator(ClusterService clu @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/search/sort/SortBuilder.java b/server/src/main/java/org/opensearch/search/sort/SortBuilder.java index 8b4be04f5977a..008e797128bc1 100644 --- a/server/src/main/java/org/opensearch/search/sort/SortBuilder.java +++ b/server/src/main/java/org/opensearch/search/sort/SortBuilder.java @@ -40,8 +40,8 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.NamedWriteable; import org.opensearch.common.lucene.search.Queries; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedObjectNotFoundException; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentParser; @@ -283,6 +283,6 @@ protected static QueryBuilder parseNestedFilter(XContentParser parser) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/search/suggest/Suggest.java b/server/src/main/java/org/opensearch/search/suggest/Suggest.java index fdc74b58e318d..c81bd94b53736 100644 --- a/server/src/main/java/org/opensearch/search/suggest/Suggest.java +++ b/server/src/main/java/org/opensearch/search/suggest/Suggest.java @@ -42,12 +42,12 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.common.text.Text; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.xcontent.XContentParserUtils; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.rest.action.search.RestSearchAction; import org.opensearch.search.aggregations.Aggregation; import org.opensearch.search.suggest.Suggest.Suggestion.Entry; @@ -740,6 +740,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/search/suggest/SuggestBuilder.java b/server/src/main/java/org/opensearch/search/suggest/SuggestBuilder.java index f294914e249c5..9fdece2b5b9a0 100644 --- a/server/src/main/java/org/opensearch/search/suggest/SuggestBuilder.java +++ b/server/src/main/java/org/opensearch/search/suggest/SuggestBuilder.java @@ -38,8 +38,8 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.lucene.BytesRefs; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -218,6 +218,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/main/java/org/opensearch/search/suggest/completion/CompletionSuggestionBuilder.java b/server/src/main/java/org/opensearch/search/suggest/completion/CompletionSuggestionBuilder.java index 1276bc824c05b..6724a48c26a63 100644 --- a/server/src/main/java/org/opensearch/search/suggest/completion/CompletionSuggestionBuilder.java +++ b/server/src/main/java/org/opensearch/search/suggest/completion/CompletionSuggestionBuilder.java @@ -32,20 +32,20 @@ package org.opensearch.search.suggest.completion; import org.opensearch.OpenSearchParseException; +import org.opensearch.common.unit.Fuzziness; +import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.ParseField; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; -import org.opensearch.common.unit.Fuzziness; -import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.CompletionFieldMapper; import org.opensearch.index.mapper.MappedFieldType; import org.opensearch.index.mapper.MapperService; @@ -72,7 +72,7 @@ */ public class CompletionSuggestionBuilder extends SuggestionBuilder { - private static final XContentType CONTEXT_BYTES_XCONTENT_TYPE = XContentType.JSON; + private static final MediaType CONTEXT_BYTES_XCONTENT_TYPE = MediaTypeRegistry.JSON; static final ParseField CONTEXTS_FIELD = new ParseField("contexts", "context"); static final ParseField SKIP_DUPLICATES_FIELD = new ParseField("skip_duplicates"); diff --git a/server/src/main/java/org/opensearch/snapshots/RestoreInfo.java b/server/src/main/java/org/opensearch/snapshots/RestoreInfo.java index f44cb222af9c6..f5a8a46b4e6ab 100644 --- a/server/src/main/java/org/opensearch/snapshots/RestoreInfo.java +++ b/server/src/main/java/org/opensearch/snapshots/RestoreInfo.java @@ -35,8 +35,8 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ObjectParser; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; @@ -215,6 +215,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } } diff --git a/server/src/main/java/org/opensearch/tasks/RawTaskStatus.java b/server/src/main/java/org/opensearch/tasks/RawTaskStatus.java index 71e113a22e9c3..28950f5a713fc 100644 --- a/server/src/main/java/org/opensearch/tasks/RawTaskStatus.java +++ b/server/src/main/java/org/opensearch/tasks/RawTaskStatus.java @@ -38,7 +38,6 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.io.InputStream; @@ -87,7 +86,7 @@ public String getWriteableName() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } /** diff --git a/server/src/main/java/org/opensearch/tasks/TaskInfo.java b/server/src/main/java/org/opensearch/tasks/TaskInfo.java index 2da461a93b871..3212ed7481b8d 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskInfo.java +++ b/server/src/main/java/org/opensearch/tasks/TaskInfo.java @@ -41,8 +41,8 @@ import org.opensearch.common.unit.TimeValue; import org.opensearch.core.xcontent.ConstructingObjectParser; import org.opensearch.common.xcontent.ObjectParserHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -398,7 +398,7 @@ public static TaskInfo fromXContent(XContentParser parser) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } // Implements equals and hashCode for testing diff --git a/server/src/main/java/org/opensearch/tasks/TaskResourceStats.java b/server/src/main/java/org/opensearch/tasks/TaskResourceStats.java index ce6c88a0c283f..7451c5b3bc148 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskResourceStats.java +++ b/server/src/main/java/org/opensearch/tasks/TaskResourceStats.java @@ -13,7 +13,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -117,7 +117,7 @@ public static TaskResourceStats fromXContent(XContentParser parser) throws IOExc @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } // Implements equals and hashcode for testing diff --git a/server/src/main/java/org/opensearch/tasks/TaskResourceUsage.java b/server/src/main/java/org/opensearch/tasks/TaskResourceUsage.java index 2c86d06613b6c..31a7cd3ac372b 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskResourceUsage.java +++ b/server/src/main/java/org/opensearch/tasks/TaskResourceUsage.java @@ -12,9 +12,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -88,7 +88,7 @@ public static TaskResourceUsage fromXContent(XContentParser parser) { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } // Implements equals and hashcode for testing diff --git a/server/src/main/java/org/opensearch/tasks/TaskResult.java b/server/src/main/java/org/opensearch/tasks/TaskResult.java index 607e7443f73fd..63e24b3175995 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskResult.java +++ b/server/src/main/java/org/opensearch/tasks/TaskResult.java @@ -47,7 +47,6 @@ import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.Map; @@ -92,7 +91,7 @@ public TaskResult(TaskInfo task, Exception error) throws IOException { * Construct a {@linkplain TaskResult} for a task that completed successfully. */ public TaskResult(TaskInfo task, ToXContent response) throws IOException { - this(true, task, null, XContentHelper.toXContent(response, Requests.INDEX_CONTENT_TYPE, true)); + this(true, task, null, org.opensearch.core.xcontent.XContentHelper.toXContent(response, Requests.INDEX_CONTENT_TYPE, true)); } public TaskResult(boolean completed, TaskInfo task, @Nullable BytesReference error, @Nullable BytesReference result) { @@ -208,7 +207,7 @@ public XContentBuilder innerToXContent(XContentBuilder builder, Params params) t @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } // Implements equals and hashcode for testing diff --git a/server/src/main/java/org/opensearch/tasks/TaskResultsService.java b/server/src/main/java/org/opensearch/tasks/TaskResultsService.java index 01be4eaaaf732..3dc61635d9ba7 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskResultsService.java +++ b/server/src/main/java/org/opensearch/tasks/TaskResultsService.java @@ -57,7 +57,6 @@ import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.Streams; import org.opensearch.threadpool.ThreadPool; @@ -146,7 +145,7 @@ public void onFailure(Exception e) { client.admin() .indices() .preparePutMapping(TASK_INDEX) - .setSource(taskResultIndexMapping(), XContentType.JSON) + .setSource(taskResultIndexMapping(), MediaTypeRegistry.JSON) .execute(ActionListener.delegateFailure(listener, (l, r) -> doStoreResult(taskResult, listener))); } else { doStoreResult(taskResult, listener); diff --git a/server/src/main/java/org/opensearch/tasks/TaskThreadUsage.java b/server/src/main/java/org/opensearch/tasks/TaskThreadUsage.java index 9c0e2371e77de..85f01bd7f4676 100644 --- a/server/src/main/java/org/opensearch/tasks/TaskThreadUsage.java +++ b/server/src/main/java/org/opensearch/tasks/TaskThreadUsage.java @@ -12,9 +12,9 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContentFragment; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -104,6 +104,6 @@ public int hashCode() { @Override public String toString() { - return Strings.toString(XContentType.JSON, this, true, true); + return Strings.toString(MediaTypeRegistry.JSON, this, true, true); } } diff --git a/server/src/test/java/org/opensearch/ExceptionSerializationTests.java b/server/src/test/java/org/opensearch/ExceptionSerializationTests.java index f46d08798868f..da29d90ac3539 100644 --- a/server/src/test/java/org/opensearch/ExceptionSerializationTests.java +++ b/server/src/test/java/org/opensearch/ExceptionSerializationTests.java @@ -76,9 +76,9 @@ import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.util.CancellableThreadsTests; import org.opensearch.common.util.set.Sets; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.snapshots.IndexShardSnapshotException; import org.opensearch.core.index.snapshots.IndexShardSnapshotFailedException; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentLocation; import org.opensearch.discovery.MasterNotDiscoveredException; import org.opensearch.env.ShardLockObtainFailedException; @@ -545,12 +545,12 @@ public void testNotSerializableExceptionWrapper() throws IOException { NotSerializableExceptionWrapper ex = serialize(new NotSerializableExceptionWrapper(new NullPointerException())); assertEquals( "{\"type\":\"null_pointer_exception\",\"reason\":\"null_pointer_exception: null\"}", - Strings.toString(XContentType.JSON, ex) + Strings.toString(MediaTypeRegistry.JSON, ex) ); ex = serialize(new NotSerializableExceptionWrapper(new IllegalArgumentException("nono!"))); assertEquals( "{\"type\":\"illegal_argument_exception\",\"reason\":\"illegal_argument_exception: nono!\"}", - Strings.toString(XContentType.JSON, ex) + Strings.toString(MediaTypeRegistry.JSON, ex) ); class UnknownException extends Exception { diff --git a/server/src/test/java/org/opensearch/OpenSearchExceptionTests.java b/server/src/test/java/org/opensearch/OpenSearchExceptionTests.java index e27d376907caa..3df1bdbbc8731 100644 --- a/server/src/test/java/org/opensearch/OpenSearchExceptionTests.java +++ b/server/src/test/java/org/opensearch/OpenSearchExceptionTests.java @@ -46,7 +46,6 @@ import org.opensearch.common.UUIDs; import org.opensearch.common.collect.Tuple; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.ParsingException; import org.opensearch.core.common.Strings; @@ -978,7 +977,7 @@ public void testFailureToAndFromXContentWithDetails() throws IOException { * be rendered like the REST API does when the "error_trace" parameter is set to true. */ private static void assertToXContentAsJson(ToXContent e, String expectedJson) throws IOException { - BytesReference actual = XContentHelper.toXContent(e, XContentType.JSON, randomBoolean()); + BytesReference actual = org.opensearch.core.xcontent.XContentHelper.toXContent(e, MediaTypeRegistry.JSON, randomBoolean()); assertToXContentEquivalent(new BytesArray(expectedJson), actual, MediaTypeRegistry.JSON); } diff --git a/server/src/test/java/org/opensearch/action/RenamedTimeoutRequestParameterTests.java b/server/src/test/java/org/opensearch/action/RenamedTimeoutRequestParameterTests.java index 23b1a8d8462cb..af20c450186aa 100644 --- a/server/src/test/java/org/opensearch/action/RenamedTimeoutRequestParameterTests.java +++ b/server/src/test/java/org/opensearch/action/RenamedTimeoutRequestParameterTests.java @@ -16,8 +16,8 @@ import org.opensearch.common.logging.DeprecationLogger; import org.opensearch.common.settings.Settings; import org.opensearch.common.settings.SettingsFilter; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.rest.BaseRestHandler; import org.opensearch.rest.action.admin.cluster.RestClusterGetSettingsAction; import org.opensearch.rest.action.admin.cluster.RestClusterHealthAction; @@ -715,6 +715,6 @@ private FakeRestRequest getRestRequestWithBodyWithBothParams() { } private FakeRestRequest getFakeRestRequestWithBody() { - return new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withContent(new BytesArray("{}"), XContentType.JSON).build(); + return new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withContent(new BytesArray("{}"), MediaTypeRegistry.JSON).build(); } } diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java index 3fbac5590cff0..67792f2a62b2c 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java @@ -52,7 +52,6 @@ import org.opensearch.cluster.service.ClusterService; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.StreamInput; @@ -343,7 +342,7 @@ public void onFailure(Exception e) { "local tasks [{}]", localTasks.values() .stream() - .map(t -> Strings.toString(XContentType.JSON, t.taskInfo(testNodes[0].getNodeId(), true))) + .map(t -> Strings.toString(MediaTypeRegistry.JSON, t.taskInfo(testNodes[0].getNodeId(), true))) .collect(Collectors.joining(",")) ); assertEquals(2, localTasks.size()); // all node tasks + 1 coordinating task @@ -761,7 +760,7 @@ public void testTasksToXContentGrouping() throws Exception { } private Map serialize(ListTasksResponse response, boolean byParents) throws IOException { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder(); builder.startObject(); if (byParents) { DiscoveryNodes nodes = testNodes[0].clusterService.state().nodes(); diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/remotestore/restore/RestoreRemoteStoreRequestTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/remotestore/restore/RestoreRemoteStoreRequestTests.java index 2edfa23286658..c2e9336ccf1c4 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/remotestore/restore/RestoreRemoteStoreRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/remotestore/restore/RestoreRemoteStoreRequestTests.java @@ -10,11 +10,11 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.Writeable; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.test.AbstractWireSerializingTestCase; @@ -70,7 +70,7 @@ protected RestoreRemoteStoreRequest mutateInstance(RestoreRemoteStoreRequest ins public void testSource() throws IOException { RestoreRemoteStoreRequest original = createTestInstance(); XContentBuilder builder = original.toXContent(XContentFactory.jsonBuilder(), new ToXContent.MapParams(Collections.emptyMap())); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, null, BytesReference.bytes(builder).streamInput()); Map map = parser.mapOrdered(); diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestTests.java index 6df0563ee1b4e..505ed8fe9f600 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/settings/ClusterUpdateSettingsRequestTests.java @@ -33,10 +33,11 @@ package org.opensearch.action.admin.cluster.settings; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParseException; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.OpenSearchTestCase; import org.opensearch.test.XContentTestUtils; @@ -59,14 +60,14 @@ public void testFromXContentWithRandomFields() throws IOException { private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws IOException { final ClusterUpdateSettingsRequest request = createTestItem(); boolean humanReadable = randomBoolean(); - final XContentType xContentType = XContentType.JSON; - BytesReference originalBytes = toShuffledXContent(request, xContentType, ToXContent.EMPTY_PARAMS, humanReadable); + final MediaType mediaType = MediaTypeRegistry.JSON; + BytesReference originalBytes = toShuffledXContent(request, mediaType, ToXContent.EMPTY_PARAMS, humanReadable); if (addRandomFields) { String unsupportedField = "unsupported_field"; BytesReference mutated = BytesReference.bytes( XContentTestUtils.insertIntoXContent( - xContentType.xContent(), + mediaType.xContent(), originalBytes, Collections.singletonList(""), () -> unsupportedField, @@ -75,11 +76,11 @@ private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws ); XContentParseException iae = expectThrows( XContentParseException.class, - () -> ClusterUpdateSettingsRequest.fromXContent(createParser(xContentType.xContent(), mutated)) + () -> ClusterUpdateSettingsRequest.fromXContent(createParser(mediaType.xContent(), mutated)) ); assertThat(iae.getMessage(), containsString("[cluster_update_settings_request] unknown field [" + unsupportedField + "]")); } else { - try (XContentParser parser = createParser(xContentType.xContent(), originalBytes)) { + try (XContentParser parser = createParser(mediaType.xContent(), originalBytes)) { ClusterUpdateSettingsRequest parsedRequest = ClusterUpdateSettingsRequest.fromXContent(parser); assertNull(parser.nextToken()); diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/ClusterPutWeightedRoutingRequestTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/ClusterPutWeightedRoutingRequestTests.java index 3b50b0ff87428..21248b11e69e5 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/ClusterPutWeightedRoutingRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/shards/routing/weighted/put/ClusterPutWeightedRoutingRequestTests.java @@ -11,7 +11,7 @@ import org.opensearch.action.ActionRequestValidationException; import org.opensearch.cluster.routing.WeightedRouting; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchTestCase; import java.util.Map; @@ -24,7 +24,7 @@ public void testSetWeightedRoutingWeight() { Map weights = Map.of("us-east-1a", 1.0, "us-east-1b", 1.0, "us-east-1c", 0.0); WeightedRouting weightedRouting = new WeightedRouting("zone", weights); - request.setWeightedRouting(new BytesArray(reqString), XContentType.JSON); + request.setWeightedRouting(new BytesArray(reqString), MediaTypeRegistry.JSON); assertEquals(weightedRouting, request.getWeightedRouting()); assertEquals(1, request.getVersion()); } @@ -32,7 +32,7 @@ public void testSetWeightedRoutingWeight() { public void testValidate_ValuesAreProper() { String reqString = "{\"weights\":{\"us-east-1c\":\"0\",\"us-east-1b\":\"1\",\"us-east-1a\":\"1\"},\"_version\":1}"; ClusterPutWeightedRoutingRequest request = new ClusterPutWeightedRoutingRequest("zone"); - request.setWeightedRouting(new BytesArray(reqString), XContentType.JSON); + request.setWeightedRouting(new BytesArray(reqString), MediaTypeRegistry.JSON); ActionRequestValidationException actionRequestValidationException = request.validate(); assertNull(actionRequestValidationException); } @@ -40,7 +40,7 @@ public void testValidate_ValuesAreProper() { public void testValidate_MissingWeights() { String reqString = "{}"; ClusterPutWeightedRoutingRequest request = new ClusterPutWeightedRoutingRequest("zone"); - request.setWeightedRouting(new BytesArray(reqString), XContentType.JSON); + request.setWeightedRouting(new BytesArray(reqString), MediaTypeRegistry.JSON); ActionRequestValidationException actionRequestValidationException = request.validate(); assertNotNull(actionRequestValidationException); assertTrue(actionRequestValidationException.getMessage().contains("Weights are missing")); @@ -49,7 +49,7 @@ public void testValidate_MissingWeights() { public void testValidate_AttributeMissing() { String reqString = "{\"weights\":{\"us-east-1c\":\"0\",\"us-east-1b\":\"1\",\"us-east-1a\": \"1\"},\"_version\":1}"; ClusterPutWeightedRoutingRequest request = new ClusterPutWeightedRoutingRequest(); - request.setWeightedRouting(new BytesArray(reqString), XContentType.JSON); + request.setWeightedRouting(new BytesArray(reqString), MediaTypeRegistry.JSON); ActionRequestValidationException actionRequestValidationException = request.validate(); assertNotNull(actionRequestValidationException); assertTrue(actionRequestValidationException.getMessage().contains("Attribute name is missing")); @@ -58,7 +58,7 @@ public void testValidate_AttributeMissing() { public void testValidate_MoreThanHalfWithZeroWeight() { String reqString = "{\"weights\":{\"us-east-1c\":\"0\",\"us-east-1b\":\"0\",\"us-east-1a\": \"1\"}," + "\"_version\":1}"; ClusterPutWeightedRoutingRequest request = new ClusterPutWeightedRoutingRequest("zone"); - request.setWeightedRouting(new BytesArray(reqString), XContentType.JSON); + request.setWeightedRouting(new BytesArray(reqString), MediaTypeRegistry.JSON); ActionRequestValidationException actionRequestValidationException = request.validate(); assertNotNull(actionRequestValidationException); assertTrue( @@ -69,7 +69,7 @@ public void testValidate_MoreThanHalfWithZeroWeight() { public void testValidate_VersionMissing() { String reqString = "{\"weights\":{\"us-east-1c\": \"0\",\"us-east-1b\": \"1\",\"us-east-1a\": \"1\"}}"; ClusterPutWeightedRoutingRequest request = new ClusterPutWeightedRoutingRequest("zone"); - request.setWeightedRouting(new BytesArray(reqString), XContentType.JSON); + request.setWeightedRouting(new BytesArray(reqString), MediaTypeRegistry.JSON); ActionRequestValidationException actionRequestValidationException = request.validate(); assertNotNull(actionRequestValidationException); assertTrue(actionRequestValidationException.getMessage().contains("Version is missing")); diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/snapshots/create/CreateSnapshotRequestTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/snapshots/create/CreateSnapshotRequestTests.java index 7c9d913951d36..057f1af11df2c 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/snapshots/create/CreateSnapshotRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/snapshots/create/CreateSnapshotRequestTests.java @@ -38,12 +38,12 @@ import org.opensearch.action.support.IndicesOptions.WildcardStates; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent.MapParams; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.OpenSearchTestCase; import java.io.IOException; @@ -124,7 +124,7 @@ public void testToXContent() throws IOException { } XContentBuilder builder = original.toXContent(XContentFactory.jsonBuilder(), new MapParams(Collections.emptyMap())); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, null, BytesReference.bytes(builder).streamInput()); Map map = parser.mapOrdered(); CreateSnapshotRequest processed = new CreateSnapshotRequest((String) map.get("repository"), (String) map.get("snapshot")); diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequestTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequestTests.java index 82b2cfb2e3e51..ed541fdddb984 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/snapshots/restore/RestoreSnapshotRequestTests.java @@ -35,12 +35,12 @@ import org.opensearch.action.support.IndicesOptions; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.Writeable; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.AbstractWireSerializingTestCase; import java.io.IOException; @@ -145,7 +145,7 @@ public void testSource() throws IOException { RestoreSnapshotRequest original = createTestInstance(); original.snapshotUuid(null); // cannot be set via the REST API XContentBuilder builder = original.toXContent(XContentFactory.jsonBuilder(), new ToXContent.MapParams(Collections.emptyMap())); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, null, BytesReference.bytes(builder).streamInput()); Map map = parser.mapOrdered(); diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/stats/ClusterStatsNodesTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/stats/ClusterStatsNodesTests.java index 627ada7092273..a0c45f95ef7c0 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/stats/ClusterStatsNodesTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/stats/ClusterStatsNodesTests.java @@ -38,7 +38,7 @@ import org.opensearch.cluster.node.DiscoveryNode; import org.opensearch.common.network.NetworkModule; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchTestCase; import java.util.Arrays; @@ -51,7 +51,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.hamcrest.Matchers.equalTo; public class ClusterStatsNodesTests extends OpenSearchTestCase { @@ -62,11 +62,17 @@ public class ClusterStatsNodesTests extends OpenSearchTestCase { */ public void testNetworkTypesToXContent() throws Exception { ClusterStatsNodes.NetworkTypes stats = new ClusterStatsNodes.NetworkTypes(emptyList()); - assertEquals("{\"transport_types\":{},\"http_types\":{}}", toXContent(stats, XContentType.JSON, randomBoolean()).utf8ToString()); + assertEquals( + "{\"transport_types\":{},\"http_types\":{}}", + toXContent(stats, MediaTypeRegistry.JSON, randomBoolean()).utf8ToString() + ); List nodeInfos = singletonList(createNodeInfo("node_0", null, null)); stats = new ClusterStatsNodes.NetworkTypes(nodeInfos); - assertEquals("{\"transport_types\":{},\"http_types\":{}}", toXContent(stats, XContentType.JSON, randomBoolean()).utf8ToString()); + assertEquals( + "{\"transport_types\":{},\"http_types\":{}}", + toXContent(stats, MediaTypeRegistry.JSON, randomBoolean()).utf8ToString() + ); nodeInfos = Arrays.asList( createNodeInfo("node_1", "", ""), @@ -76,7 +82,7 @@ public void testNetworkTypesToXContent() throws Exception { stats = new ClusterStatsNodes.NetworkTypes(nodeInfos); assertEquals( "{" + "\"transport_types\":{\"custom\":1}," + "\"http_types\":{\"custom\":2}" + "}", - toXContent(stats, XContentType.JSON, randomBoolean()).utf8ToString() + toXContent(stats, MediaTypeRegistry.JSON, randomBoolean()).utf8ToString() ); } @@ -132,7 +138,7 @@ public void testIngestStats() throws Exception { } processorStatsString += "}"; assertThat( - toXContent(stats, XContentType.JSON, false).utf8ToString(), + toXContent(stats, MediaTypeRegistry.JSON, false).utf8ToString(), equalTo( "{\"ingest\":{" + "\"number_of_pipelines\":" diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java index 67358fade4b17..ebfd2a6761f46 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/storedscripts/GetStoredScriptResponseTests.java @@ -33,8 +33,8 @@ package org.opensearch.action.admin.cluster.storedscripts; import org.opensearch.core.common.io.stream.Writeable; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.script.Script; import org.opensearch.script.StoredScriptSource; import org.opensearch.test.AbstractSerializingTestCase; @@ -70,7 +70,7 @@ private static StoredScriptSource randomScriptSource() { final String lang = randomFrom("lang", "painless", "mustache"); final String source = randomAlphaOfLengthBetween(1, 10); final Map options = randomBoolean() - ? Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) + ? Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType()) : Collections.emptyMap(); return new StoredScriptSource(lang, source, options); } diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequestTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequestTests.java index cfdd776e60832..a61386f2c3973 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/storedscripts/PutStoredScriptRequestTests.java @@ -36,6 +36,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.core.common.io.stream.StreamInput; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentType; @@ -52,17 +53,17 @@ public void testSerialization() throws IOException { "bar", "context", new BytesArray("{}"), - XContentType.JSON, + MediaTypeRegistry.JSON, new StoredScriptSource("foo", "bar", Collections.emptyMap()) ); - assertEquals(XContentType.JSON, storedScriptRequest.mediaType()); + assertEquals(MediaTypeRegistry.JSON, storedScriptRequest.mediaType()); try (BytesStreamOutput output = new BytesStreamOutput()) { storedScriptRequest.writeTo(output); try (StreamInput in = output.bytes().streamInput()) { PutStoredScriptRequest serialized = new PutStoredScriptRequest(in); - assertEquals(XContentType.JSON, serialized.mediaType()); + assertEquals(MediaTypeRegistry.JSON, serialized.mediaType()); assertEquals(storedScriptRequest.id(), serialized.id()); assertEquals(storedScriptRequest.context(), serialized.context()); } diff --git a/server/src/test/java/org/opensearch/action/admin/indices/alias/AliasActionsTests.java b/server/src/test/java/org/opensearch/action/admin/indices/alias/AliasActionsTests.java index 952404768a993..d578c3137fbdd 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/alias/AliasActionsTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/alias/AliasActionsTests.java @@ -194,7 +194,7 @@ public void testParseAdd() throws IOException { if (filter == null || filter.isEmpty()) { assertNull(action.filter()); } else { - assertEquals(MediaTypeRegistry.contentBuilder(XContentType.JSON).map(filter).toString(), action.filter()); + assertEquals(MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON).map(filter).toString(), action.filter()); } assertEquals(Objects.toString(searchRouting, null), action.searchRouting()); assertEquals(Objects.toString(indexRouting, null), action.indexRouting()); diff --git a/server/src/test/java/org/opensearch/action/admin/indices/close/CloseIndexResponseTests.java b/server/src/test/java/org/opensearch/action/admin/indices/close/CloseIndexResponseTests.java index 7e3b4f175d8ea..5b6c2d10bddfa 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/close/CloseIndexResponseTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/close/CloseIndexResponseTests.java @@ -37,6 +37,7 @@ import org.opensearch.action.admin.indices.close.CloseIndexResponse.IndexResult; import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.Writeable; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentType; @@ -151,7 +152,7 @@ public void testToXContent() throws IOException { CloseIndexResponse closeIndexResponse = new CloseIndexResponse(true, true, Collections.singletonList(indexResult)); assertEquals( "{\"acknowledged\":true,\"shards_acknowledged\":true,\"indices\":{\"test\":{\"closed\":true}}}", - Strings.toString(XContentType.JSON, closeIndexResponse) + Strings.toString(MediaTypeRegistry.JSON, closeIndexResponse) ); CloseIndexResponse.ShardResult[] shards = new CloseIndexResponse.ShardResult[1]; @@ -168,7 +169,7 @@ public void testToXContent() throws IOException { + "\"failures\":[{\"node\":\"nodeId\",\"shard\":0,\"index\":\"test\",\"status\":\"INTERNAL_SERVER_ERROR\"," + "\"reason\":{\"type\":\"action_not_found_transport_exception\"," + "\"reason\":\"No handler for action [test]\"}}]}}}}}", - Strings.toString(XContentType.JSON, closeIndexResponse) + Strings.toString(MediaTypeRegistry.JSON, closeIndexResponse) ); } diff --git a/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilderTests.java b/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilderTests.java index 8ecd60803b52d..2d71495b2dc19 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilderTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestBuilderTests.java @@ -34,9 +34,9 @@ import org.opensearch.OpenSearchParseException; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.OpenSearchTestCase; import org.opensearch.test.client.NoOpClient; import org.junit.After; @@ -75,11 +75,11 @@ public void testSetSource() throws IOException { CreateIndexRequestBuilder builder = new CreateIndexRequestBuilder(this.testClient, CreateIndexAction.INSTANCE); OpenSearchParseException e = expectThrows(OpenSearchParseException.class, () -> { - builder.setSource("{\"" + KEY + "\" : \"" + VALUE + "\"}", XContentType.JSON); + builder.setSource("{\"" + KEY + "\" : \"" + VALUE + "\"}", MediaTypeRegistry.JSON); }); assertEquals(String.format(Locale.ROOT, "unknown key [%s] for create index", KEY), e.getMessage()); - builder.setSource("{\"settings\" : {\"" + KEY + "\" : \"" + VALUE + "\"}}", XContentType.JSON); + builder.setSource("{\"settings\" : {\"" + KEY + "\" : \"" + VALUE + "\"}}", MediaTypeRegistry.JSON); assertEquals(VALUE, builder.request().settings().get(KEY)); XContentBuilder xContent = XContentFactory.jsonBuilder() @@ -100,7 +100,7 @@ public void testSetSource() throws IOException { .endObject() .endObject(); doc.close(); - builder.setSource(docOut.toByteArray(), XContentType.JSON); + builder.setSource(docOut.toByteArray(), MediaTypeRegistry.JSON); assertEquals(VALUE, builder.request().settings().get(KEY)); Map settingsMap = new HashMap<>(); @@ -117,7 +117,7 @@ public void testSetSettings() throws IOException { builder.setSettings(Settings.builder().put(KEY, VALUE)); assertEquals(VALUE, builder.request().settings().get(KEY)); - builder.setSettings("{\"" + KEY + "\" : \"" + VALUE + "\"}", XContentType.JSON); + builder.setSettings("{\"" + KEY + "\" : \"" + VALUE + "\"}", MediaTypeRegistry.JSON); assertEquals(VALUE, builder.request().settings().get(KEY)); builder.setSettings(Settings.builder().put(KEY, VALUE)); diff --git a/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestTests.java b/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestTests.java index 2a2efbd027ac0..26f904e6da31b 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexRequestTests.java @@ -94,7 +94,7 @@ public void testTopLevelKeys() { CreateIndexRequest request = new CreateIndexRequest(); OpenSearchParseException e = expectThrows( OpenSearchParseException.class, - () -> { request.source(createIndex, XContentType.JSON); } + () -> { request.source(createIndex, MediaTypeRegistry.JSON); } ); assertEquals("unknown key [FOO_SHOULD_BE_ILLEGAL_HERE] for create index", e.getMessage()); } diff --git a/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexResponseTests.java b/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexResponseTests.java index 022c372802f9e..dc35bd76897df 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexResponseTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/create/CreateIndexResponseTests.java @@ -34,8 +34,8 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.test.AbstractSerializingTestCase; @@ -84,13 +84,13 @@ protected CreateIndexResponse doParseInstance(XContentParser parser) { public void testToXContent() { CreateIndexResponse response = new CreateIndexResponse(true, false, "index_name"); - String output = Strings.toString(XContentType.JSON, response); + String output = Strings.toString(MediaTypeRegistry.JSON, response); assertEquals("{\"acknowledged\":true,\"shards_acknowledged\":false,\"index\":\"index_name\"}", output); } public void testToAndFromXContentIndexNull() throws IOException { CreateIndexResponse response = new CreateIndexResponse(true, false, null); - String output = Strings.toString(XContentType.JSON, response); + String output = Strings.toString(MediaTypeRegistry.JSON, response); assertEquals("{\"acknowledged\":true,\"shards_acknowledged\":false,\"index\":null}", output); try (XContentParser parser = createParser(JsonXContent.jsonXContent, output)) { CreateIndexResponse parsedResponse = CreateIndexResponse.fromXContent(parser); diff --git a/server/src/test/java/org/opensearch/action/admin/indices/forcemerge/RestForceMergeActionTests.java b/server/src/test/java/org/opensearch/action/admin/indices/forcemerge/RestForceMergeActionTests.java index 821fb60c82a25..c6def72ca460c 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/forcemerge/RestForceMergeActionTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/forcemerge/RestForceMergeActionTests.java @@ -34,8 +34,8 @@ import org.opensearch.client.node.NodeClient; import org.opensearch.core.common.bytes.BytesArray; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.rest.RestRequest; import org.opensearch.rest.action.admin.indices.RestForceMergeAction; @@ -62,7 +62,7 @@ public void testBodyRejection() throws Exception { String json = JsonXContent.contentBuilder().startObject().field("max_num_segments", 1).endObject().toString(); final FakeRestRequest request = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withContent( new BytesArray(json), - XContentType.JSON + MediaTypeRegistry.JSON ).withPath("/_forcemerge").build(); IllegalArgumentException e = expectThrows( IllegalArgumentException.class, diff --git a/server/src/test/java/org/opensearch/action/admin/indices/mapping/get/GetFieldMappingsResponseTests.java b/server/src/test/java/org/opensearch/action/admin/indices/mapping/get/GetFieldMappingsResponseTests.java index 21f301674761f..00e07dae23c5a 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/mapping/get/GetFieldMappingsResponseTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/mapping/get/GetFieldMappingsResponseTests.java @@ -38,7 +38,7 @@ import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.AbstractWireSerializingTestCase; import java.io.IOException; @@ -69,7 +69,7 @@ public void testNullFieldMappingToXContent() { Map> mappings = new HashMap<>(); mappings.put("index", Collections.emptyMap()); GetFieldMappingsResponse response = new GetFieldMappingsResponse(mappings); - assertEquals("{\"index\":{\"mappings\":{}}}", Strings.toString(XContentType.JSON, response)); + assertEquals("{\"index\":{\"mappings\":{}}}", Strings.toString(MediaTypeRegistry.JSON, response)); } @Override diff --git a/server/src/test/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequestTests.java b/server/src/test/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequestTests.java index 0827f7e114bdb..552f0ee4b2410 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/mapping/put/PutMappingRequestTests.java @@ -45,6 +45,7 @@ import org.opensearch.common.collect.Tuple; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.concurrent.ThreadContext; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -72,12 +73,12 @@ public void testValidation() { assertNotNull("source validation should fail", ex); assertTrue(ex.getMessage().contains("source is missing")); - r.source("", XContentType.JSON); + r.source("", MediaTypeRegistry.JSON); ex = r.validate(); assertNotNull("source validation should fail", ex); assertTrue(ex.getMessage().contains("source is empty")); - r.source("somevalidmapping", XContentType.JSON); + r.source("somevalidmapping", MediaTypeRegistry.JSON); ex = r.validate(); assertNull("validation should succeed", ex); @@ -113,7 +114,7 @@ public void testToXContent() throws IOException { mapping.endObject(); request.source(mapping); - String actualRequestBody = Strings.toString(XContentType.JSON, request); + String actualRequestBody = Strings.toString(MediaTypeRegistry.JSON, request); String expectedRequestBody = "{\"properties\":{\"email\":{\"type\":\"text\"}}}"; assertEquals(expectedRequestBody, actualRequestBody); } @@ -121,7 +122,7 @@ public void testToXContent() throws IOException { public void testToXContentWithEmptySource() throws IOException { PutMappingRequest request = new PutMappingRequest("foo"); - String actualRequestBody = Strings.toString(XContentType.JSON, request); + String actualRequestBody = Strings.toString(MediaTypeRegistry.JSON, request); String expectedRequestBody = "{}"; assertEquals(expectedRequestBody, actualRequestBody); } @@ -143,8 +144,8 @@ public void testToAndFromXContent() throws IOException { private void assertMappingsEqual(String expected, String actual) throws IOException { try ( - XContentParser expectedJson = createParser(XContentType.JSON.xContent(), expected); - XContentParser actualJson = createParser(XContentType.JSON.xContent(), actual) + XContentParser expectedJson = createParser(MediaTypeRegistry.JSON.xContent(), expected); + XContentParser actualJson = createParser(MediaTypeRegistry.JSON.xContent(), actual) ) { assertEquals(expectedJson.mapOrdered(), actualJson.mapOrdered()); } diff --git a/server/src/test/java/org/opensearch/action/admin/indices/rollover/RolloverRequestTests.java b/server/src/test/java/org/opensearch/action/admin/indices/rollover/RolloverRequestTests.java index f65d39583336b..3a52c20b324b5 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/rollover/RolloverRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/rollover/RolloverRequestTests.java @@ -147,7 +147,7 @@ public void testTypelessMappingParsing() throws Exception { String mapping = createIndexRequest.mappings(); assertNotNull(mapping); - Map parsedMapping = XContentHelper.convertToMap(new BytesArray(mapping), false, XContentType.JSON).v2(); + Map parsedMapping = XContentHelper.convertToMap(new BytesArray(mapping), false, MediaTypeRegistry.JSON).v2(); @SuppressWarnings("unchecked") Map properties = (Map) parsedMapping.get(MapperService.SINGLE_MAPPING_NAME); diff --git a/server/src/test/java/org/opensearch/action/admin/indices/shrink/ResizeRequestTests.java b/server/src/test/java/org/opensearch/action/admin/indices/shrink/ResizeRequestTests.java index e189c3e24423a..a67faa8a45f12 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/shrink/ResizeRequestTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/shrink/ResizeRequestTests.java @@ -41,6 +41,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.index.RandomCreateIndexGenerator; import org.opensearch.test.OpenSearchTestCase; @@ -78,7 +79,7 @@ private void runTestCopySettingsValidation(final Boolean copySettings, final Con public void testToXContent() throws IOException { { ResizeRequest request = new ResizeRequest("target", "source"); - String actualRequestBody = Strings.toString(XContentType.JSON, request); + String actualRequestBody = Strings.toString(MediaTypeRegistry.JSON, request); assertEquals("{\"settings\":{},\"aliases\":{}}", actualRequestBody); } { @@ -93,7 +94,7 @@ public void testToXContent() throws IOException { settings.put(SETTING_NUMBER_OF_SHARDS, 10); target.settings(settings); request.setTargetIndex(target); - String actualRequestBody = Strings.toString(XContentType.JSON, request); + String actualRequestBody = Strings.toString(MediaTypeRegistry.JSON, request); String expectedRequestBody = "{\"settings\":{\"index\":{\"number_of_shards\":\"10\"}}," + "\"aliases\":{\"test_alias\":{\"filter\":{\"term\":{\"year\":2016}},\"routing\":\"1\",\"is_write_index\":true}}}"; assertEquals(expectedRequestBody, actualRequestBody); diff --git a/server/src/test/java/org/opensearch/action/admin/indices/shrink/ResizeResponseTests.java b/server/src/test/java/org/opensearch/action/admin/indices/shrink/ResizeResponseTests.java index 7d97a4285f5da..f984c969e4b70 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/shrink/ResizeResponseTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/shrink/ResizeResponseTests.java @@ -34,7 +34,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.io.stream.Writeable; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.test.AbstractSerializingTestCase; @@ -42,7 +42,7 @@ public class ResizeResponseTests extends AbstractSerializingTestCase()); - String output = Strings.toString(XContentType.JSON, response); + String output = Strings.toString(MediaTypeRegistry.JSON, response); assertEquals("{\"_shards\":{\"total\":10,\"successful\":10,\"failed\":0},\"valid\":true}", output); } } diff --git a/server/src/test/java/org/opensearch/action/bulk/BulkProcessorTests.java b/server/src/test/java/org/opensearch/action/bulk/BulkProcessorTests.java index 0111c8d6e3132..c8a171df6cadc 100644 --- a/server/src/test/java/org/opensearch/action/bulk/BulkProcessorTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/BulkProcessorTests.java @@ -42,7 +42,7 @@ import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.concurrent.ThreadContext; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchTestCase; import org.opensearch.threadpool.Scheduler; import org.opensearch.threadpool.TestThreadPool; @@ -208,7 +208,7 @@ public void testConcurrentExecutions() throws Exception { if (randomBoolean()) { bulkProcessor.add(indexRequest); } else { - bulkProcessor.add(bytesReference, null, null, XContentType.JSON); + bulkProcessor.add(bytesReference, null, null, MediaTypeRegistry.JSON); } } catch (Exception e) { throw ExceptionsHelper.convertToRuntime(e); @@ -334,7 +334,7 @@ public void testConcurrentExecutionsWithFlush() throws Exception { if (randomBoolean()) { bulkProcessor.add(indexRequest); } else { - bulkProcessor.add(bytesReference, null, null, XContentType.JSON); + bulkProcessor.add(bytesReference, null, null, MediaTypeRegistry.JSON); } } catch (Exception e) { throw ExceptionsHelper.convertToRuntime(e); diff --git a/server/src/test/java/org/opensearch/action/bulk/BulkRequestModifierTests.java b/server/src/test/java/org/opensearch/action/bulk/BulkRequestModifierTests.java index e68d7d7d0d447..31c6472ad46b3 100644 --- a/server/src/test/java/org/opensearch/action/bulk/BulkRequestModifierTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/BulkRequestModifierTests.java @@ -36,8 +36,8 @@ import org.opensearch.action.DocWriteRequest; import org.opensearch.action.index.IndexRequest; import org.opensearch.action.index.IndexResponse; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.shard.ShardId; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchTestCase; import org.hamcrest.Matchers; @@ -58,7 +58,7 @@ public void testBulkRequestModifier() { int numRequests = scaledRandomIntBetween(8, 64); BulkRequest bulkRequest = new BulkRequest(); for (int i = 0; i < numRequests; i++) { - bulkRequest.add(new IndexRequest("_index").id(String.valueOf(i)).source("{}", XContentType.JSON)); + bulkRequest.add(new IndexRequest("_index").id(String.valueOf(i)).source("{}", MediaTypeRegistry.JSON)); } CaptureActionListener actionListener = new CaptureActionListener(); TransportBulkAction.BulkRequestModifier bulkRequestModifier = new TransportBulkAction.BulkRequestModifier(bulkRequest); diff --git a/server/src/test/java/org/opensearch/action/bulk/BulkRequestParserTests.java b/server/src/test/java/org/opensearch/action/bulk/BulkRequestParserTests.java index e0e9ea73d9291..4f07c098b0869 100644 --- a/server/src/test/java/org/opensearch/action/bulk/BulkRequestParserTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/BulkRequestParserTests.java @@ -34,7 +34,7 @@ import org.opensearch.action.index.IndexRequest; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchTestCase; import org.hamcrest.Matchers; @@ -49,7 +49,7 @@ public void testIndexRequest() throws IOException { BytesArray request = new BytesArray("{ \"index\":{ \"_id\": \"bar\" } }\n{}\n"); BulkRequestParser parser = new BulkRequestParser(); final AtomicBoolean parsed = new AtomicBoolean(); - parser.parse(request, "foo", null, null, null, null, false, XContentType.JSON, indexRequest -> { + parser.parse(request, "foo", null, null, null, null, false, MediaTypeRegistry.JSON, indexRequest -> { assertFalse(parsed.get()); assertEquals("foo", indexRequest.index()); assertEquals("bar", indexRequest.id()); @@ -58,17 +58,17 @@ public void testIndexRequest() throws IOException { }, req -> fail(), req -> fail()); assertTrue(parsed.get()); - parser.parse(request, "foo", null, null, null, true, false, XContentType.JSON, indexRequest -> { + parser.parse(request, "foo", null, null, null, true, false, MediaTypeRegistry.JSON, indexRequest -> { assertTrue(indexRequest.isRequireAlias()); }, req -> fail(), req -> fail()); request = new BytesArray("{ \"index\":{ \"_id\": \"bar\", \"require_alias\": true } }\n{}\n"); - parser.parse(request, "foo", null, null, null, null, false, XContentType.JSON, indexRequest -> { + parser.parse(request, "foo", null, null, null, null, false, MediaTypeRegistry.JSON, indexRequest -> { assertTrue(indexRequest.isRequireAlias()); }, req -> fail(), req -> fail()); request = new BytesArray("{ \"index\":{ \"_id\": \"bar\", \"require_alias\": false } }\n{}\n"); - parser.parse(request, "foo", null, null, null, true, false, XContentType.JSON, indexRequest -> { + parser.parse(request, "foo", null, null, null, true, false, MediaTypeRegistry.JSON, indexRequest -> { assertFalse(indexRequest.isRequireAlias()); }, req -> fail(), req -> fail()); } @@ -77,7 +77,7 @@ public void testDeleteRequest() throws IOException { BytesArray request = new BytesArray("{ \"delete\":{ \"_id\": \"bar\" } }\n"); BulkRequestParser parser = new BulkRequestParser(); final AtomicBoolean parsed = new AtomicBoolean(); - parser.parse(request, "foo", null, null, null, null, false, XContentType.JSON, req -> fail(), req -> fail(), deleteRequest -> { + parser.parse(request, "foo", null, null, null, null, false, MediaTypeRegistry.JSON, req -> fail(), req -> fail(), deleteRequest -> { assertFalse(parsed.get()); assertEquals("foo", deleteRequest.index()); assertEquals("bar", deleteRequest.id()); @@ -90,7 +90,7 @@ public void testUpdateRequest() throws IOException { BytesArray request = new BytesArray("{ \"update\":{ \"_id\": \"bar\" } }\n{}\n"); BulkRequestParser parser = new BulkRequestParser(); final AtomicBoolean parsed = new AtomicBoolean(); - parser.parse(request, "foo", null, null, null, null, false, XContentType.JSON, req -> fail(), updateRequest -> { + parser.parse(request, "foo", null, null, null, null, false, MediaTypeRegistry.JSON, req -> fail(), updateRequest -> { assertFalse(parsed.get()); assertEquals("foo", updateRequest.index()); assertEquals("bar", updateRequest.id()); @@ -99,17 +99,17 @@ public void testUpdateRequest() throws IOException { }, req -> fail()); assertTrue(parsed.get()); - parser.parse(request, "foo", null, null, null, true, false, XContentType.JSON, req -> fail(), updateRequest -> { + parser.parse(request, "foo", null, null, null, true, false, MediaTypeRegistry.JSON, req -> fail(), updateRequest -> { assertTrue(updateRequest.isRequireAlias()); }, req -> fail()); request = new BytesArray("{ \"update\":{ \"_id\": \"bar\", \"require_alias\": true } }\n{}\n"); - parser.parse(request, "foo", null, null, null, null, false, XContentType.JSON, req -> fail(), updateRequest -> { + parser.parse(request, "foo", null, null, null, null, false, MediaTypeRegistry.JSON, req -> fail(), updateRequest -> { assertTrue(updateRequest.isRequireAlias()); }, req -> fail()); request = new BytesArray("{ \"update\":{ \"_id\": \"bar\", \"require_alias\": false } }\n{}\n"); - parser.parse(request, "foo", null, null, null, true, false, XContentType.JSON, req -> fail(), updateRequest -> { + parser.parse(request, "foo", null, null, null, true, false, MediaTypeRegistry.JSON, req -> fail(), updateRequest -> { assertFalse(updateRequest.isRequireAlias()); }, req -> fail()); } @@ -127,7 +127,7 @@ public void testBarfOnLackOfTrailingNewline() { null, null, false, - XContentType.JSON, + MediaTypeRegistry.JSON, indexRequest -> fail(), req -> fail(), req -> fail() @@ -142,7 +142,19 @@ public void testFailOnExplicitIndex() { IllegalArgumentException ex = expectThrows( IllegalArgumentException.class, - () -> parser.parse(request, null, null, null, null, null, false, XContentType.JSON, req -> fail(), req -> fail(), req -> fail()) + () -> parser.parse( + request, + null, + null, + null, + null, + null, + false, + MediaTypeRegistry.JSON, + req -> fail(), + req -> fail(), + req -> fail() + ) ); assertEquals("explicit index in bulk is not allowed", ex.getMessage()); } @@ -162,7 +174,7 @@ public void testParseDeduplicatesParameterStrings() throws IOException { null, null, true, - XContentType.JSON, + MediaTypeRegistry.JSON, indexRequest -> indexRequests.add(indexRequest), req -> fail(), req -> fail() @@ -189,7 +201,7 @@ public void testFailOnUnsupportedAction() { null, true, false, - XContentType.JSON, + MediaTypeRegistry.JSON, req -> fail(), req -> fail(), req -> fail() diff --git a/server/src/test/java/org/opensearch/action/bulk/BulkRequestTests.java b/server/src/test/java/org/opensearch/action/bulk/BulkRequestTests.java index 2f2c9b2be9e50..b3a5cff0041a7 100644 --- a/server/src/test/java/org/opensearch/action/bulk/BulkRequestTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/BulkRequestTests.java @@ -71,7 +71,7 @@ public class BulkRequestTests extends OpenSearchTestCase { public void testSimpleBulk1() throws Exception { String bulkAction = copyToStringFromClasspath("/org/opensearch/action/bulk/simple-bulk.json"); BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); assertThat(bulkRequest.numberOfActions(), equalTo(3)); assertThat(((IndexRequest) bulkRequest.requests().get(0)).source(), equalTo(new BytesArray("{ \"field1\" : \"value1\" }"))); assertThat(bulkRequest.requests().get(1), instanceOf(DeleteRequest.class)); @@ -81,13 +81,13 @@ public void testSimpleBulk1() throws Exception { public void testSimpleBulkWithCarriageReturn() throws Exception { String bulkAction = "{ \"index\":{\"_index\":\"test\",\"_id\":\"1\"} }\r\n{ \"field1\" : \"value1\" }\r\n"; BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); assertThat(bulkRequest.numberOfActions(), equalTo(1)); assertThat(((IndexRequest) bulkRequest.requests().get(0)).source(), equalTo(new BytesArray("{ \"field1\" : \"value1\" }"))); Map sourceMap = XContentHelper.convertToMap( ((IndexRequest) bulkRequest.requests().get(0)).source(), false, - XContentType.JSON + MediaTypeRegistry.JSON ).v2(); assertEquals("value1", sourceMap.get("field1")); } @@ -95,21 +95,21 @@ public void testSimpleBulkWithCarriageReturn() throws Exception { public void testSimpleBulk2() throws Exception { String bulkAction = copyToStringFromClasspath("/org/opensearch/action/bulk/simple-bulk2.json"); BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); assertThat(bulkRequest.numberOfActions(), equalTo(3)); } public void testSimpleBulk3() throws Exception { String bulkAction = copyToStringFromClasspath("/org/opensearch/action/bulk/simple-bulk3.json"); BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); assertThat(bulkRequest.numberOfActions(), equalTo(3)); } public void testSimpleBulk4() throws Exception { String bulkAction = copyToStringFromClasspath("/org/opensearch/action/bulk/simple-bulk4.json"); BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); assertThat(bulkRequest.numberOfActions(), equalTo(4)); assertThat(bulkRequest.requests().get(0).id(), equalTo("1")); assertThat(((UpdateRequest) bulkRequest.requests().get(0)).retryOnConflict(), equalTo(2)); @@ -131,12 +131,12 @@ public void testBulkAllowExplicitIndex() throws Exception { String bulkAction1 = copyToStringFromClasspath("/org/opensearch/action/bulk/simple-bulk.json"); Exception ex = expectThrows( Exception.class, - () -> new BulkRequest().add(new BytesArray(bulkAction1.getBytes(StandardCharsets.UTF_8)), null, false, XContentType.JSON) + () -> new BulkRequest().add(new BytesArray(bulkAction1.getBytes(StandardCharsets.UTF_8)), null, false, MediaTypeRegistry.JSON) ); assertEquals("explicit index in bulk is not allowed", ex.getMessage()); String bulkAction = copyToStringFromClasspath("/org/opensearch/action/bulk/simple-bulk5.json"); - new BulkRequest().add(new BytesArray(bulkAction.getBytes(StandardCharsets.UTF_8)), "test", false, XContentType.JSON); + new BulkRequest().add(new BytesArray(bulkAction.getBytes(StandardCharsets.UTF_8)), "test", false, MediaTypeRegistry.JSON); } public void testBulkAddIterable() { @@ -157,7 +157,7 @@ public void testSimpleBulk6() throws Exception { BulkRequest bulkRequest = new BulkRequest(); ParsingException exc = expectThrows( ParsingException.class, - () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON) + () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON) ); assertThat(exc.getMessage(), containsString("Unknown key for a VALUE_STRING in [hello]")); } @@ -167,7 +167,7 @@ public void testSimpleBulk7() throws Exception { BulkRequest bulkRequest = new BulkRequest(); IllegalArgumentException exc = expectThrows( IllegalArgumentException.class, - () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON) + () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON) ); assertThat( exc.getMessage(), @@ -180,7 +180,7 @@ public void testSimpleBulk8() throws Exception { BulkRequest bulkRequest = new BulkRequest(); IllegalArgumentException exc = expectThrows( IllegalArgumentException.class, - () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON) + () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON) ); assertThat(exc.getMessage(), containsString("Action/metadata line [3] contains an unknown parameter [_foo]")); } @@ -190,7 +190,7 @@ public void testSimpleBulk9() throws Exception { BulkRequest bulkRequest = new BulkRequest(); IllegalArgumentException exc = expectThrows( IllegalArgumentException.class, - () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON) + () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON) ); assertThat( exc.getMessage(), @@ -201,7 +201,7 @@ public void testSimpleBulk9() throws Exception { public void testSimpleBulk10() throws Exception { String bulkAction = copyToStringFromClasspath("/org/opensearch/action/bulk/simple-bulk10.json"); BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); assertThat(bulkRequest.numberOfActions(), equalTo(9)); } @@ -210,7 +210,7 @@ public void testBulkActionShouldNotContainArray() throws Exception { BulkRequest bulkRequest = new BulkRequest(); IllegalArgumentException exc = expectThrows( IllegalArgumentException.class, - () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON) + () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON) ); assertEquals( exc.getMessage(), @@ -240,7 +240,7 @@ public void testBulkEmptyObject() throws Exception { BulkRequest bulkRequest = new BulkRequest(); IllegalArgumentException exc = expectThrows( IllegalArgumentException.class, - () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON) + () -> bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON) ); assertThat( exc.getMessage(), @@ -256,8 +256,8 @@ public void testBulkRequestWithRefresh() throws Exception { // We force here a "type is missing" validation error bulkRequest.add(new DeleteRequest("index", "id")); bulkRequest.add(new DeleteRequest("index", "id").setRefreshPolicy(RefreshPolicy.IMMEDIATE)); - bulkRequest.add(new UpdateRequest("index", "id").doc("{}", XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE)); - bulkRequest.add(new IndexRequest("index").id("id").source("{}", XContentType.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE)); + bulkRequest.add(new UpdateRequest("index", "id").doc("{}", MediaTypeRegistry.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE)); + bulkRequest.add(new IndexRequest("index").id("id").source("{}", MediaTypeRegistry.JSON).setRefreshPolicy(RefreshPolicy.IMMEDIATE)); ActionRequestValidationException validate = bulkRequest.validate(); assertThat(validate, notNullValue()); assertThat(validate.validationErrors(), not(empty())); @@ -408,7 +408,7 @@ public void testBulkTerminatedByNewline() throws Exception { String bulkAction = copyToStringFromClasspath("/org/opensearch/action/bulk/simple-bulk11.json"); IllegalArgumentException expectThrows = expectThrows( IllegalArgumentException.class, - () -> new BulkRequest().add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON) + () -> new BulkRequest().add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON) ); assertEquals("The bulk request must be terminated by a newline [\\n]", expectThrows.getMessage()); @@ -419,7 +419,7 @@ public void testBulkTerminatedByNewline() throws Exception { 0, bulkActionWithNewLine.length(), null, - XContentType.JSON + MediaTypeRegistry.JSON ); assertEquals(3, bulkRequestWithNewLine.numberOfActions()); } diff --git a/server/src/test/java/org/opensearch/action/bulk/BulkResponseTests.java b/server/src/test/java/org/opensearch/action/bulk/BulkResponseTests.java index 7c758fb25ce85..6b8857c956348 100644 --- a/server/src/test/java/org/opensearch/action/bulk/BulkResponseTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/BulkResponseTests.java @@ -51,7 +51,7 @@ import static org.opensearch.OpenSearchExceptionTests.randomExceptions; import static org.opensearch.action.bulk.BulkItemResponseTests.assertBulkItemResponse; import static org.opensearch.action.bulk.BulkResponse.NO_INGEST_TOOK; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; public class BulkResponseTests extends OpenSearchTestCase { diff --git a/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionTookTests.java b/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionTookTests.java index 2361b69e9b82c..e10b848a39431 100644 --- a/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionTookTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/TransportBulkActionTookTests.java @@ -51,8 +51,8 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.util.concurrent.AtomicArray; import org.opensearch.common.util.concurrent.ThreadContext; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexNotFoundException; import org.opensearch.index.IndexingPressureService; import org.opensearch.indices.SystemIndices; @@ -217,7 +217,7 @@ private void runTestTook(boolean controlled) throws Exception { bulkAction = Strings.replace(bulkAction, "\r\n", "\n"); } BulkRequest bulkRequest = new BulkRequest(); - bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, XContentType.JSON); + bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, MediaTypeRegistry.JSON); AtomicLong expected = new AtomicLong(); TransportBulkAction action = createAction(controlled, expected); action.doExecute(null, bulkRequest, new ActionListener() { diff --git a/server/src/test/java/org/opensearch/action/delete/DeleteResponseTests.java b/server/src/test/java/org/opensearch/action/delete/DeleteResponseTests.java index 58dca0bebc0f1..c6ecb8608ff5e 100644 --- a/server/src/test/java/org/opensearch/action/delete/DeleteResponseTests.java +++ b/server/src/test/java/org/opensearch/action/delete/DeleteResponseTests.java @@ -36,6 +36,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.collect.Tuple; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -56,7 +57,7 @@ public class DeleteResponseTests extends OpenSearchTestCase { public void testToXContent() { { DeleteResponse response = new DeleteResponse(new ShardId("index", "index_uuid", 0), "id", 3, 17, 5, true); - String output = Strings.toString(XContentType.JSON, response); + String output = Strings.toString(MediaTypeRegistry.JSON, response); assertEquals( "{\"_index\":\"index\",\"_id\":\"id\",\"_version\":5,\"result\":\"deleted\"," + "\"_shards\":null,\"_seq_no\":3,\"_primary_term\":17}", @@ -67,7 +68,7 @@ public void testToXContent() { DeleteResponse response = new DeleteResponse(new ShardId("index", "index_uuid", 0), "id", -1, 0, 7, true); response.setForcedRefresh(true); response.setShardInfo(new ReplicationResponse.ShardInfo(10, 5)); - String output = Strings.toString(XContentType.JSON, response); + String output = Strings.toString(MediaTypeRegistry.JSON, response); assertEquals( "{\"_index\":\"index\",\"_id\":\"id\",\"_version\":7,\"result\":\"deleted\"," + "\"forced_refresh\":true,\"_shards\":{\"total\":10,\"successful\":5,\"failed\":0}}", diff --git a/server/src/test/java/org/opensearch/action/explain/ExplainResponseTests.java b/server/src/test/java/org/opensearch/action/explain/ExplainResponseTests.java index 14f2a5c94bcd0..b34702e0a5b4d 100644 --- a/server/src/test/java/org/opensearch/action/explain/ExplainResponseTests.java +++ b/server/src/test/java/org/opensearch/action/explain/ExplainResponseTests.java @@ -41,7 +41,6 @@ import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.get.GetResult; import org.opensearch.test.AbstractSerializingTestCase; import org.opensearch.test.RandomObjects; @@ -114,7 +113,7 @@ public void testToXContent() throws IOException { ); ExplainResponse response = new ExplainResponse(index, id, exist, explanation, getResult); - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); response.toXContent(builder, ToXContent.EMPTY_PARAMS); String generatedResponse = BytesReference.bytes(builder).utf8ToString().replaceAll("\\s+", ""); diff --git a/server/src/test/java/org/opensearch/action/fieldcaps/MergedFieldCapabilitiesResponseTests.java b/server/src/test/java/org/opensearch/action/fieldcaps/MergedFieldCapabilitiesResponseTests.java index d76ed86ed490e..f196ba16a2584 100644 --- a/server/src/test/java/org/opensearch/action/fieldcaps/MergedFieldCapabilitiesResponseTests.java +++ b/server/src/test/java/org/opensearch/action/fieldcaps/MergedFieldCapabilitiesResponseTests.java @@ -38,7 +38,6 @@ import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.AbstractSerializingTestCase; import java.io.IOException; @@ -125,7 +124,7 @@ protected Predicate getRandomFieldsExcludeFilter() { public void testToXContent() throws IOException { FieldCapabilitiesResponse response = createSimpleResponse(); - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); response.toXContent(builder, ToXContent.EMPTY_PARAMS); String generatedResponse = BytesReference.bytes(builder).utf8ToString(); diff --git a/server/src/test/java/org/opensearch/action/get/GetResponseTests.java b/server/src/test/java/org/opensearch/action/get/GetResponseTests.java index 4299c330ad3ec..adf280a29380e 100644 --- a/server/src/test/java/org/opensearch/action/get/GetResponseTests.java +++ b/server/src/test/java/org/opensearch/action/get/GetResponseTests.java @@ -38,6 +38,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.collect.Tuple; import org.opensearch.common.document.DocumentField; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -48,7 +49,7 @@ import java.util.Collections; import java.util.function.Predicate; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.index.get.GetResultTests.copyGetResult; import static org.opensearch.index.get.GetResultTests.mutateGetResult; import static org.opensearch.index.get.GetResultTests.randomGetResult; @@ -118,7 +119,7 @@ public void testToXContent() { null ) ); - String output = Strings.toString(XContentType.JSON, getResponse); + String output = Strings.toString(MediaTypeRegistry.JSON, getResponse); assertEquals( "{\"_index\":\"index\",\"_id\":\"id\",\"_version\":1,\"_seq_no\":0,\"_primary_term\":1," + "\"found\":true,\"_source\":{ \"field1\" : \"value1\", \"field2\":\"value2\"},\"fields\":{\"field1\":[\"value1\"]}}", @@ -127,7 +128,7 @@ public void testToXContent() { } { GetResponse getResponse = new GetResponse(new GetResult("index", "id", UNASSIGNED_SEQ_NO, 0, 1, false, null, null, null)); - String output = Strings.toString(XContentType.JSON, getResponse); + String output = Strings.toString(MediaTypeRegistry.JSON, getResponse); assertEquals("{\"_index\":\"index\",\"_id\":\"id\",\"found\":false}", output); } } @@ -155,7 +156,7 @@ public void testToString() { public void testEqualsAndHashcode() { checkEqualsAndHashCode( - new GetResponse(randomGetResult(XContentType.JSON).v1()), + new GetResponse(randomGetResult(MediaTypeRegistry.JSON).v1()), GetResponseTests::copyGetResponse, GetResponseTests::mutateGetResponse ); diff --git a/server/src/test/java/org/opensearch/action/get/TransportMultiGetActionTests.java b/server/src/test/java/org/opensearch/action/get/TransportMultiGetActionTests.java index 9e467aff710df..39e8f1af8c331 100644 --- a/server/src/test/java/org/opensearch/action/get/TransportMultiGetActionTests.java +++ b/server/src/test/java/org/opensearch/action/get/TransportMultiGetActionTests.java @@ -53,9 +53,9 @@ import org.opensearch.common.util.concurrent.ThreadContext; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.Index; import org.opensearch.core.index.shard.ShardId; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.indices.IndicesService; import org.opensearch.tasks.Task; import org.opensearch.tasks.TaskId; @@ -139,7 +139,7 @@ public TaskManager getTaskManager() { .endObject() ), true, - XContentType.JSON + MediaTypeRegistry.JSON ) ) ) @@ -164,7 +164,7 @@ public TaskManager getTaskManager() { .endObject() ), true, - XContentType.JSON + MediaTypeRegistry.JSON ) ) ) diff --git a/server/src/test/java/org/opensearch/action/index/IndexRequestBuilderTests.java b/server/src/test/java/org/opensearch/action/index/IndexRequestBuilderTests.java index 5c3fba48d6215..5665040bb5e7f 100644 --- a/server/src/test/java/org/opensearch/action/index/IndexRequestBuilderTests.java +++ b/server/src/test/java/org/opensearch/action/index/IndexRequestBuilderTests.java @@ -32,10 +32,10 @@ package org.opensearch.action.index; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.OpenSearchTestCase; import org.opensearch.test.client.NoOpClient; import org.junit.After; @@ -74,7 +74,7 @@ public void testSetSource() throws Exception { indexRequestBuilder.setSource(source); assertEquals(EXPECTED_SOURCE, XContentHelper.convertToJson(indexRequestBuilder.request().source(), true)); - indexRequestBuilder.setSource(source, XContentType.JSON); + indexRequestBuilder.setSource(source, MediaTypeRegistry.JSON); assertEquals(EXPECTED_SOURCE, XContentHelper.convertToJson(indexRequestBuilder.request().source(), true)); indexRequestBuilder.setSource("SomeKey", "SomeValue"); @@ -87,7 +87,7 @@ public void testSetSource() throws Exception { ByteArrayOutputStream docOut = new ByteArrayOutputStream(); XContentBuilder doc = XContentFactory.jsonBuilder(docOut).startObject().field("SomeKey", "SomeValue").endObject(); doc.close(); - indexRequestBuilder.setSource(docOut.toByteArray(), XContentType.JSON); + indexRequestBuilder.setSource(docOut.toByteArray(), MediaTypeRegistry.JSON); assertEquals( EXPECTED_SOURCE, XContentHelper.convertToJson(indexRequestBuilder.request().source(), true, indexRequestBuilder.request().getContentType()) diff --git a/server/src/test/java/org/opensearch/action/index/IndexRequestTests.java b/server/src/test/java/org/opensearch/action/index/IndexRequestTests.java index c4d3b17de1a5a..66c371db025a3 100644 --- a/server/src/test/java/org/opensearch/action/index/IndexRequestTests.java +++ b/server/src/test/java/org/opensearch/action/index/IndexRequestTests.java @@ -40,7 +40,7 @@ import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.common.unit.ByteSizeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.VersionType; import org.opensearch.index.seqno.SequenceNumbers; import org.opensearch.core.index.shard.ShardId; @@ -99,19 +99,19 @@ public void testCreateOperationRejectsVersions() { public void testIndexingRejectsLongIds() { String id = randomAlphaOfLength(511); IndexRequest request = new IndexRequest("index").id(id); - request.source("{}", XContentType.JSON); + request.source("{}", MediaTypeRegistry.JSON); ActionRequestValidationException validate = request.validate(); assertNull(validate); id = randomAlphaOfLength(512); request = new IndexRequest("index").id(id); - request.source("{}", XContentType.JSON); + request.source("{}", MediaTypeRegistry.JSON); validate = request.validate(); assertNull(validate); id = randomAlphaOfLength(513); request = new IndexRequest("index").id(id); - request.source("{}", XContentType.JSON); + request.source("{}", MediaTypeRegistry.JSON); validate = request.validate(); assertThat(validate, notNullValue()); assertThat(validate.getMessage(), containsString("id [" + id + "] is too long, must be no longer than 512 bytes but was: 513")); @@ -182,15 +182,15 @@ public void testIndexResponse() { public void testIndexRequestXContentSerialization() throws IOException { IndexRequest indexRequest = new IndexRequest("foo").id("1"); boolean isRequireAlias = randomBoolean(); - indexRequest.source("{}", XContentType.JSON); + indexRequest.source("{}", MediaTypeRegistry.JSON); indexRequest.setRequireAlias(isRequireAlias); - assertEquals(XContentType.JSON, indexRequest.getContentType()); + assertEquals(MediaTypeRegistry.JSON, indexRequest.getContentType()); BytesStreamOutput out = new BytesStreamOutput(); indexRequest.writeTo(out); StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes); IndexRequest serialized = new IndexRequest(in); - assertEquals(XContentType.JSON, serialized.getContentType()); + assertEquals(MediaTypeRegistry.JSON, serialized.getContentType()); assertEquals(new BytesArray("{}"), serialized.source()); assertEquals(isRequireAlias, serialized.isRequireAlias()); } @@ -215,11 +215,11 @@ public void testToStringSizeLimit() throws UnsupportedEncodingException { IndexRequest request = new IndexRequest("index"); String source = "{\"name\":\"value\"}"; - request.source(source, XContentType.JSON); + request.source(source, MediaTypeRegistry.JSON); assertEquals("index {[index][null], source[" + source + "]}", request.toString()); source = "{\"name\":\"" + randomUnicodeOfLength(IndexRequest.MAX_SOURCE_LENGTH_IN_TOSTRING) + "\"}"; - request.source(source, XContentType.JSON); + request.source(source, MediaTypeRegistry.JSON); int actualBytes = source.getBytes("UTF-8").length; assertEquals( "index {[index][null], source[n/a, actual length: [" @@ -233,7 +233,7 @@ public void testToStringSizeLimit() throws UnsupportedEncodingException { public void testRejectsEmptyStringPipeline() { IndexRequest request = new IndexRequest("index"); - request.source("{}", XContentType.JSON); + request.source("{}", MediaTypeRegistry.JSON); request.setPipeline(""); ActionRequestValidationException validate = request.validate(); assertThat(validate, notNullValue()); diff --git a/server/src/test/java/org/opensearch/action/index/IndexResponseTests.java b/server/src/test/java/org/opensearch/action/index/IndexResponseTests.java index ba729d0d3593c..6d268f282f6a0 100644 --- a/server/src/test/java/org/opensearch/action/index/IndexResponseTests.java +++ b/server/src/test/java/org/opensearch/action/index/IndexResponseTests.java @@ -37,6 +37,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.collect.Tuple; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -57,7 +58,7 @@ public class IndexResponseTests extends OpenSearchTestCase { public void testToXContent() { { IndexResponse indexResponse = new IndexResponse(new ShardId("index", "index_uuid", 0), "id", 3, 17, 5, true); - String output = Strings.toString(XContentType.JSON, indexResponse); + String output = Strings.toString(MediaTypeRegistry.JSON, indexResponse); assertEquals( "{\"_index\":\"index\",\"_id\":\"id\",\"_version\":5,\"result\":\"created\",\"_shards\":null," + "\"_seq_no\":3,\"_primary_term\":17}", @@ -68,7 +69,7 @@ public void testToXContent() { IndexResponse indexResponse = new IndexResponse(new ShardId("index", "index_uuid", 0), "id", -1, 17, 7, true); indexResponse.setForcedRefresh(true); indexResponse.setShardInfo(new ReplicationResponse.ShardInfo(10, 5)); - String output = Strings.toString(XContentType.JSON, indexResponse); + String output = Strings.toString(MediaTypeRegistry.JSON, indexResponse); assertEquals( "{\"_index\":\"index\",\"_id\":\"id\",\"_version\":7,\"result\":\"created\"," + "\"forced_refresh\":true,\"_shards\":{\"total\":10,\"successful\":5,\"failed\":0}}", diff --git a/server/src/test/java/org/opensearch/action/ingest/PutPipelineRequestTests.java b/server/src/test/java/org/opensearch/action/ingest/PutPipelineRequestTests.java index 336ec67546dc5..e024f6b598ab6 100644 --- a/server/src/test/java/org/opensearch/action/ingest/PutPipelineRequestTests.java +++ b/server/src/test/java/org/opensearch/action/ingest/PutPipelineRequestTests.java @@ -36,6 +36,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.core.common.io.stream.StreamInput; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentType; @@ -48,15 +49,19 @@ public class PutPipelineRequestTests extends OpenSearchTestCase { public void testSerializationWithXContent() throws IOException { - PutPipelineRequest request = new PutPipelineRequest("1", new BytesArray("{}".getBytes(StandardCharsets.UTF_8)), XContentType.JSON); - assertEquals(XContentType.JSON, request.getMediaType()); + PutPipelineRequest request = new PutPipelineRequest( + "1", + new BytesArray("{}".getBytes(StandardCharsets.UTF_8)), + MediaTypeRegistry.JSON + ); + assertEquals(MediaTypeRegistry.JSON, request.getMediaType()); BytesStreamOutput output = new BytesStreamOutput(); request.writeTo(output); StreamInput in = StreamInput.wrap(output.bytes().toBytesRef().bytes); PutPipelineRequest serialized = new PutPipelineRequest(in); - assertEquals(XContentType.JSON, serialized.getMediaType()); + assertEquals(MediaTypeRegistry.JSON, serialized.getMediaType()); assertEquals("{}", serialized.getSource().utf8ToString()); } diff --git a/server/src/test/java/org/opensearch/action/ingest/SimulatePipelineRequestTests.java b/server/src/test/java/org/opensearch/action/ingest/SimulatePipelineRequestTests.java index 35cbc83661c8e..20710155b48cc 100644 --- a/server/src/test/java/org/opensearch/action/ingest/SimulatePipelineRequestTests.java +++ b/server/src/test/java/org/opensearch/action/ingest/SimulatePipelineRequestTests.java @@ -35,7 +35,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.core.common.io.stream.StreamInput; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchTestCase; import java.io.IOException; @@ -46,7 +46,7 @@ public class SimulatePipelineRequestTests extends OpenSearchTestCase { public void testSerialization() throws IOException { - SimulatePipelineRequest request = new SimulatePipelineRequest(new BytesArray(""), XContentType.JSON); + SimulatePipelineRequest request = new SimulatePipelineRequest(new BytesArray(""), MediaTypeRegistry.JSON); // Sometimes we set an id if (randomBoolean()) { request.setId(randomAlphaOfLengthBetween(1, 10)); @@ -69,16 +69,16 @@ public void testSerialization() throws IOException { public void testSerializationWithXContent() throws IOException { SimulatePipelineRequest request = new SimulatePipelineRequest( new BytesArray("{}".getBytes(StandardCharsets.UTF_8)), - XContentType.JSON + MediaTypeRegistry.JSON ); - assertEquals(XContentType.JSON, request.getXContentType()); + assertEquals(MediaTypeRegistry.JSON, request.getXContentType()); BytesStreamOutput output = new BytesStreamOutput(); request.writeTo(output); StreamInput in = StreamInput.wrap(output.bytes().toBytesRef().bytes); SimulatePipelineRequest serialized = new SimulatePipelineRequest(in); - assertEquals(XContentType.JSON, serialized.getXContentType()); + assertEquals(MediaTypeRegistry.JSON, serialized.getXContentType()); assertEquals("{}", serialized.getSource().utf8ToString()); } } diff --git a/server/src/test/java/org/opensearch/action/search/MultiSearchRequestTests.java b/server/src/test/java/org/opensearch/action/search/MultiSearchRequestTests.java index d4b792a0ca6af..e14c7c39084f2 100644 --- a/server/src/test/java/org/opensearch/action/search/MultiSearchRequestTests.java +++ b/server/src/test/java/org/opensearch/action/search/MultiSearchRequestTests.java @@ -43,6 +43,8 @@ import org.opensearch.core.common.io.stream.NamedWriteableRegistry; import org.opensearch.common.logging.DeprecationLogger; import org.opensearch.common.unit.TimeValue; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; @@ -120,7 +122,7 @@ public void testFailWithUnknownKey() { + "{\"query\" : {\"match_all\" :{}}}\r\n"; FakeRestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(requestContent), - XContentType.JSON + MediaTypeRegistry.JSON ).build(); IllegalArgumentException ex = expectThrows( IllegalArgumentException.class, @@ -134,7 +136,7 @@ public void testSimpleAddWithCarriageReturn() throws Exception { + "{\"query\" : {\"match_all\" :{}}}\r\n"; FakeRestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(requestContent), - XContentType.JSON + MediaTypeRegistry.JSON ).build(); MultiSearchRequest request = RestMultiSearchAction.parseRequest(restRequest, null, true); assertThat(request.requests().size(), equalTo(1)); @@ -152,7 +154,7 @@ public void testCancelAfterIntervalAtParentAndFewChildRequest() throws Exception + "{\"query\" : {\"match_all\" :{}}}\r\n"; FakeRestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(requestContent), - XContentType.JSON + MediaTypeRegistry.JSON ).withParams(Collections.singletonMap("cancel_after_time_interval", "20s")).build(); MultiSearchRequest request = RestMultiSearchAction.parseRequest(restRequest, null, true); assertThat(request.requests().size(), equalTo(2)); @@ -169,7 +171,7 @@ public void testOnlyParentMSearchRequestWithCancelAfterTimeIntervalParameter() t + "{\"query\" : {\"match_all\" :{}}}\r\n"; FakeRestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(requestContent), - XContentType.JSON + MediaTypeRegistry.JSON ).withParams(Collections.singletonMap("cancel_after_time_interval", "20s")).build(); MultiSearchRequest request = RestMultiSearchAction.parseRequest(restRequest, null, true); assertThat(request.requests().size(), equalTo(1)); @@ -182,7 +184,7 @@ public void testDefaultIndicesOptions() throws IOException { + "{\"query\" : {\"match_all\" :{}}}\r\n"; FakeRestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(requestContent), - XContentType.JSON + MediaTypeRegistry.JSON ).withParams(Collections.singletonMap("ignore_unavailable", "true")).build(); MultiSearchRequest request = RestMultiSearchAction.parseRequest(restRequest, null, true); assertThat(request.requests().size(), equalTo(1)); @@ -301,7 +303,7 @@ public void testResponseErrorToXContent() { + "\"type\":\"illegal_state_exception\",\"reason\":\"baaaaaazzzz\"},\"status\":500" + "}" + "]}", - Strings.toString(XContentType.JSON, response) + Strings.toString(MediaTypeRegistry.JSON, response) ); } @@ -315,7 +317,7 @@ public void testMsearchTerminatedByNewline() throws Exception { String mserchAction = StreamsUtils.copyToStringFromClasspath("/org/opensearch/action/search/simple-msearch5.json"); RestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(mserchAction.getBytes(StandardCharsets.UTF_8)), - XContentType.JSON + MediaTypeRegistry.JSON ).build(); IllegalArgumentException expectThrows = expectThrows( IllegalArgumentException.class, @@ -326,7 +328,7 @@ public void testMsearchTerminatedByNewline() throws Exception { String mserchActionWithNewLine = mserchAction + "\n"; RestRequest restRequestWithNewLine = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(mserchActionWithNewLine.getBytes(StandardCharsets.UTF_8)), - XContentType.JSON + MediaTypeRegistry.JSON ).build(); MultiSearchRequest msearchRequest = RestMultiSearchAction.parseRequest(restRequestWithNewLine, null, true); assertEquals(3, msearchRequest.requests().size()); @@ -334,14 +336,14 @@ public void testMsearchTerminatedByNewline() throws Exception { private MultiSearchRequest parseMultiSearchRequestFromString(String request) throws IOException { return parseMultiSearchRequest( - new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(request), XContentType.JSON).build() + new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(request), MediaTypeRegistry.JSON).build() ); } private MultiSearchRequest parseMultiSearchRequestFromFile(String sample) throws IOException { byte[] data = StreamsUtils.copyToBytesFromClasspath(sample); return parseMultiSearchRequest( - new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(data), XContentType.JSON).build() + new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(data), MediaTypeRegistry.JSON).build() ); } @@ -379,10 +381,10 @@ public void testMultiLineSerialization() throws IOException { int iters = 16; for (int i = 0; i < iters; i++) { // The only formats that support stream separator - XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE); + MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE); MultiSearchRequest originalRequest = createMultiSearchRequest(); - byte[] originalBytes = MultiSearchRequest.writeMultiLineFormat(originalRequest, xContentType.xContent()); + byte[] originalBytes = MultiSearchRequest.writeMultiLineFormat(originalRequest, mediaType.xContent()); MultiSearchRequest parsedRequest = new MultiSearchRequest(); CheckedBiConsumer consumer = (r, p) -> { SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.fromXContent(p, false); @@ -393,7 +395,7 @@ public void testMultiLineSerialization() throws IOException { }; MultiSearchRequest.readMultiLineFormat( new BytesArray(originalBytes), - xContentType.xContent(), + mediaType.xContent(), consumer, null, null, @@ -413,7 +415,7 @@ public void testSerDeWithCancelAfterTimeIntervalParameterAndRandomVersion() thro + "\"cancel_after_time_interval\" : \"10s\"}\r\n{\"query\" : {\"match_all\" :{}}}\r\n"; FakeRestRequest restRequest = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(requestContent), - XContentType.JSON + MediaTypeRegistry.JSON ).build(); Version version = VersionUtils.randomVersion(random()); MultiSearchRequest originalRequest = RestMultiSearchAction.parseRequest(restRequest, null, true); @@ -545,7 +547,7 @@ private void assertExpandWildcardsValue(IndicesOptions options, String expectedV try (XContentBuilder builder = JsonXContent.contentBuilder()) { MultiSearchRequest.writeSearchRequestParams(request, builder); Map map = XContentHelper.convertToMap( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), BytesReference.bytes(builder).streamInput(), false ); diff --git a/server/src/test/java/org/opensearch/action/search/SearchPhaseExecutionExceptionTests.java b/server/src/test/java/org/opensearch/action/search/SearchPhaseExecutionExceptionTests.java index 8056206a661a5..d5ffde60686c9 100644 --- a/server/src/test/java/org/opensearch/action/search/SearchPhaseExecutionExceptionTests.java +++ b/server/src/test/java/org/opensearch/action/search/SearchPhaseExecutionExceptionTests.java @@ -39,6 +39,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContent; import org.opensearch.common.xcontent.XContentHelper; @@ -111,7 +112,7 @@ public void testToXContent() throws IOException { + " ]" + "}" ); - assertEquals(expectedJson, Strings.toString(XContentType.JSON, exception)); + assertEquals(expectedJson, Strings.toString(MediaTypeRegistry.JSON, exception)); } public void testToAndFromXContent() throws IOException { diff --git a/server/src/test/java/org/opensearch/action/search/SearchResponseTests.java b/server/src/test/java/org/opensearch/action/search/SearchResponseTests.java index 145f1238a08fc..5358420433bbc 100644 --- a/server/src/test/java/org/opensearch/action/search/SearchResponseTests.java +++ b/server/src/test/java/org/opensearch/action/search/SearchResponseTests.java @@ -36,15 +36,16 @@ import org.opensearch.Version; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.NamedWriteableRegistry; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; +import org.opensearch.core.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.rest.action.search.RestSearchAction; import org.opensearch.search.SearchHit; @@ -182,7 +183,7 @@ public void testFromXContentWithRandomFields() throws IOException { } private void doFromXContentTestWithRandomFields(SearchResponse response, boolean addRandomFields) throws IOException { - XContentType xcontentType = randomFrom(XContentType.values()); + MediaType xcontentType = randomFrom(XContentType.values()); boolean humanReadable = randomBoolean(); final ToXContent.Params params = new ToXContent.MapParams(singletonMap(RestSearchAction.TYPED_KEYS_PARAM, "true")); BytesReference originalBytes = toShuffledXContent(response, xcontentType, params, humanReadable); @@ -330,7 +331,7 @@ public void testToXContent() { } } expectedString.append("}"); - assertEquals(expectedString.toString(), Strings.toString(XContentType.JSON, response)); + assertEquals(expectedString.toString(), Strings.toString(MediaTypeRegistry.JSON, response)); } } @@ -363,7 +364,7 @@ public void testToXContentEmptyClusters() throws IOException { SearchResponse.Clusters.EMPTY ); SearchResponse deserialized = copyWriteable(searchResponse, namedWriteableRegistry, SearchResponse::new, Version.CURRENT); - XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder builder = XContentBuilder.builder(MediaTypeRegistry.JSON.xContent()); deserialized.getClusters().toXContent(builder, ToXContent.EMPTY_PARAMS); assertEquals(0, builder.toString().length()); } diff --git a/server/src/test/java/org/opensearch/action/search/ShardSearchFailureTests.java b/server/src/test/java/org/opensearch/action/search/ShardSearchFailureTests.java index 4fa555f0edddc..4a5a2aba9eb5a 100644 --- a/server/src/test/java/org/opensearch/action/search/ShardSearchFailureTests.java +++ b/server/src/test/java/org/opensearch/action/search/ShardSearchFailureTests.java @@ -36,6 +36,7 @@ import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.core.common.ParsingException; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -47,7 +48,7 @@ import java.io.IOException; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.test.XContentTestUtils.insertRandomFields; public class ShardSearchFailureTests extends OpenSearchTestCase { @@ -124,7 +125,7 @@ public void testToXContent() throws IOException { new ParsingException(0, 0, "some message", null), new SearchShardTarget("nodeId", new ShardId(new Index("indexName", "indexUuid"), 123), null, OriginalIndices.NONE) ); - BytesReference xContent = toXContent(failure, XContentType.JSON, randomBoolean()); + BytesReference xContent = toXContent(failure, MediaTypeRegistry.JSON, randomBoolean()); assertEquals( "{\"shard\":123," + "\"index\":\"indexName\"," @@ -145,7 +146,7 @@ public void testToXContentWithClusterAlias() throws IOException { new ParsingException(0, 0, "some message", null), new SearchShardTarget("nodeId", new ShardId(new Index("indexName", "indexUuid"), 123), "cluster1", OriginalIndices.NONE) ); - BytesReference xContent = toXContent(failure, XContentType.JSON, randomBoolean()); + BytesReference xContent = toXContent(failure, MediaTypeRegistry.JSON, randomBoolean()); assertEquals( "{\"shard\":123," + "\"index\":\"cluster1:indexName\"," diff --git a/server/src/test/java/org/opensearch/action/support/replication/ReplicationResponseTests.java b/server/src/test/java/org/opensearch/action/support/replication/ReplicationResponseTests.java index 35d7134b5dcc4..dc5a06b40209d 100644 --- a/server/src/test/java/org/opensearch/action/support/replication/ReplicationResponseTests.java +++ b/server/src/test/java/org/opensearch/action/support/replication/ReplicationResponseTests.java @@ -39,6 +39,7 @@ import org.opensearch.core.common.breaker.CircuitBreakingException; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.collect.Tuple; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -51,7 +52,7 @@ import java.util.Locale; import static org.opensearch.OpenSearchExceptionTests.assertDeepEquals; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; public class ReplicationResponseTests extends OpenSearchTestCase { @@ -66,7 +67,7 @@ public void testShardInfoToString() { public void testShardInfoToXContent() throws IOException { { ShardInfo shardInfo = new ShardInfo(5, 3); - String output = Strings.toString(XContentType.JSON, shardInfo); + String output = Strings.toString(MediaTypeRegistry.JSON, shardInfo); assertEquals("{\"total\":5,\"successful\":3,\"failed\":0}", output); } { @@ -88,7 +89,7 @@ public void testShardInfoToXContent() throws IOException { true ) ); - String output = Strings.toString(XContentType.JSON, shardInfo); + String output = Strings.toString(MediaTypeRegistry.JSON, shardInfo); assertEquals( "{\"total\":6,\"successful\":4,\"failed\":2,\"failures\":[{\"_index\":\"index\",\"_shard\":3," + "\"_node\":\"_node_id\",\"reason\":{\"type\":\"illegal_argument_exception\",\"reason\":\"Wrong\"}," diff --git a/server/src/test/java/org/opensearch/action/termvectors/TermVectorsUnitTests.java b/server/src/test/java/org/opensearch/action/termvectors/TermVectorsUnitTests.java index c7f14f7a22805..90efa3341eb73 100644 --- a/server/src/test/java/org/opensearch/action/termvectors/TermVectorsUnitTests.java +++ b/server/src/test/java/org/opensearch/action/termvectors/TermVectorsUnitTests.java @@ -55,8 +55,8 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.InputStreamStreamInput; import org.opensearch.core.common.io.stream.OutputStreamStreamOutput; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.core.index.shard.ShardId; import org.opensearch.rest.action.document.RestTermVectorsAction; @@ -247,7 +247,7 @@ public void testStreamRequest() throws IOException { request.termStatistics(random().nextBoolean()); String pref = random().nextBoolean() ? "somePreference" : null; request.preference(pref); - request.doc(new BytesArray("{}"), randomBoolean(), XContentType.JSON); + request.doc(new BytesArray("{}"), randomBoolean(), MediaTypeRegistry.JSON); // write ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); @@ -267,7 +267,7 @@ public void testStreamRequest() throws IOException { assertThat(request.preference(), equalTo(pref)); assertThat(request.routing(), equalTo(null)); assertEquals(new BytesArray("{}"), request.doc()); - assertEquals(XContentType.JSON, request.xContentType()); + assertEquals(MediaTypeRegistry.JSON, request.xContentType()); } } @@ -281,7 +281,7 @@ public void testStreamRequestLegacyVersion() throws IOException { request.termStatistics(random().nextBoolean()); String pref = random().nextBoolean() ? "somePreference" : null; request.preference(pref); - request.doc(new BytesArray("{}"), randomBoolean(), XContentType.JSON); + request.doc(new BytesArray("{}"), randomBoolean(), MediaTypeRegistry.JSON); // write using older version which contains types ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); @@ -313,7 +313,7 @@ public void testStreamRequestLegacyVersion() throws IOException { assertThat(request.preference(), equalTo(pref)); assertThat(request.routing(), equalTo(null)); assertEquals(new BytesArray("{}"), request.doc()); - assertEquals(XContentType.JSON, request.xContentType()); + assertEquals(MediaTypeRegistry.JSON, request.xContentType()); } } diff --git a/server/src/test/java/org/opensearch/action/termvectors/TransportMultiTermVectorsActionTests.java b/server/src/test/java/org/opensearch/action/termvectors/TransportMultiTermVectorsActionTests.java index cc4abc5343959..0b0827d704c74 100644 --- a/server/src/test/java/org/opensearch/action/termvectors/TransportMultiTermVectorsActionTests.java +++ b/server/src/test/java/org/opensearch/action/termvectors/TransportMultiTermVectorsActionTests.java @@ -54,9 +54,9 @@ import org.opensearch.common.util.concurrent.ThreadContext; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.Index; import org.opensearch.core.index.shard.ShardId; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.indices.IndicesService; import org.opensearch.tasks.Task; import org.opensearch.tasks.TaskId; @@ -140,7 +140,7 @@ public TaskManager getTaskManager() { .endObject() ), true, - XContentType.JSON + MediaTypeRegistry.JSON ) ) ) @@ -165,7 +165,7 @@ public TaskManager getTaskManager() { .endObject() ), true, - XContentType.JSON + MediaTypeRegistry.JSON ) ) ) diff --git a/server/src/test/java/org/opensearch/action/update/UpdateRequestTests.java b/server/src/test/java/org/opensearch/action/update/UpdateRequestTests.java index e0ee034f53821..b74221b4fc59a 100644 --- a/server/src/test/java/org/opensearch/action/update/UpdateRequestTests.java +++ b/server/src/test/java/org/opensearch/action/update/UpdateRequestTests.java @@ -42,6 +42,7 @@ import org.opensearch.common.document.DocumentField; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; @@ -71,7 +72,7 @@ import static java.util.Collections.emptyMap; import static org.opensearch.common.xcontent.XContentFactory.jsonBuilder; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO; import static org.opensearch.script.MockScriptEngine.mockInlineScript; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; @@ -514,7 +515,7 @@ public void testToValidateUpsertRequestAndCAS() { UpdateRequest updateRequest = new UpdateRequest("index", "id"); updateRequest.setIfSeqNo(1L); updateRequest.setIfPrimaryTerm(1L); - updateRequest.doc("{}", XContentType.JSON); + updateRequest.doc("{}", MediaTypeRegistry.JSON); updateRequest.upsert(new IndexRequest("index").id("id")); assertThat( updateRequest.validate().validationErrors(), @@ -524,7 +525,7 @@ public void testToValidateUpsertRequestAndCAS() { public void testToValidateUpsertRequestWithVersion() { UpdateRequest updateRequest = new UpdateRequest("index", "id"); - updateRequest.doc("{}", XContentType.JSON); + updateRequest.doc("{}", MediaTypeRegistry.JSON); updateRequest.upsert(new IndexRequest("index").id("1").version(1L)); assertThat(updateRequest.validate().validationErrors(), contains("can't provide version in upsert request")); } @@ -532,7 +533,7 @@ public void testToValidateUpsertRequestWithVersion() { public void testValidate() { { UpdateRequest request = new UpdateRequest("index", "id"); - request.doc("{}", XContentType.JSON); + request.doc("{}", MediaTypeRegistry.JSON); ActionRequestValidationException validate = request.validate(); assertThat(validate, nullValue()); @@ -540,7 +541,7 @@ public void testValidate() { { // Null types are defaulted to "_doc" UpdateRequest request = new UpdateRequest("index", null); - request.doc("{}", XContentType.JSON); + request.doc("{}", MediaTypeRegistry.JSON); ActionRequestValidationException validate = request.validate(); assertThat(validate, not(nullValue())); diff --git a/server/src/test/java/org/opensearch/action/update/UpdateResponseTests.java b/server/src/test/java/org/opensearch/action/update/UpdateResponseTests.java index 187b7f259ed63..b49b5a582304a 100644 --- a/server/src/test/java/org/opensearch/action/update/UpdateResponseTests.java +++ b/server/src/test/java/org/opensearch/action/update/UpdateResponseTests.java @@ -40,9 +40,10 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.collect.Tuple; import org.opensearch.common.document.DocumentField; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.get.GetResult; import org.opensearch.index.get.GetResultTests; import org.opensearch.index.seqno.SequenceNumbers; @@ -60,7 +61,7 @@ import static org.opensearch.action.DocWriteResponse.Result.NOT_FOUND; import static org.opensearch.action.DocWriteResponse.Result.UPDATED; import static org.opensearch.cluster.metadata.IndexMetadata.INDEX_UUID_NA_VALUE; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.test.XContentTestUtils.insertRandomFields; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; @@ -69,7 +70,7 @@ public class UpdateResponseTests extends OpenSearchTestCase { public void testToXContent() throws IOException { { UpdateResponse updateResponse = new UpdateResponse(new ShardId("index", "index_uuid", 0), "id", -2, 0, 0, NOT_FOUND); - String output = Strings.toString(XContentType.JSON, updateResponse); + String output = Strings.toString(MediaTypeRegistry.JSON, updateResponse); assertEquals( "{\"_index\":\"index\",\"_id\":\"id\",\"_version\":0,\"result\":\"not_found\"," + "\"_shards\":{\"total\":0,\"successful\":0,\"failed\":0}}", @@ -86,7 +87,7 @@ public void testToXContent() throws IOException { 1, DELETED ); - String output = Strings.toString(XContentType.JSON, updateResponse); + String output = Strings.toString(MediaTypeRegistry.JSON, updateResponse); assertEquals( "{\"_index\":\"index\",\"_id\":\"id\",\"_version\":1,\"result\":\"deleted\"," + "\"_shards\":{\"total\":10,\"successful\":6,\"failed\":0},\"_seq_no\":3,\"_primary_term\":17}", @@ -110,7 +111,7 @@ public void testToXContent() throws IOException { ); updateResponse.setGetResult(new GetResult("books", "1", 0, 1, 2, true, source, fields, null)); - String output = Strings.toString(XContentType.JSON, updateResponse); + String output = Strings.toString(MediaTypeRegistry.JSON, updateResponse); assertEquals( "{\"_index\":\"books\",\"_id\":\"1\",\"_version\":2,\"result\":\"updated\"," + "\"_shards\":{\"total\":3,\"successful\":2,\"failed\":0},\"_seq_no\":7,\"_primary_term\":17,\"get\":{" @@ -136,13 +137,13 @@ public void testFromXContentWithRandomFields() throws IOException { } private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws IOException { - final XContentType xContentType = randomFrom(XContentType.JSON); - final Tuple tuple = randomUpdateResponse(xContentType); + final MediaType mediaType = randomFrom(MediaTypeRegistry.JSON); + final Tuple tuple = randomUpdateResponse(mediaType); UpdateResponse updateResponse = tuple.v1(); UpdateResponse expectedUpdateResponse = tuple.v2(); boolean humanReadable = randomBoolean(); - BytesReference originalBytes = toShuffledXContent(updateResponse, xContentType, ToXContent.EMPTY_PARAMS, humanReadable); + BytesReference originalBytes = toShuffledXContent(updateResponse, mediaType, ToXContent.EMPTY_PARAMS, humanReadable); BytesReference mutated; if (addRandomFields) { @@ -155,12 +156,12 @@ private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws // object since this is where GetResult's metadata fields are rendered out and they would be parsed back as // extra metadata fields. Predicate excludeFilter = path -> path.contains("reason") || path.contains("get"); - mutated = insertRandomFields(xContentType, originalBytes, excludeFilter, random()); + mutated = insertRandomFields(mediaType, originalBytes, excludeFilter, random()); } else { mutated = originalBytes; } UpdateResponse parsedUpdateResponse; - try (XContentParser parser = createParser(xContentType.xContent(), mutated)) { + try (XContentParser parser = createParser(mediaType.xContent(), mutated)) { parsedUpdateResponse = UpdateResponse.fromXContent(parser); assertNull(parser.nextToken()); } @@ -173,9 +174,9 @@ private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws // Prints out the parsed UpdateResponse object to verify that it is the same as the expected output. // If random fields have been inserted, it checks that they have been filtered out and that they do // not alter the final output of the parsed object. - BytesReference parsedBytes = toXContent(parsedUpdateResponse, xContentType, humanReadable); - BytesReference expectedBytes = toXContent(expectedUpdateResponse, xContentType, humanReadable); - assertToXContentEquivalent(expectedBytes, parsedBytes, xContentType); + BytesReference parsedBytes = toXContent(parsedUpdateResponse, mediaType, humanReadable); + BytesReference expectedBytes = toXContent(expectedUpdateResponse, mediaType, humanReadable); + assertToXContentEquivalent(expectedBytes, parsedBytes, mediaType); } /** @@ -184,8 +185,8 @@ private void doFromXContentTestWithRandomFields(boolean addRandomFields) throws * The left element is the actual {@link UpdateResponse} to serialize while the right element is the * expected {@link UpdateResponse} after parsing. */ - public static Tuple randomUpdateResponse(XContentType xContentType) { - Tuple getResults = GetResultTests.randomGetResult(xContentType); + public static Tuple randomUpdateResponse(MediaType mediaType) { + Tuple getResults = GetResultTests.randomGetResult(mediaType); GetResult actualGetResult = getResults.v1(); GetResult expectedGetResult = getResults.v2(); diff --git a/server/src/test/java/org/opensearch/client/AbstractClientHeadersTestCase.java b/server/src/test/java/org/opensearch/client/AbstractClientHeadersTestCase.java index 92a88aa7940ee..0d324a0da7ee6 100644 --- a/server/src/test/java/org/opensearch/client/AbstractClientHeadersTestCase.java +++ b/server/src/test/java/org/opensearch/client/AbstractClientHeadersTestCase.java @@ -49,7 +49,7 @@ import org.opensearch.action.search.SearchAction; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.concurrent.ThreadContext; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.env.Environment; import org.opensearch.test.OpenSearchTestCase; import org.opensearch.threadpool.ThreadPool; @@ -130,7 +130,7 @@ public void testActions() { .execute(new AssertingActionListener<>(DeleteStoredScriptAction.NAME, client.threadPool())); client.prepareIndex("idx") .setId("id") - .setSource("source", XContentType.JSON) + .setSource("source", MediaTypeRegistry.JSON) .execute(new AssertingActionListener<>(IndexAction.NAME, client.threadPool())); // choosing arbitrary cluster admin actions to test diff --git a/server/src/test/java/org/opensearch/cluster/metadata/IndexGraveyardTests.java b/server/src/test/java/org/opensearch/cluster/metadata/IndexGraveyardTests.java index dd570a33d9c58..97d73fff4f834 100644 --- a/server/src/test/java/org/opensearch/cluster/metadata/IndexGraveyardTests.java +++ b/server/src/test/java/org/opensearch/cluster/metadata/IndexGraveyardTests.java @@ -38,7 +38,7 @@ import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentOpenSearchExtension; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -87,7 +87,7 @@ public void testXContent() throws IOException { if (graveyard.getTombstones().size() > 0) { // check that date properly printed assertThat( - Strings.toString(XContentType.JSON, graveyard, false, true), + Strings.toString(MediaTypeRegistry.JSON, graveyard, false, true), containsString( XContentOpenSearchExtension.DEFAULT_DATE_PRINTER.print(graveyard.getTombstones().get(0).getDeleteDateInMillis()) ) diff --git a/server/src/test/java/org/opensearch/cluster/metadata/IndexMetadataTests.java b/server/src/test/java/org/opensearch/cluster/metadata/IndexMetadataTests.java index 6ace70864ba47..3cd36c24755c3 100644 --- a/server/src/test/java/org/opensearch/cluster/metadata/IndexMetadataTests.java +++ b/server/src/test/java/org/opensearch/cluster/metadata/IndexMetadataTests.java @@ -46,8 +46,8 @@ import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.set.Sets; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -129,9 +129,9 @@ public void testIndexMetadataSerialization() throws IOException { final IndexMetadata fromXContentMeta = IndexMetadata.fromXContent(parser); assertEquals( "expected: " - + Strings.toString(XContentType.JSON, metadata) + + Strings.toString(MediaTypeRegistry.JSON, metadata) + "\nactual : " - + Strings.toString(XContentType.JSON, fromXContentMeta), + + Strings.toString(MediaTypeRegistry.JSON, fromXContentMeta), metadata, fromXContentMeta ); diff --git a/server/src/test/java/org/opensearch/cluster/metadata/IndexTemplateMetadataTests.java b/server/src/test/java/org/opensearch/cluster/metadata/IndexTemplateMetadataTests.java index 4648eaa6e3852..4610bc1c0c5a1 100644 --- a/server/src/test/java/org/opensearch/cluster/metadata/IndexTemplateMetadataTests.java +++ b/server/src/test/java/org/opensearch/cluster/metadata/IndexTemplateMetadataTests.java @@ -35,12 +35,12 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.test.OpenSearchTestCase; @@ -73,7 +73,7 @@ public void testIndexTemplateMetadataXContentRoundTrip() throws Exception { NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, templateBytes, - XContentType.JSON + MediaTypeRegistry.JSON ) ) { indexTemplateMetadata = IndexTemplateMetadata.Builder.fromXContent(parser, "test"); @@ -93,7 +93,7 @@ public void testIndexTemplateMetadataXContentRoundTrip() throws Exception { NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, templateBytesRoundTrip, - XContentType.JSON + MediaTypeRegistry.JSON ) ) { indexTemplateMetadataRoundTrip = IndexTemplateMetadata.Builder.fromXContent(parser, "test"); @@ -142,7 +142,7 @@ public void testValidateInvalidIndexPatterns() throws Exception { NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new BytesArray(templateWithEmptyPattern), - XContentType.JSON + MediaTypeRegistry.JSON ) ) { final IllegalArgumentException ex = expectThrows( @@ -166,7 +166,7 @@ public void testValidateInvalidIndexPatterns() throws Exception { NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new BytesArray(templateWithoutPattern), - XContentType.JSON + MediaTypeRegistry.JSON ) ) { final IllegalArgumentException ex = expectThrows( @@ -184,7 +184,7 @@ public void testParseTemplateWithAliases() throws Exception { NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new BytesArray(templateInJSON), - XContentType.JSON + MediaTypeRegistry.JSON ) ) { IndexTemplateMetadata template = IndexTemplateMetadata.Builder.fromXContent(parser, randomAlphaOfLengthBetween(1, 100)); @@ -222,7 +222,7 @@ public void testFromToXContent() throws Exception { templateBuilder.putMapping("doc", "{\"doc\":{\"properties\":{\"type\":\"text\"}}}"); } IndexTemplateMetadata template = templateBuilder.build(); - XContentBuilder builder = XContentBuilder.builder(randomFrom(XContentType.JSON.xContent())); + XContentBuilder builder = XContentBuilder.builder(randomFrom(MediaTypeRegistry.JSON.xContent())); builder.startObject(); IndexTemplateMetadata.Builder.toXContentWithTypes(template, builder, ToXContent.EMPTY_PARAMS); builder.endObject(); diff --git a/server/src/test/java/org/opensearch/cluster/metadata/MetadataIndexTemplateServiceTests.java b/server/src/test/java/org/opensearch/cluster/metadata/MetadataIndexTemplateServiceTests.java index 2f92ee8e0abdd..dc8f0ea26dccc 100644 --- a/server/src/test/java/org/opensearch/cluster/metadata/MetadataIndexTemplateServiceTests.java +++ b/server/src/test/java/org/opensearch/cluster/metadata/MetadataIndexTemplateServiceTests.java @@ -47,10 +47,10 @@ import org.opensearch.common.settings.SettingsException; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.env.Environment; import org.opensearch.core.index.Index; import org.opensearch.index.mapper.MapperParsingException; @@ -2146,7 +2146,7 @@ public static void assertTemplatesEqual(ComposableIndexTemplate actual, Composab Map actualMappings; Map expectedMappings; try ( - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser( new NamedXContentRegistry(Collections.emptyList()), LoggingDeprecationHandler.INSTANCE, @@ -2158,7 +2158,7 @@ public static void assertTemplatesEqual(ComposableIndexTemplate actual, Composab throw new AssertionError(e); } try ( - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser( new NamedXContentRegistry(Collections.emptyList()), LoggingDeprecationHandler.INSTANCE, diff --git a/server/src/test/java/org/opensearch/cluster/serialization/ClusterStateToStringTests.java b/server/src/test/java/org/opensearch/cluster/serialization/ClusterStateToStringTests.java index 6f81db2f0ef92..c978325917fe9 100644 --- a/server/src/test/java/org/opensearch/cluster/serialization/ClusterStateToStringTests.java +++ b/server/src/test/java/org/opensearch/cluster/serialization/ClusterStateToStringTests.java @@ -43,8 +43,8 @@ import org.opensearch.cluster.routing.RoutingTable; import org.opensearch.cluster.routing.allocation.AllocationService; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import java.util.Arrays; @@ -80,7 +80,7 @@ public void testClusterStateSerialization() throws Exception { AllocationService strategy = createAllocationService(); clusterState = ClusterState.builder(clusterState).routingTable(strategy.reroute(clusterState, "reroute").routingTable()).build(); - String clusterStateString = Strings.toString(XContentType.JSON, clusterState); + String clusterStateString = Strings.toString(MediaTypeRegistry.JSON, clusterState); assertNotNull(clusterStateString); assertThat(clusterStateString, containsString("test_idx")); diff --git a/server/src/test/java/org/opensearch/common/geo/GeoJsonSerializationTests.java b/server/src/test/java/org/opensearch/common/geo/GeoJsonSerializationTests.java index 23855c8f8dc91..45c9c79b7174f 100644 --- a/server/src/test/java/org/opensearch/common/geo/GeoJsonSerializationTests.java +++ b/server/src/test/java/org/opensearch/common/geo/GeoJsonSerializationTests.java @@ -35,13 +35,13 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.ToXContentObject; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.geo.GeometryTestUtils; import org.opensearch.geometry.Geometry; import org.opensearch.geometry.utils.GeographyValidator; @@ -153,7 +153,7 @@ public void testToMap() throws IOException { StreamInput input = BytesReference.bytes(builder).streamInput(); try ( - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, input) ) { Map map = GeoJson.toMap(geometry); diff --git a/server/src/test/java/org/opensearch/common/settings/SettingsTests.java b/server/src/test/java/org/opensearch/common/settings/SettingsTests.java index 83fb74bb185c2..d627fe7c80477 100644 --- a/server/src/test/java/org/opensearch/common/settings/SettingsTests.java +++ b/server/src/test/java/org/opensearch/common/settings/SettingsTests.java @@ -41,6 +41,7 @@ import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.unit.TimeValue; import org.opensearch.core.common.settings.SecureString; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -514,7 +515,7 @@ public void testToAndFromXContent() throws IOException { .putNull("foo.null.baz") .build(); final boolean flatSettings = randomBoolean(); - XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder(); builder.startObject(); settings.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("flat_settings", "" + flatSettings))); builder.endObject(); @@ -547,20 +548,20 @@ public void testSimpleJsonSettings() throws Exception { public void testToXContent() throws IOException { // this is just terrible but it's the existing behavior! Settings test = Settings.builder().putList("foo.bar", "1", "2", "3").put("foo.bar.baz", "test").build(); - XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder builder = XContentBuilder.builder(MediaTypeRegistry.JSON.xContent()); builder.startObject(); test.toXContent(builder, new ToXContent.MapParams(Collections.emptyMap())); builder.endObject(); assertEquals("{\"foo\":{\"bar.baz\":\"test\",\"bar\":[\"1\",\"2\",\"3\"]}}", builder.toString()); test = Settings.builder().putList("foo.bar", "1", "2", "3").build(); - builder = XContentBuilder.builder(XContentType.JSON.xContent()); + builder = XContentBuilder.builder(MediaTypeRegistry.JSON.xContent()); builder.startObject(); test.toXContent(builder, new ToXContent.MapParams(Collections.emptyMap())); builder.endObject(); assertEquals("{\"foo\":{\"bar\":[\"1\",\"2\",\"3\"]}}", builder.toString()); - builder = XContentBuilder.builder(XContentType.JSON.xContent()); + builder = XContentBuilder.builder(MediaTypeRegistry.JSON.xContent()); builder.startObject(); test.toXContent(builder, new ToXContent.MapParams(Collections.singletonMap("flat_settings", "true"))); builder.endObject(); @@ -707,14 +708,14 @@ public void testSetByTimeUnit() { public void testProcessSetting() throws IOException { Settings test = Settings.builder().put("ant", "value1").put("ant.bee.cat", "value2").put("bee.cat", "value3").build(); - XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder builder = XContentBuilder.builder(MediaTypeRegistry.JSON.xContent()); builder.startObject(); test.toXContent(builder, new ToXContent.MapParams(Collections.emptyMap())); builder.endObject(); assertEquals("{\"ant.bee\":{\"cat\":\"value2\"},\"ant\":\"value1\",\"bee\":{\"cat\":\"value3\"}}", builder.toString()); test = Settings.builder().put("ant", "value1").put("ant.bee.cat", "value2").put("ant.bee.cat.dog.ewe", "value3").build(); - builder = XContentBuilder.builder(XContentType.JSON.xContent()); + builder = XContentBuilder.builder(MediaTypeRegistry.JSON.xContent()); builder.startObject(); test.toXContent(builder, new ToXContent.MapParams(Collections.emptyMap())); builder.endObject(); diff --git a/server/src/test/java/org/opensearch/common/xcontent/XContentFactoryTests.java b/server/src/test/java/org/opensearch/common/xcontent/XContentFactoryTests.java index 41e63f3f6d825..3ba727a8edf2a 100644 --- a/server/src/test/java/org/opensearch/common/xcontent/XContentFactoryTests.java +++ b/server/src/test/java/org/opensearch/common/xcontent/XContentFactoryTests.java @@ -36,6 +36,7 @@ import com.fasterxml.jackson.dataformat.smile.SmileConstants; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.test.OpenSearchTestCase; @@ -48,7 +49,7 @@ public class XContentFactoryTests extends OpenSearchTestCase { public void testGuessJson() throws IOException { - testGuessType(XContentType.JSON); + testGuessType(MediaTypeRegistry.JSON); } public void testGuessSmile() throws IOException { @@ -63,14 +64,14 @@ public void testGuessCbor() throws IOException { testGuessType(XContentType.CBOR); } - private void testGuessType(XContentType type) throws IOException { + private void testGuessType(MediaType type) throws IOException { XContentBuilder builder = MediaTypeRegistry.contentBuilder(type); builder.startObject(); builder.field("field1", "value1"); builder.endObject(); final BytesReference bytes; - if (type == XContentType.JSON && randomBoolean()) { + if (type == MediaTypeRegistry.JSON && randomBoolean()) { final int length = randomIntBetween(0, 8 * MediaTypeRegistry.GUESS_HEADER_LENGTH); final String content = builder.toString(); final StringBuilder sb = new StringBuilder(length + content.length()); @@ -132,15 +133,15 @@ public void testInvalidStream() throws Exception { public void testJsonFromBytesOptionallyPrecededByUtf8Bom() throws Exception { byte[] bytes = new byte[] { (byte) '{', (byte) '}' }; - assertThat(MediaTypeRegistry.xContent(bytes), equalTo(XContentType.JSON)); + assertThat(MediaTypeRegistry.xContent(bytes), equalTo(MediaTypeRegistry.JSON)); bytes = new byte[] { (byte) 0x20, (byte) '{', (byte) '}' }; - assertThat(MediaTypeRegistry.xContent(bytes), equalTo(XContentType.JSON)); + assertThat(MediaTypeRegistry.xContent(bytes), equalTo(MediaTypeRegistry.JSON)); bytes = new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf, (byte) '{', (byte) '}' }; - assertThat(MediaTypeRegistry.xContent(bytes), equalTo(XContentType.JSON)); + assertThat(MediaTypeRegistry.xContent(bytes), equalTo(MediaTypeRegistry.JSON)); bytes = new byte[] { (byte) 0xef, (byte) 0xbb, (byte) 0xbf, (byte) 0x20, (byte) '{', (byte) '}' }; - assertThat(MediaTypeRegistry.xContent(bytes), equalTo(XContentType.JSON)); + assertThat(MediaTypeRegistry.xContent(bytes), equalTo(MediaTypeRegistry.JSON)); } } diff --git a/server/src/test/java/org/opensearch/common/xcontent/XContentParserUtilsTests.java b/server/src/test/java/org/opensearch/common/xcontent/XContentParserUtilsTests.java index 4f0d4b7cb63dc..b9feb10c51fff 100644 --- a/server/src/test/java/org/opensearch/common/xcontent/XContentParserUtilsTests.java +++ b/server/src/test/java/org/opensearch/common/xcontent/XContentParserUtilsTests.java @@ -40,6 +40,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.xcontent.json.JsonXContent; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParserUtils; import org.opensearch.core.xcontent.DeprecationHandler; import org.opensearch.core.xcontent.NamedObjectNotFoundException; @@ -55,7 +56,7 @@ import java.util.List; import java.util.Map; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.core.xcontent.XContentParserUtils.ensureFieldName; import static org.opensearch.core.xcontent.XContentParserUtils.parseTypedKeysObject; @@ -113,7 +114,7 @@ public void testStoredFieldsValueBoolean() throws IOException { public void testStoredFieldsValueBinary() throws IOException { final byte[] value = randomUnicodeOfLength(scaledRandomIntBetween(10, 1000)).getBytes("UTF-8"); assertParseFieldsSimpleValue(value, (xcontentType, result) -> { - if (xcontentType == XContentType.JSON) { + if (xcontentType == MediaTypeRegistry.JSON) { // binary values will be parsed back and returned as base64 strings when reading from json assertArrayEquals(value, Base64.getDecoder().decode((String) result)); } else { diff --git a/server/src/test/java/org/opensearch/common/xcontent/XContentTypeTests.java b/server/src/test/java/org/opensearch/common/xcontent/XContentTypeTests.java index 8c53d7edebca8..53fbcb4659f72 100644 --- a/server/src/test/java/org/opensearch/common/xcontent/XContentTypeTests.java +++ b/server/src/test/java/org/opensearch/common/xcontent/XContentTypeTests.java @@ -32,6 +32,7 @@ package org.opensearch.common.xcontent; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchTestCase; import java.util.Locale; @@ -43,7 +44,7 @@ public class XContentTypeTests extends OpenSearchTestCase { public void testFromJson() throws Exception { String mediaType = "application/json"; - XContentType expectedXContentType = XContentType.JSON; + MediaType expectedXContentType = MediaTypeRegistry.JSON; assertThat(MediaType.fromMediaType(mediaType), equalTo(expectedXContentType)); assertThat(MediaType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType)); assertThat(MediaType.fromMediaType(mediaType + "; charset=UTF-8"), equalTo(expectedXContentType)); @@ -51,7 +52,7 @@ public void testFromJson() throws Exception { public void testFromNdJson() throws Exception { String mediaType = "application/x-ndjson"; - XContentType expectedXContentType = XContentType.JSON; + MediaType expectedXContentType = MediaTypeRegistry.JSON; assertThat(MediaType.fromMediaType(mediaType), equalTo(expectedXContentType)); assertThat(MediaType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType)); assertThat(MediaType.fromMediaType(mediaType + "; charset=UTF-8"), equalTo(expectedXContentType)); @@ -59,7 +60,7 @@ public void testFromNdJson() throws Exception { public void testFromJsonUppercase() throws Exception { String mediaType = "application/json".toUpperCase(Locale.ROOT); - XContentType expectedXContentType = XContentType.JSON; + MediaType expectedXContentType = MediaTypeRegistry.JSON; assertThat(MediaType.fromMediaType(mediaType), equalTo(expectedXContentType)); assertThat(MediaType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType)); assertThat(MediaType.fromMediaType(mediaType + "; charset=UTF-8"), equalTo(expectedXContentType)); @@ -89,14 +90,14 @@ public void testFromCbor() throws Exception { public void testFromWildcard() throws Exception { String mediaType = "application/*"; - XContentType expectedXContentType = XContentType.JSON; + MediaType expectedXContentType = MediaTypeRegistry.JSON; assertThat(MediaType.fromMediaType(mediaType), equalTo(expectedXContentType)); assertThat(MediaType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType)); } public void testFromWildcardUppercase() throws Exception { String mediaType = "APPLICATION/*"; - XContentType expectedXContentType = XContentType.JSON; + MediaType expectedXContentType = MediaTypeRegistry.JSON; assertThat(MediaType.fromMediaType(mediaType), equalTo(expectedXContentType)); assertThat(MediaType.fromMediaType(mediaType + ";"), equalTo(expectedXContentType)); } @@ -109,15 +110,15 @@ public void testFromRubbish() throws Exception { } public void testVersionedMediaType() throws Exception { - assertThat(MediaType.fromMediaType("application/vnd.opensearch+json;compatible-with=7"), equalTo(XContentType.JSON)); + assertThat(MediaType.fromMediaType("application/vnd.opensearch+json;compatible-with=7"), equalTo(MediaTypeRegistry.JSON)); assertThat(MediaType.fromMediaType("application/vnd.opensearch+yaml;compatible-with=7"), equalTo(XContentType.YAML)); assertThat(MediaType.fromMediaType("application/vnd.opensearch+cbor;compatible-with=7"), equalTo(XContentType.CBOR)); assertThat(MediaType.fromMediaType("application/vnd.opensearch+smile;compatible-with=7"), equalTo(XContentType.SMILE)); - assertThat(MediaType.fromMediaType("application/vnd.opensearch+json ;compatible-with=7"), equalTo(XContentType.JSON)); + assertThat(MediaType.fromMediaType("application/vnd.opensearch+json ;compatible-with=7"), equalTo(MediaTypeRegistry.JSON)); String mthv = "application/vnd.opensearch+json ;compatible-with=7;charset=utf-8"; - assertThat(MediaType.fromMediaType(mthv), equalTo(XContentType.JSON)); - assertThat(MediaType.fromMediaType(mthv.toUpperCase(Locale.ROOT)), equalTo(XContentType.JSON)); + assertThat(MediaType.fromMediaType(mthv), equalTo(MediaTypeRegistry.JSON)); + assertThat(MediaType.fromMediaType(mthv.toUpperCase(Locale.ROOT)), equalTo(MediaTypeRegistry.JSON)); } } diff --git a/server/src/test/java/org/opensearch/common/xcontent/builder/XContentBuilderTests.java b/server/src/test/java/org/opensearch/common/xcontent/builder/XContentBuilderTests.java index 9ffe9915808e3..167fddef8fa59 100644 --- a/server/src/test/java/org/opensearch/common/xcontent/builder/XContentBuilderTests.java +++ b/server/src/test/java/org/opensearch/common/xcontent/builder/XContentBuilderTests.java @@ -67,7 +67,7 @@ public class XContentBuilderTests extends OpenSearchTestCase { public void testPrettyWithLfAtEnd() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); - XContentGenerator generator = XContentType.JSON.xContent().createGenerator(os); + XContentGenerator generator = MediaTypeRegistry.JSON.xContent().createGenerator(os); generator.usePrettyPrint(); generator.usePrintLineFeedAtEnd(); @@ -86,7 +86,7 @@ public void testPrettyWithLfAtEnd() throws Exception { public void testReuseJsonGenerator() throws Exception { ByteArrayOutputStream os = new ByteArrayOutputStream(); - XContentGenerator generator = XContentType.JSON.xContent().createGenerator(os); + XContentGenerator generator = MediaTypeRegistry.JSON.xContent().createGenerator(os); generator.writeStartObject(); generator.writeStringField("test", "value"); generator.writeEndObject(); @@ -106,14 +106,14 @@ public void testReuseJsonGenerator() throws Exception { public void testRaw() throws IOException { { - XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); xContentBuilder.startObject(); xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}").streamInput()); xContentBuilder.endObject(); assertThat(xContentBuilder.toString(), equalTo("{\"foo\":{\"test\":\"value\"}}")); } { - XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); xContentBuilder.startObject(); xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}").streamInput()); xContentBuilder.rawField("foo1", new BytesArray("{\"test\":\"value\"}").streamInput()); @@ -121,7 +121,7 @@ public void testRaw() throws IOException { assertThat(xContentBuilder.toString(), equalTo("{\"foo\":{\"test\":\"value\"},\"foo1\":{\"test\":\"value\"}}")); } { - XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); xContentBuilder.startObject(); xContentBuilder.field("test", "value"); xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}").streamInput()); @@ -129,7 +129,7 @@ public void testRaw() throws IOException { assertThat(xContentBuilder.toString(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"}}")); } { - XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); xContentBuilder.startObject(); xContentBuilder.field("test", "value"); xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}").streamInput()); @@ -138,7 +138,7 @@ public void testRaw() throws IOException { assertThat(xContentBuilder.toString(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"test1\":\"value1\"}")); } { - XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); xContentBuilder.startObject(); xContentBuilder.field("test", "value"); xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}").streamInput()); @@ -153,17 +153,17 @@ public void testRaw() throws IOException { } public void testSimpleGenerator() throws Exception { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.startObject().field("test", "value").endObject(); assertThat(builder.toString(), equalTo("{\"test\":\"value\"}")); - builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.startObject().field("test", "value").endObject(); assertThat(builder.toString(), equalTo("{\"test\":\"value\"}")); } public void testOverloadedList() throws Exception { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.startObject().field("test", Arrays.asList("1", "2")).endObject(); assertThat(builder.toString(), equalTo("{\"test\":[\"1\",\"2\"]}")); } @@ -171,7 +171,7 @@ public void testOverloadedList() throws Exception { public void testWritingBinaryToStream() throws Exception { BytesStreamOutput bos = new BytesStreamOutput(); - XContentGenerator gen = XContentType.JSON.xContent().createGenerator(bos); + XContentGenerator gen = MediaTypeRegistry.JSON.xContent().createGenerator(bos); gen.writeStartObject(); gen.writeStringField("name", "something"); gen.flush(); @@ -185,7 +185,7 @@ public void testWritingBinaryToStream() throws Exception { } public void testByteConversion() throws Exception { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.startObject().field("test_name", (Byte) (byte) 120).endObject(); assertThat(BytesReference.bytes(builder).utf8ToString(), equalTo("{\"test_name\":120}")); } @@ -195,21 +195,21 @@ public void testDateTypesConversion() throws Exception { String expectedDate = XContentOpenSearchExtension.DEFAULT_DATE_PRINTER.print(date.getTime()); Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC"), Locale.ROOT); String expectedCalendar = XContentOpenSearchExtension.DEFAULT_DATE_PRINTER.print(calendar.getTimeInMillis()); - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.startObject().timeField("date", date).endObject(); assertThat(builder.toString(), equalTo("{\"date\":\"" + expectedDate + "\"}")); - builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.startObject().field("calendar", calendar).endObject(); assertThat(builder.toString(), equalTo("{\"calendar\":\"" + expectedCalendar + "\"}")); - builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); Map map = new HashMap<>(); map.put("date", date); builder.map(map); assertThat(builder.toString(), equalTo("{\"date\":\"" + expectedDate + "\"}")); - builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); map = new HashMap<>(); map.put("calendar", calendar); builder.map(map); @@ -217,7 +217,7 @@ public void testDateTypesConversion() throws Exception { } public void testCopyCurrentStructure() throws Exception { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.startObject().field("test", "test field").startObject("filter").startObject("terms"); // up to 20k random terms @@ -284,10 +284,10 @@ public void testHandlingOfPath_absolute() throws IOException { } private void checkPathSerialization(Path path) throws IOException { - XContentBuilder pathBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder pathBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); pathBuilder.startObject().field("file", path).endObject(); - XContentBuilder stringBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder stringBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); stringBuilder.startObject().field("file", path.toString()).endObject(); assertThat(pathBuilder.toString(), equalTo(stringBuilder.toString())); @@ -297,10 +297,10 @@ public void testHandlingOfPath_StringName() throws IOException { Path path = PathUtils.get("path"); String name = new String("file"); - XContentBuilder pathBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder pathBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); pathBuilder.startObject().field(name, path).endObject(); - XContentBuilder stringBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder stringBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); stringBuilder.startObject().field(name, path.toString()).endObject(); assertThat(pathBuilder.toString(), equalTo(stringBuilder.toString())); @@ -309,17 +309,17 @@ public void testHandlingOfPath_StringName() throws IOException { public void testHandlingOfCollectionOfPaths() throws IOException { Path path = PathUtils.get("path"); - XContentBuilder pathBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder pathBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); pathBuilder.startObject().field("file", Arrays.asList(path)).endObject(); - XContentBuilder stringBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder stringBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); stringBuilder.startObject().field("file", Arrays.asList(path.toString())).endObject(); assertThat(pathBuilder.toString(), equalTo(stringBuilder.toString())); } public void testIndentIsPlatformIndependent() throws IOException { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON).prettyPrint(); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON).prettyPrint(); builder.startObject().field("test", "foo").startObject("foo").field("foobar", "boom").endObject().endObject(); String string = builder.toString(); assertEquals("{\n" + " \"test\" : \"foo\",\n" + " \"foo\" : {\n" + " \"foobar\" : \"boom\"\n" + " }\n" + "}", string); @@ -331,7 +331,7 @@ public void testIndentIsPlatformIndependent() throws IOException { } public void testRenderGeoPoint() throws IOException { - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON).prettyPrint(); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON).prettyPrint(); builder.startObject().field("foo").value(new GeoPoint(1, 2)).endObject(); String string = builder.toString(); assertEquals("{\n" + " \"foo\" : {\n" + " \"lat\" : 1.0,\n" + " \"lon\" : 2.0\n" + " }\n" + "}", string.trim()); diff --git a/server/src/test/java/org/opensearch/common/xcontent/cbor/JsonVsCborTests.java b/server/src/test/java/org/opensearch/common/xcontent/cbor/JsonVsCborTests.java index 89add6ea78722..ccf9b5804dcfa 100644 --- a/server/src/test/java/org/opensearch/common/xcontent/cbor/JsonVsCborTests.java +++ b/server/src/test/java/org/opensearch/common/xcontent/cbor/JsonVsCborTests.java @@ -33,6 +33,7 @@ package org.opensearch.common.xcontent.cbor; import org.opensearch.common.io.stream.BytesStreamOutput; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentGenerator; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -50,7 +51,7 @@ public void testCompareParsingTokens() throws IOException { XContentGenerator xsonGen = XContentType.CBOR.xContent().createGenerator(xsonOs); BytesStreamOutput jsonOs = new BytesStreamOutput(); - XContentGenerator jsonGen = XContentType.JSON.xContent().createGenerator(jsonOs); + XContentGenerator jsonGen = MediaTypeRegistry.JSON.xContent().createGenerator(jsonOs); xsonGen.writeStartObject(); jsonGen.writeStartObject(); diff --git a/server/src/test/java/org/opensearch/common/xcontent/smile/JsonVsSmileTests.java b/server/src/test/java/org/opensearch/common/xcontent/smile/JsonVsSmileTests.java index a96031f2a1dad..ed036c0e5771c 100644 --- a/server/src/test/java/org/opensearch/common/xcontent/smile/JsonVsSmileTests.java +++ b/server/src/test/java/org/opensearch/common/xcontent/smile/JsonVsSmileTests.java @@ -33,6 +33,7 @@ package org.opensearch.common.xcontent.smile; import org.opensearch.common.io.stream.BytesStreamOutput; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentGenerator; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -50,7 +51,7 @@ public void testCompareParsingTokens() throws IOException { XContentGenerator xsonGen = XContentType.SMILE.xContent().createGenerator(xsonOs); BytesStreamOutput jsonOs = new BytesStreamOutput(); - XContentGenerator jsonGen = XContentType.JSON.xContent().createGenerator(jsonOs); + XContentGenerator jsonGen = MediaTypeRegistry.JSON.xContent().createGenerator(jsonOs); xsonGen.writeStartObject(); jsonGen.writeStartObject(); diff --git a/server/src/test/java/org/opensearch/common/xcontent/support/XContentHelperTests.java b/server/src/test/java/org/opensearch/common/xcontent/support/XContentHelperTests.java index 652e11c2fd99f..eaa20e9e73b91 100644 --- a/server/src/test/java/org/opensearch/common/xcontent/support/XContentHelperTests.java +++ b/server/src/test/java/org/opensearch/common/xcontent/support/XContentHelperTests.java @@ -35,6 +35,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.ToXContentObject; @@ -211,7 +212,7 @@ public void testChildBytes() throws IOException { } public void testEmbeddedObject() throws IOException { - // Need to test this separately as XContentType.JSON never produces VALUE_EMBEDDED_OBJECT + // Need to test this separately as MediaTypeRegistry.JSON never produces VALUE_EMBEDDED_OBJECT XContentBuilder builder = XContentBuilder.builder(XContentType.CBOR.xContent()); builder.startObject().startObject("root"); CompressedXContent embedded = new CompressedXContent("{\"field\":\"value\"}"); @@ -252,7 +253,7 @@ public void testEmptyChildBytes() throws IOException { String inputJson = "{ \"mappings\" : {} }"; try ( - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, inputJson) ) { diff --git a/server/src/test/java/org/opensearch/common/xcontent/support/XContentMapValuesTests.java b/server/src/test/java/org/opensearch/common/xcontent/support/XContentMapValuesTests.java index 5b3ba777449eb..72f0101925ff5 100644 --- a/server/src/test/java/org/opensearch/common/xcontent/support/XContentMapValuesTests.java +++ b/server/src/test/java/org/opensearch/common/xcontent/support/XContentMapValuesTests.java @@ -55,7 +55,7 @@ import static java.util.Collections.emptySet; import static java.util.Collections.singleton; import static org.opensearch.common.xcontent.XContentHelper.convertToMap; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.hamcrest.Matchers.hasEntry; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.hasSize; diff --git a/server/src/test/java/org/opensearch/extensions/rest/ExtensionRestRequestTests.java b/server/src/test/java/org/opensearch/extensions/rest/ExtensionRestRequestTests.java index e12549b93ab53..2f8cec957e42e 100644 --- a/server/src/test/java/org/opensearch/extensions/rest/ExtensionRestRequestTests.java +++ b/server/src/test/java/org/opensearch/extensions/rest/ExtensionRestRequestTests.java @@ -15,9 +15,10 @@ import org.opensearch.core.common.io.stream.BytesStreamInput; import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.core.common.io.stream.NamedWriteableRegistry; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.io.stream.NamedWriteableAwareStreamInput; import org.opensearch.rest.BytesRestResponse; import org.opensearch.rest.RestRequest.Method; @@ -39,7 +40,7 @@ public class ExtensionRestRequestTests extends OpenSearchTestCase { private String expectedUri; Map expectedParams; Map> expectedHeaders; - XContentType expectedContentType; + MediaType expectedContentType; BytesReference expectedContent; String extensionUniqueId1; Principal userPrincipal; @@ -59,7 +60,7 @@ public void setUp() throws Exception { entry("Content-Type", Arrays.asList("application/json")), entry("foo", Arrays.asList("hello", "world")) ); - expectedContentType = XContentType.JSON; + expectedContentType = MediaTypeRegistry.JSON; expectedContent = new BytesArray("{\"key\": \"value\"}".getBytes(StandardCharsets.UTF_8)); extensionUniqueId1 = "ext_1"; userPrincipal = () -> "user1"; diff --git a/server/src/test/java/org/opensearch/extensions/rest/ExtensionRestResponseTests.java b/server/src/test/java/org/opensearch/extensions/rest/ExtensionRestResponseTests.java index e76e6b98811f7..0be23e22fdaff 100644 --- a/server/src/test/java/org/opensearch/extensions/rest/ExtensionRestResponseTests.java +++ b/server/src/test/java/org/opensearch/extensions/rest/ExtensionRestResponseTests.java @@ -16,10 +16,10 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.http.HttpRequest; import org.opensearch.http.HttpResponse; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.rest.RestRequest; import org.opensearch.core.rest.RestStatus; import org.opensearch.rest.RestRequest.Method; @@ -110,7 +110,7 @@ public HttpRequest releaseAndCopy() { } public void testConstructorWithBuilder() throws IOException { - XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder(); builder.startObject(); builder.field("status", ACCEPTED); builder.endObject(); diff --git a/server/src/test/java/org/opensearch/extensions/rest/RestInitializeExtensionActionTests.java b/server/src/test/java/org/opensearch/extensions/rest/RestInitializeExtensionActionTests.java index 1faa3bd9aec55..dbb1f45f55d9a 100644 --- a/server/src/test/java/org/opensearch/extensions/rest/RestInitializeExtensionActionTests.java +++ b/server/src/test/java/org/opensearch/extensions/rest/RestInitializeExtensionActionTests.java @@ -31,7 +31,7 @@ import org.opensearch.common.settings.Setting; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.PageCacheRecycler; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.extensions.ExtensionsManager; import org.opensearch.extensions.ExtensionsSettings; import org.opensearch.core.indices.breaker.NoneCircuitBreakerService; @@ -103,7 +103,7 @@ public void testRestInitializeExtensionActionResponse() throws Exception { + "\"minimumCompatibleVersion\":\"" + Version.CURRENT.minimumCompatibilityVersion().toString() + "\"}"; - RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(content), XContentType.JSON) + RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(content), MediaTypeRegistry.JSON) .withMethod(RestRequest.Method.POST) .build(); @@ -125,7 +125,7 @@ public void testRestInitializeExtensionActionFailure() throws Exception { + "\"minimumCompatibleVersion\":\"" + Version.CURRENT.minimumCompatibilityVersion().toString() + "\"}"; - RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(content), XContentType.JSON) + RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(content), MediaTypeRegistry.JSON) .withMethod(RestRequest.Method.POST) .build(); @@ -163,7 +163,7 @@ public void testRestInitializeExtensionActionResponseWithAdditionalSettings() th + "\"minimumCompatibleVersion\":\"" + Version.CURRENT.minimumCompatibilityVersion().toString() + "\",\"boolSetting\":true,\"stringSetting\":\"customSetting\",\"intSetting\":5,\"listSetting\":[\"one\",\"two\",\"three\"]}"; - RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(content), XContentType.JSON) + RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(content), MediaTypeRegistry.JSON) .withMethod(RestRequest.Method.POST) .build(); @@ -210,7 +210,7 @@ public void testRestInitializeExtensionActionResponseWithAdditionalSettingsUsing + "\"minimumCompatibleVersion\":\"" + Version.CURRENT.minimumCompatibilityVersion().toString() + "\"}"; - RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(content), XContentType.JSON) + RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent(new BytesArray(content), MediaTypeRegistry.JSON) .withMethod(RestRequest.Method.POST) .build(); diff --git a/server/src/test/java/org/opensearch/index/IndexServiceTests.java b/server/src/test/java/org/opensearch/index/IndexServiceTests.java index ac572c4fa8440..f36cce90f1a7a 100644 --- a/server/src/test/java/org/opensearch/index/IndexServiceTests.java +++ b/server/src/test/java/org/opensearch/index/IndexServiceTests.java @@ -40,10 +40,10 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; import org.opensearch.core.index.Index; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.engine.Engine; import org.opensearch.index.query.QueryBuilder; import org.opensearch.index.shard.IndexShard; @@ -300,7 +300,7 @@ public void testRefreshActuallyWorks() throws Exception { assertEquals(1000, refreshTask.getInterval().millis()); assertTrue(indexService.getRefreshTask().mustReschedule()); IndexShard shard = indexService.getShard(0); - client().prepareIndex("test").setId("0").setSource("{\"foo\": \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("0").setSource("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON).get(); // now disable the refresh client().admin() .indices() @@ -321,7 +321,7 @@ public void testRefreshActuallyWorks() throws Exception { }); assertFalse(refreshTask.isClosed()); // refresh every millisecond - client().prepareIndex("test").setId("1").setSource("{\"foo\": \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON).get(); client().admin() .indices() .prepareUpdateSettings("test") @@ -335,7 +335,7 @@ public void testRefreshActuallyWorks() throws Exception { assertEquals(2, search.totalHits.value); } }); - client().prepareIndex("test").setId("2").setSource("{\"foo\": \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("2").setSource("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON).get(); assertBusy(() -> { // this one becomes visible due to the scheduled refresh try (Engine.Searcher searcher = shard.acquireSearcher("test")) { @@ -353,7 +353,7 @@ public void testAsyncFsyncActuallyWorks() throws Exception { IndexService indexService = createIndex("test", settings); ensureGreen("test"); assertTrue(indexService.getRefreshTask().mustReschedule()); - client().prepareIndex("test").setId("1").setSource("{\"foo\": \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON).get(); IndexShard shard = indexService.getShard(0); assertBusy(() -> assertFalse(shard.isSyncNeeded())); } @@ -375,7 +375,7 @@ public void testRescheduleAsyncFsync() throws Exception { assertNotNull(indexService.getFsyncTask()); assertTrue(indexService.getFsyncTask().mustReschedule()); - client().prepareIndex("test").setId("1").setSource("{\"foo\": \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON).get(); assertNotNull(indexService.getFsyncTask()); final IndexShard shard = indexService.getShard(0); assertBusy(() -> assertFalse(shard.isSyncNeeded())); @@ -402,7 +402,7 @@ public void testAsyncTranslogTrimActuallyWorks() throws Exception { IndexService indexService = createIndex("test", settings); ensureGreen("test"); assertTrue(indexService.getTrimTranslogTask().mustReschedule()); - client().prepareIndex("test").setId("1").setSource("{\"foo\": \"bar\"}", XContentType.JSON).get(); + client().prepareIndex("test").setId("1").setSource("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON).get(); client().admin().indices().prepareFlush("test").get(); client().admin() .indices() @@ -429,7 +429,11 @@ public void testAsyncTranslogTrimTaskOnClosedIndex() throws Exception { int translogOps = 0; final int numDocs = scaledRandomIntBetween(10, 100); for (int i = 0; i < numDocs; i++) { - client().prepareIndex().setIndex(indexName).setId(String.valueOf(i)).setSource("{\"foo\": \"bar\"}", XContentType.JSON).get(); + client().prepareIndex() + .setIndex(indexName) + .setId(String.valueOf(i)) + .setSource("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON) + .get(); translogOps++; if (randomBoolean()) { client().admin().indices().prepareFlush(indexName).get(); diff --git a/server/src/test/java/org/opensearch/index/IndexingSlowLogTests.java b/server/src/test/java/org/opensearch/index/IndexingSlowLogTests.java index 6823bb5a8225f..6d8f7f9b5a3a1 100644 --- a/server/src/test/java/org/opensearch/index/IndexingSlowLogTests.java +++ b/server/src/test/java/org/opensearch/index/IndexingSlowLogTests.java @@ -47,9 +47,9 @@ import org.opensearch.common.logging.MockAppender; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.core.index.Index; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexingSlowLog.IndexingSlowLogMessage; import org.opensearch.index.engine.Engine; import org.opensearch.index.engine.InternalEngineTests; @@ -227,7 +227,7 @@ public void testSlowLogMessageHasJsonFields() throws IOException { "routingValue", null, source, - XContentType.JSON, + MediaTypeRegistry.JSON, null ); Index index = new Index("foo", "123"); @@ -255,7 +255,7 @@ public void testSlowLogParsedDocumentPrinterSourceToLog() throws IOException { null, null, source, - XContentType.JSON, + MediaTypeRegistry.JSON, null ); Index index = new Index("foo", "123"); @@ -285,7 +285,7 @@ public void testSlowLogParsedDocumentPrinterSourceToLog() throws IOException { null, null, source, - XContentType.JSON, + MediaTypeRegistry.JSON, null ); diff --git a/server/src/test/java/org/opensearch/index/engine/InternalEngineTests.java b/server/src/test/java/org/opensearch/index/engine/InternalEngineTests.java index d58d166415446..e2dc545388412 100644 --- a/server/src/test/java/org/opensearch/index/engine/InternalEngineTests.java +++ b/server/src/test/java/org/opensearch/index/engine/InternalEngineTests.java @@ -117,9 +117,9 @@ import org.opensearch.common.util.concurrent.AbstractRunnable; import org.opensearch.common.util.concurrent.ConcurrentCollections; import org.opensearch.common.util.concurrent.ReleasableLock; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.VersionType; import org.opensearch.index.codec.CodecService; @@ -5712,7 +5712,7 @@ public void testSeqNoGenerator() throws IOException { "routing", Collections.singletonList(document), source, - XContentType.JSON, + MediaTypeRegistry.JSON, null ); diff --git a/server/src/test/java/org/opensearch/index/fielddata/BinaryDVFieldDataTests.java b/server/src/test/java/org/opensearch/index/fielddata/BinaryDVFieldDataTests.java index 06bdd2f80d762..0470840bcff5d 100644 --- a/server/src/test/java/org/opensearch/index/fielddata/BinaryDVFieldDataTests.java +++ b/server/src/test/java/org/opensearch/index/fielddata/BinaryDVFieldDataTests.java @@ -36,9 +36,9 @@ import org.apache.lucene.util.BytesRef; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.DocumentMapper; import org.opensearch.index.mapper.ParsedDocument; import org.opensearch.index.mapper.SourceToParse; @@ -79,16 +79,16 @@ public void testDocValue() throws Exception { doc.endArray(); } doc.endObject(); - ParsedDocument d = mapper.parse(new SourceToParse("test", "1", BytesReference.bytes(doc), XContentType.JSON)); + ParsedDocument d = mapper.parse(new SourceToParse("test", "1", BytesReference.bytes(doc), MediaTypeRegistry.JSON)); writer.addDocument(d.rootDoc()); BytesRef bytes1 = randomBytes(); doc = XContentFactory.jsonBuilder().startObject().field("field", bytes1.bytes, bytes1.offset, bytes1.length).endObject(); - d = mapper.parse(new SourceToParse("test", "2", BytesReference.bytes(doc), XContentType.JSON)); + d = mapper.parse(new SourceToParse("test", "2", BytesReference.bytes(doc), MediaTypeRegistry.JSON)); writer.addDocument(d.rootDoc()); doc = XContentFactory.jsonBuilder().startObject().endObject(); - d = mapper.parse(new SourceToParse("test", "3", BytesReference.bytes(doc), XContentType.JSON)); + d = mapper.parse(new SourceToParse("test", "3", BytesReference.bytes(doc), MediaTypeRegistry.JSON)); writer.addDocument(d.rootDoc()); // test remove duplicate value @@ -104,7 +104,7 @@ public void testDocValue() throws Exception { doc.endArray(); } doc.endObject(); - d = mapper.parse(new SourceToParse("test", "4", BytesReference.bytes(doc), XContentType.JSON)); + d = mapper.parse(new SourceToParse("test", "4", BytesReference.bytes(doc), MediaTypeRegistry.JSON)); writer.addDocument(d.rootDoc()); IndexFieldData indexFieldData = getForField("field"); diff --git a/server/src/test/java/org/opensearch/index/get/DocumentFieldTests.java b/server/src/test/java/org/opensearch/index/get/DocumentFieldTests.java index 46f315141ef30..1c898fd07f0b8 100644 --- a/server/src/test/java/org/opensearch/index/get/DocumentFieldTests.java +++ b/server/src/test/java/org/opensearch/index/get/DocumentFieldTests.java @@ -36,6 +36,8 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.collect.Tuple; import org.opensearch.common.document.DocumentField; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -52,7 +54,7 @@ import java.util.function.Predicate; import java.util.function.Supplier; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; @@ -60,13 +62,13 @@ public class DocumentFieldTests extends OpenSearchTestCase { public void testToXContent() { DocumentField documentField = new DocumentField("field", Arrays.asList("value1", "value2")); - String output = Strings.toString(XContentType.JSON, documentField); + String output = Strings.toString(MediaTypeRegistry.JSON, documentField); assertEquals("{\"field\":[\"value1\",\"value2\"]}", output); } public void testEqualsAndHashcode() { checkEqualsAndHashCode( - randomDocumentField(XContentType.JSON).v1(), + randomDocumentField(MediaTypeRegistry.JSON).v1(), DocumentFieldTests::copyDocumentField, DocumentFieldTests::mutateDocumentField ); @@ -102,7 +104,7 @@ private static DocumentField copyDocumentField(DocumentField documentField) { private static DocumentField mutateDocumentField(DocumentField documentField) { List> mutations = new ArrayList<>(); mutations.add(() -> new DocumentField(randomUnicodeOfCodepointLength(15), documentField.getValues())); - mutations.add(() -> new DocumentField(documentField.getName(), randomDocumentField(XContentType.JSON).v1().getValues())); + mutations.add(() -> new DocumentField(documentField.getName(), randomDocumentField(MediaTypeRegistry.JSON).v1().getValues())); final int index = randomFrom(0, 1); final DocumentField randomCandidate = mutations.get(index).get(); if (!documentField.equals(randomCandidate)) { @@ -115,12 +117,12 @@ private static DocumentField mutateDocumentField(DocumentField documentField) { } } - public static Tuple randomDocumentField(XContentType xContentType) { - return randomDocumentField(xContentType, randomBoolean(), fieldName -> false); // don't exclude any meta-fields + public static Tuple randomDocumentField(MediaType mediaType) { + return randomDocumentField(mediaType, randomBoolean(), fieldName -> false); // don't exclude any meta-fields } public static Tuple randomDocumentField( - XContentType xContentType, + MediaType mediaType, boolean isMetafield, Predicate excludeMetaFieldFilter ) { @@ -143,7 +145,7 @@ public static Tuple randomDocumentField( switch (randomIntBetween(0, 2)) { case 0: String fieldName = randomAlphaOfLengthBetween(3, 10); - Tuple, List> tuple = RandomObjects.randomStoredFieldValues(random(), xContentType); + Tuple, List> tuple = RandomObjects.randomStoredFieldValues(random(), mediaType); DocumentField input = new DocumentField(fieldName, tuple.v1()); DocumentField expected = new DocumentField(fieldName, tuple.v2()); return Tuple.tuple(input, expected); diff --git a/server/src/test/java/org/opensearch/index/get/GetResultTests.java b/server/src/test/java/org/opensearch/index/get/GetResultTests.java index fc07f238e0633..7aa50452845d7 100644 --- a/server/src/test/java/org/opensearch/index/get/GetResultTests.java +++ b/server/src/test/java/org/opensearch/index/get/GetResultTests.java @@ -38,8 +38,9 @@ import org.opensearch.common.collect.Tuple; import org.opensearch.common.document.DocumentField; import org.opensearch.common.io.stream.BytesStreamOutput; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; -import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.IdFieldMapper; @@ -61,7 +62,7 @@ import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.index.get.DocumentFieldTests.randomDocumentField; import static org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM; @@ -105,7 +106,7 @@ public void testToXContent() throws IOException { singletonMap("field1", new DocumentField("field1", singletonList("value1"))), singletonMap("field1", new DocumentField("metafield", singletonList("metavalue"))) ); - String output = Strings.toString(XContentType.JSON, getResult); + String output = Strings.toString(MediaTypeRegistry.JSON, getResult); assertEquals( "{\"_index\":\"index\",\"_id\":\"id\",\"_version\":1,\"_seq_no\":0,\"_primary_term\":1," + "\"metafield\":\"metavalue\",\"found\":true,\"_source\":{ \"field1\" : \"value1\", \"field2\":\"value2\"}," @@ -115,7 +116,7 @@ public void testToXContent() throws IOException { } { GetResult getResult = new GetResult("index", "id", UNASSIGNED_SEQ_NO, 0, 1, false, null, null, null); - String output = Strings.toString(XContentType.JSON, getResult); + String output = Strings.toString(MediaTypeRegistry.JSON, getResult); assertEquals("{\"_index\":\"index\",\"_id\":\"id\",\"found\":false}", output); } } @@ -173,7 +174,7 @@ public void testToXContentEmbedded() throws IOException { null ); - BytesReference originalBytes = toXContentEmbedded(getResult, XContentType.JSON, false); + BytesReference originalBytes = toXContentEmbedded(getResult, MediaTypeRegistry.JSON, false); assertEquals( "{\"_seq_no\":0,\"_primary_term\":1,\"found\":true,\"_source\":{\"foo\":\"bar\",\"baz\":[\"baz_0\",\"baz_1\"]}," + "\"fields\":{\"foo\":[\"bar\"],\"baz\":[\"baz_0\",\"baz_1\"]}}", @@ -184,7 +185,7 @@ public void testToXContentEmbedded() throws IOException { public void testToXContentEmbeddedNotFound() throws IOException { GetResult getResult = new GetResult("index", "id", UNASSIGNED_SEQ_NO, 0, 1, false, null, null, null); - BytesReference originalBytes = toXContentEmbedded(getResult, XContentType.JSON, false); + BytesReference originalBytes = toXContentEmbedded(getResult, MediaTypeRegistry.JSON, false); assertEquals("{\"found\":false}", originalBytes.utf8ToString()); } @@ -196,7 +197,7 @@ public void testSerializationNotFound() throws IOException { getResult.writeTo(out); getResult = new GetResult(out.bytes().streamInput()); - BytesReference originalBytes = toXContentEmbedded(getResult, XContentType.JSON, false); + BytesReference originalBytes = toXContentEmbedded(getResult, MediaTypeRegistry.JSON, false); assertEquals("{\"found\":false}", originalBytes.utf8ToString()); } @@ -212,7 +213,11 @@ public void testGetSourceAsBytes() { } public void testEqualsAndHashcode() { - checkEqualsAndHashCode(randomGetResult(XContentType.JSON).v1(), GetResultTests::copyGetResult, GetResultTests::mutateGetResult); + checkEqualsAndHashCode( + randomGetResult(MediaTypeRegistry.JSON).v1(), + GetResultTests::copyGetResult, + GetResultTests::mutateGetResult + ); } public static GetResult copyGetResult(GetResult getResult) { @@ -305,14 +310,14 @@ public static GetResult mutateGetResult(GetResult getResult) { getResult.getVersion(), getResult.isExists(), getResult.internalSourceRef(), - randomDocumentFields(XContentType.JSON, randomBoolean()).v1(), + randomDocumentFields(MediaTypeRegistry.JSON, randomBoolean()).v1(), null ) ); return randomFrom(mutations).get(); } - public static Tuple randomGetResult(XContentType xContentType) { + public static Tuple randomGetResult(MediaType mediaType) { final String index = randomAlphaOfLengthBetween(3, 10); final String type = randomAlphaOfLengthBetween(3, 10); final String id = randomAlphaOfLengthBetween(3, 10); @@ -334,11 +339,11 @@ public static Tuple randomGetResult(XContentType xContentT source = RandomObjects.randomSource(random()); } if (randomBoolean()) { - Tuple, Map> tuple = randomDocumentFields(xContentType, false); + Tuple, Map> tuple = randomDocumentFields(mediaType, false); docFields = tuple.v1(); expectedDocFields = tuple.v2(); - tuple = randomDocumentFields(xContentType, true); + tuple = randomDocumentFields(mediaType, true); metaFields = tuple.v1(); expectedMetaFields = tuple.v2(); } @@ -364,7 +369,7 @@ public static Tuple randomGetResult(XContentType xContentT } public static Tuple, Map> randomDocumentFields( - XContentType xContentType, + MediaType mediaType, boolean isMetaFields ) { int numFields = isMetaFields ? randomIntBetween(1, 3) : randomIntBetween(2, 10); @@ -378,7 +383,7 @@ public static Tuple, Map> rand || field.equals(SourceFieldMapper.NAME) || field.equals(SeqNoFieldMapper.NAME); while (fields.size() < numFields) { - Tuple tuple = randomDocumentField(xContentType, isMetaFields, excludeMetaFieldFilter); + Tuple tuple = randomDocumentField(mediaType, isMetaFields, excludeMetaFieldFilter); DocumentField getField = tuple.v1(); DocumentField expectedGetField = tuple.v2(); if (fields.putIfAbsent(getField.getName(), getField) == null) { @@ -388,8 +393,7 @@ public static Tuple, Map> rand return Tuple.tuple(fields, expectedFields); } - private static BytesReference toXContentEmbedded(GetResult getResult, XContentType xContentType, boolean humanReadable) - throws IOException { - return XContentHelper.toXContent(getResult::toXContentEmbedded, xContentType, humanReadable); + private static BytesReference toXContentEmbedded(GetResult getResult, MediaType mediaType, boolean humanReadable) throws IOException { + return org.opensearch.core.xcontent.XContentHelper.toXContent(getResult::toXContentEmbedded, mediaType, humanReadable); } } diff --git a/server/src/test/java/org/opensearch/index/mapper/CompletionFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/CompletionFieldMapperTests.java index 7b7db2ced0ab2..32b9f6ab13a4e 100644 --- a/server/src/test/java/org/opensearch/index/mapper/CompletionFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/CompletionFieldMapperTests.java @@ -49,8 +49,8 @@ import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.unit.Fuzziness; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.index.IndexSettings; @@ -187,7 +187,7 @@ public void testCompletionAnalyzerSettings() throws Exception { assertEquals( "{\"field\":{\"type\":\"completion\",\"analyzer\":\"simple\",\"search_analyzer\":\"standard\"," + "\"preserve_separators\":false,\"preserve_position_increments\":true,\"max_input_length\":50}}", - Strings.toString(XContentType.JSON, fieldMapper) + Strings.toString(MediaTypeRegistry.JSON, fieldMapper) ); } diff --git a/server/src/test/java/org/opensearch/index/mapper/DataStreamFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/DataStreamFieldMapperTests.java index 0c8dd94dc0a07..285a1a472565f 100644 --- a/server/src/test/java/org/opensearch/index/mapper/DataStreamFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/DataStreamFieldMapperTests.java @@ -11,7 +11,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchSingleNodeTestCase; import static org.hamcrest.Matchers.containsString; @@ -83,7 +83,7 @@ public void testDeeplyNestedCustomTimestampField() throws Exception { .endObject() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); assertThat(doc.rootDoc().getFields("event.meta.created_at").length, equalTo(2)); @@ -103,7 +103,7 @@ public void testDeeplyNestedCustomTimestampField() throws Exception { .endObject() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); }); @@ -125,7 +125,7 @@ private void assertDataStreamFieldMapper(String mapping, String timestampFieldNa BytesReference.bytes( XContentFactory.jsonBuilder().startObject().field(timestampFieldName, "2020-12-06T11:04:05.000Z").endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -143,7 +143,7 @@ private void assertDataStreamFieldMapper(String mapping, String timestampFieldNa BytesReference.bytes( XContentFactory.jsonBuilder().startObject().field("invalid-field-name", "2020-12-06T11:04:05.000Z").endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); }); @@ -164,7 +164,7 @@ private void assertDataStreamFieldMapper(String mapping, String timestampFieldNa .array(timestampFieldName, "2020-12-06T11:04:05.000Z", "2020-12-07T11:04:05.000Z") .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); }); diff --git a/server/src/test/java/org/opensearch/index/mapper/DocumentParserTests.java b/server/src/test/java/org/opensearch/index/mapper/DocumentParserTests.java index 0d800cf34501c..59a521668b4ea 100644 --- a/server/src/test/java/org/opensearch/index/mapper/DocumentParserTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/DocumentParserTests.java @@ -40,7 +40,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.mapper.ParseContext.Document; import org.opensearch.plugins.Plugin; @@ -1062,7 +1062,7 @@ public void testParseToJsonAndParse() throws Exception { // reparse it DocumentMapper builtDocMapper = createDocumentMapper(MapperService.SINGLE_MAPPING_NAME, builtMapping); BytesReference json = new BytesArray(copyToBytesFromClasspath("/org/opensearch/index/mapper/simple/test1.json")); - Document doc = builtDocMapper.parse(new SourceToParse("test", "1", json, XContentType.JSON)).rootDoc(); + Document doc = builtDocMapper.parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)).rootDoc(); assertThat(doc.getBinaryValue(builtDocMapper.idFieldMapper().name()), equalTo(Uid.encodeId("1"))); assertThat(doc.get(builtDocMapper.mappers().getMapper("name.first").name()), equalTo("fred")); } @@ -1074,7 +1074,7 @@ public void testSimpleParser() throws Exception { assertThat((String) docMapper.meta().get("param1"), equalTo("value1")); BytesReference json = new BytesArray(copyToBytesFromClasspath("/org/opensearch/index/mapper/simple/test1.json")); - Document doc = docMapper.parse(new SourceToParse("test", "1", json, XContentType.JSON)).rootDoc(); + Document doc = docMapper.parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)).rootDoc(); assertThat(doc.getBinaryValue(docMapper.idFieldMapper().name()), equalTo(Uid.encodeId("1"))); assertThat(doc.get(docMapper.mappers().getMapper("name.first").name()), equalTo("fred")); } @@ -1083,7 +1083,7 @@ public void testSimpleParserNoTypeNoId() throws Exception { String mapping = copyToStringFromClasspath("/org/opensearch/index/mapper/simple/test-mapping.json"); DocumentMapper docMapper = createDocumentMapper(MapperService.SINGLE_MAPPING_NAME, mapping); BytesReference json = new BytesArray(copyToBytesFromClasspath("/org/opensearch/index/mapper/simple/test1-notype-noid.json")); - Document doc = docMapper.parse(new SourceToParse("test", "1", json, XContentType.JSON)).rootDoc(); + Document doc = docMapper.parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)).rootDoc(); assertThat(doc.getBinaryValue(docMapper.idFieldMapper().name()), equalTo(Uid.encodeId("1"))); assertThat(doc.get(docMapper.mappers().getMapper("name.first").name()), equalTo("fred")); } @@ -1105,7 +1105,7 @@ public void testNoDocumentSent() throws Exception { BytesReference json = new BytesArray("".getBytes(StandardCharsets.UTF_8)); MapperParsingException e = expectThrows( MapperParsingException.class, - () -> docMapper.parse(new SourceToParse("test", "1", json, XContentType.JSON)) + () -> docMapper.parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)) ); assertThat(e.getMessage(), equalTo("failed to parse, document is empty")); } diff --git a/server/src/test/java/org/opensearch/index/mapper/DynamicMappingTests.java b/server/src/test/java/org/opensearch/index/mapper/DynamicMappingTests.java index fa70e29836779..5cc3a875c81f0 100644 --- a/server/src/test/java/org/opensearch/index/mapper/DynamicMappingTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/DynamicMappingTests.java @@ -34,7 +34,7 @@ import org.opensearch.common.CheckedConsumer; import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; @@ -184,7 +184,7 @@ public void testField() throws Exception { assertEquals( "{\"_doc\":{\"properties\":{\"foo\":{\"type\":\"text\",\"fields\":" + "{\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}}}}}", - Strings.toString(XContentType.JSON, doc.dynamicMappingsUpdate()) + Strings.toString(MediaTypeRegistry.JSON, doc.dynamicMappingsUpdate()) ); } @@ -200,9 +200,9 @@ public void testIncremental() throws Exception { })); assertNotNull(doc.dynamicMappingsUpdate()); - assertThat(Strings.toString(XContentType.JSON, doc.dynamicMappingsUpdate()), containsString("{\"bar\":")); + assertThat(Strings.toString(MediaTypeRegistry.JSON, doc.dynamicMappingsUpdate()), containsString("{\"bar\":")); // field is NOT in the update - assertThat(Strings.toString(XContentType.JSON, doc.dynamicMappingsUpdate()), not(containsString("{\"field\":"))); + assertThat(Strings.toString(MediaTypeRegistry.JSON, doc.dynamicMappingsUpdate()), not(containsString("{\"field\":"))); } public void testIntroduceTwoFields() throws Exception { @@ -214,8 +214,8 @@ public void testIntroduceTwoFields() throws Exception { })); assertNotNull(doc.dynamicMappingsUpdate()); - assertThat(Strings.toString(XContentType.JSON, doc.dynamicMappingsUpdate()), containsString("\"foo\":{")); - assertThat(Strings.toString(XContentType.JSON, doc.dynamicMappingsUpdate()), containsString("\"bar\":{")); + assertThat(Strings.toString(MediaTypeRegistry.JSON, doc.dynamicMappingsUpdate()), containsString("\"foo\":{")); + assertThat(Strings.toString(MediaTypeRegistry.JSON, doc.dynamicMappingsUpdate()), containsString("\"bar\":{")); } public void testObject() throws Exception { @@ -230,7 +230,7 @@ public void testObject() throws Exception { assertNotNull(doc.dynamicMappingsUpdate()); assertThat( - Strings.toString(XContentType.JSON, doc.dynamicMappingsUpdate()), + Strings.toString(MediaTypeRegistry.JSON, doc.dynamicMappingsUpdate()), containsString("{\"foo\":{\"properties\":{\"bar\":{\"properties\":{\"baz\":{\"type\":\"text\"") ); } @@ -241,7 +241,7 @@ public void testArray() throws Exception { ParsedDocument doc = mapper.parse(source(b -> b.startArray("foo").value("bar").value("baz").endArray())); assertNotNull(doc.dynamicMappingsUpdate()); - assertThat(Strings.toString(XContentType.JSON, doc.dynamicMappingsUpdate()), containsString("{\"foo\":{\"type\":\"text\"")); + assertThat(Strings.toString(MediaTypeRegistry.JSON, doc.dynamicMappingsUpdate()), containsString("{\"foo\":{\"type\":\"text\"")); } public void testInnerDynamicMapping() throws Exception { @@ -257,7 +257,7 @@ public void testInnerDynamicMapping() throws Exception { assertNotNull(doc.dynamicMappingsUpdate()); assertThat( - Strings.toString(XContentType.JSON, doc.dynamicMappingsUpdate()), + Strings.toString(MediaTypeRegistry.JSON, doc.dynamicMappingsUpdate()), containsString("{\"field\":{\"properties\":{\"bar\":{\"properties\":{\"baz\":{\"type\":\"text\"") ); } @@ -277,7 +277,7 @@ public void testComplexArray() throws Exception { assertEquals( "{\"_doc\":{\"properties\":{\"foo\":{\"properties\":{\"bar\":{\"type\":\"text\",\"fields\":{" + "\"keyword\":{\"type\":\"keyword\",\"ignore_above\":256}}},\"baz\":{\"type\":\"long\"}}}}}}", - Strings.toString(XContentType.JSON, doc.dynamicMappingsUpdate()) + Strings.toString(MediaTypeRegistry.JSON, doc.dynamicMappingsUpdate()) ); } diff --git a/server/src/test/java/org/opensearch/index/mapper/FieldFilterMapperPluginTests.java b/server/src/test/java/org/opensearch/index/mapper/FieldFilterMapperPluginTests.java index 2c825401ab94a..be5fc84a2bfc7 100644 --- a/server/src/test/java/org/opensearch/index/mapper/FieldFilterMapperPluginTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/FieldFilterMapperPluginTests.java @@ -40,7 +40,7 @@ import org.opensearch.action.fieldcaps.FieldCapabilitiesRequest; import org.opensearch.action.fieldcaps.FieldCapabilitiesResponse; import org.opensearch.cluster.metadata.MappingMetadata; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.indices.IndicesModule; import org.opensearch.plugins.MapperPlugin; import org.opensearch.plugins.Plugin; @@ -73,7 +73,7 @@ protected Collection> getPlugins() { public void putMappings() { assertAcked(client().admin().indices().prepareCreate("index1")); assertAcked(client().admin().indices().prepareCreate("filtered")); - assertAcked(client().admin().indices().preparePutMapping("index1", "filtered").setSource(TEST_ITEM, XContentType.JSON)); + assertAcked(client().admin().indices().preparePutMapping("index1", "filtered").setSource(TEST_ITEM, MediaTypeRegistry.JSON)); } public void testGetMappings() { diff --git a/server/src/test/java/org/opensearch/index/mapper/FieldNamesFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/FieldNamesFieldMapperTests.java index 829a7aa9cf6db..1049cb3b9fb51 100644 --- a/server/src/test/java/org/opensearch/index/mapper/FieldNamesFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/FieldNamesFieldMapperTests.java @@ -37,7 +37,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchSingleNodeTestCase; import java.util.ArrayList; @@ -118,7 +118,7 @@ public void testInjectIntoDocDuringParsing() throws Exception { BytesReference.bytes( XContentFactory.jsonBuilder().startObject().field("a", "100").startObject("b").field("c", 42).endObject().endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -152,7 +152,7 @@ public void testExplicitEnabled() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "value").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -181,7 +181,7 @@ public void testDisabled() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "value").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); diff --git a/server/src/test/java/org/opensearch/index/mapper/FlatObjectFieldDataTests.java b/server/src/test/java/org/opensearch/index/mapper/FlatObjectFieldDataTests.java index e7c446750d15d..76c30387ea3a2 100644 --- a/server/src/test/java/org/opensearch/index/mapper/FlatObjectFieldDataTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/FlatObjectFieldDataTests.java @@ -11,7 +11,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.index.fielddata.AbstractFieldDataTestCase; import org.opensearch.index.fielddata.IndexFieldData; @@ -41,7 +41,7 @@ public void testDocValue() throws Exception { final DocumentMapper mapper = mapperService.documentMapperParser().parse("test", new CompressedXContent(mapping)); XContentBuilder json = XContentFactory.jsonBuilder().startObject().startObject("field").field("foo", "bar").endObject().endObject(); - ParsedDocument d = mapper.parse(new SourceToParse("test", "1", BytesReference.bytes(json), XContentType.JSON)); + ParsedDocument d = mapper.parse(new SourceToParse("test", "1", BytesReference.bytes(json), MediaTypeRegistry.JSON)); writer.addDocument(d.rootDoc()); writer.commit(); diff --git a/server/src/test/java/org/opensearch/index/mapper/GenericStoreDynamicTemplateTests.java b/server/src/test/java/org/opensearch/index/mapper/GenericStoreDynamicTemplateTests.java index 1834b087e3bdd..6d816c6aab69c 100644 --- a/server/src/test/java/org/opensearch/index/mapper/GenericStoreDynamicTemplateTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/GenericStoreDynamicTemplateTests.java @@ -34,7 +34,7 @@ import org.apache.lucene.index.IndexableField; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.ParseContext.Document; import org.opensearch.test.OpenSearchSingleNodeTestCase; @@ -47,17 +47,17 @@ public class GenericStoreDynamicTemplateTests extends OpenSearchSingleNodeTestCa public void testSimple() throws Exception { String mapping = copyToStringFromClasspath("/org/opensearch/index/mapper/dynamictemplate/genericstore/test-mapping.json"); IndexService index = createIndex("test"); - client().admin().indices().preparePutMapping("test").setSource(mapping, XContentType.JSON).get(); + client().admin().indices().preparePutMapping("test").setSource(mapping, MediaTypeRegistry.JSON).get(); MapperService mapperService = index.mapperService(); byte[] json = copyToBytesFromClasspath("/org/opensearch/index/mapper/dynamictemplate/genericstore/test-data.json"); ParsedDocument parsedDoc = mapperService.documentMapper() - .parse(new SourceToParse("test", "1", new BytesArray(json), XContentType.JSON)); + .parse(new SourceToParse("test", "1", new BytesArray(json), MediaTypeRegistry.JSON)); client().admin() .indices() .preparePutMapping("test") - .setSource(parsedDoc.dynamicMappingsUpdate().toString(), XContentType.JSON) + .setSource(parsedDoc.dynamicMappingsUpdate().toString(), MediaTypeRegistry.JSON) .get(); Document doc = parsedDoc.rootDoc(); diff --git a/server/src/test/java/org/opensearch/index/mapper/GeoShapeFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/GeoShapeFieldMapperTests.java index dc5e724f68094..016862e3ffabc 100644 --- a/server/src/test/java/org/opensearch/index/mapper/GeoShapeFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/GeoShapeFieldMapperTests.java @@ -33,8 +33,8 @@ import org.opensearch.common.Explicit; import org.opensearch.common.geo.builders.ShapeBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.plugins.Plugin; @@ -229,7 +229,7 @@ public void testSerializeDefaults() throws Exception { DocumentMapper mapper = createDocumentMapper(fieldMapping(this::minimalMapping)); assertThat( Strings.toString( - XContentType.JSON, + MediaTypeRegistry.JSON, mapper.mappers().getMapper("field"), new ToXContent.MapParams(Collections.singletonMap("include_defaults", "true")) ), diff --git a/server/src/test/java/org/opensearch/index/mapper/IdFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/IdFieldMapperTests.java index 5188fb8ae2b6b..d9a8e213ea5cb 100644 --- a/server/src/test/java/org/opensearch/index/mapper/IdFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/IdFieldMapperTests.java @@ -39,7 +39,7 @@ import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.settings.Settings; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.MapperService.MergeReason; import org.opensearch.indices.IndicesService; @@ -73,7 +73,7 @@ public void testIncludeInObjectNotAllowed() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("_id", "1").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); fail("Expected failure to parse metadata field"); @@ -89,7 +89,7 @@ public void testDefaults() throws IOException { Settings indexSettings = Settings.EMPTY; MapperService mapperService = createIndex("test", indexSettings).mapperService(); DocumentMapper mapper = mapperService.merge("type", new CompressedXContent("{\"type\":{}}"), MergeReason.MAPPING_UPDATE); - ParsedDocument document = mapper.parse(new SourceToParse("index", "id", new BytesArray("{}"), XContentType.JSON)); + ParsedDocument document = mapper.parse(new SourceToParse("index", "id", new BytesArray("{}"), MediaTypeRegistry.JSON)); IndexableField[] fields = document.rootDoc().getFields(IdFieldMapper.NAME); assertEquals(1, fields.length); assertEquals(IndexOptions.DOCS, fields[0].fieldType().indexOptions()); diff --git a/server/src/test/java/org/opensearch/index/mapper/IndexFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/IndexFieldMapperTests.java index e6f84bea08a96..ee0197ca3f6e9 100644 --- a/server/src/test/java/org/opensearch/index/mapper/IndexFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/IndexFieldMapperTests.java @@ -35,7 +35,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.plugins.Plugin; import org.opensearch.test.OpenSearchSingleNodeTestCase; import org.opensearch.test.InternalSettingsPlugin; @@ -64,7 +64,7 @@ public void testDefaultDisabledIndexMapper() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "value").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); diff --git a/server/src/test/java/org/opensearch/index/mapper/IpRangeFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/IpRangeFieldMapperTests.java index 9eb05c9ab1b15..421ef5bab0764 100644 --- a/server/src/test/java/org/opensearch/index/mapper/IpRangeFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/IpRangeFieldMapperTests.java @@ -37,9 +37,9 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.network.InetAddresses; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.index.IndexService; import org.opensearch.index.termvectors.TermVectorsService; @@ -173,6 +173,6 @@ private final SourceToParse source(CheckedConsumer XContentBuilder builder = JsonXContent.contentBuilder().startObject(); build.accept(builder); builder.endObject(); - return new SourceToParse("test", "1", BytesReference.bytes(builder), XContentType.JSON); + return new SourceToParse("test", "1", BytesReference.bytes(builder), MediaTypeRegistry.JSON); } } diff --git a/server/src/test/java/org/opensearch/index/mapper/JavaMultiFieldMergeTests.java b/server/src/test/java/org/opensearch/index/mapper/JavaMultiFieldMergeTests.java index f0bc7c9f8c616..646ba48b19552 100644 --- a/server/src/test/java/org/opensearch/index/mapper/JavaMultiFieldMergeTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/JavaMultiFieldMergeTests.java @@ -36,7 +36,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.mapper.ParseContext.Document; import org.opensearch.test.OpenSearchSingleNodeTestCase; @@ -56,7 +56,7 @@ public void testMergeMultiField() throws Exception { assertThat(mapperService.fieldType("name.indexed"), nullValue()); BytesReference json = BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("name", "some name").endObject()); - Document doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, XContentType.JSON)).rootDoc(); + Document doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)).rootDoc(); IndexableField f = doc.getField("name"); assertThat(f, notNullValue()); f = doc.getField("name.indexed"); @@ -72,7 +72,7 @@ public void testMergeMultiField() throws Exception { assertThat(mapperService.fieldType("name.not_indexed2"), nullValue()); assertThat(mapperService.fieldType("name.not_indexed3"), nullValue()); - doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, XContentType.JSON)).rootDoc(); + doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)).rootDoc(); f = doc.getField("name"); assertThat(f, notNullValue()); f = doc.getField("name.indexed"); @@ -109,7 +109,7 @@ public void testUpgradeFromMultiFieldTypeToMultiFields() throws Exception { assertThat(mapperService.fieldType("name.indexed"), nullValue()); BytesReference json = BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("name", "some name").endObject()); - Document doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, XContentType.JSON)).rootDoc(); + Document doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)).rootDoc(); IndexableField f = doc.getField("name"); assertThat(f, notNullValue()); f = doc.getField("name.indexed"); @@ -125,7 +125,7 @@ public void testUpgradeFromMultiFieldTypeToMultiFields() throws Exception { assertThat(mapperService.fieldType("name.not_indexed2"), nullValue()); assertThat(mapperService.fieldType("name.not_indexed3"), nullValue()); - doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, XContentType.JSON)).rootDoc(); + doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)).rootDoc(); f = doc.getField("name"); assertThat(f, notNullValue()); f = doc.getField("name.indexed"); diff --git a/server/src/test/java/org/opensearch/index/mapper/LegacyGeoShapeFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/LegacyGeoShapeFieldMapperTests.java index 3e8dbe5b9d600..048b51d39ca6c 100644 --- a/server/src/test/java/org/opensearch/index/mapper/LegacyGeoShapeFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/LegacyGeoShapeFieldMapperTests.java @@ -42,8 +42,8 @@ import org.opensearch.common.geo.ShapeRelation; import org.opensearch.common.geo.SpatialStrategy; import org.opensearch.common.geo.builders.ShapeBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.geometry.Point; @@ -539,13 +539,13 @@ public void testSerializeDefaults() throws Exception { ToXContent.Params includeDefaults = new ToXContent.MapParams(singletonMap("include_defaults", "true")); { DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> b.field("type", "geo_shape").field("tree", "quadtree"))); - String serialized = Strings.toString(XContentType.JSON, mapper.mappers().getMapper("field"), includeDefaults); + String serialized = Strings.toString(MediaTypeRegistry.JSON, mapper.mappers().getMapper("field"), includeDefaults); assertTrue(serialized, serialized.contains("\"precision\":\"50.0m\"")); assertTrue(serialized, serialized.contains("\"tree_levels\":21")); } { DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> b.field("type", "geo_shape").field("tree", "geohash"))); - String serialized = Strings.toString(XContentType.JSON, mapper.mappers().getMapper("field"), includeDefaults); + String serialized = Strings.toString(MediaTypeRegistry.JSON, mapper.mappers().getMapper("field"), includeDefaults); assertTrue(serialized, serialized.contains("\"precision\":\"50.0m\"")); assertTrue(serialized, serialized.contains("\"tree_levels\":9")); } @@ -553,7 +553,7 @@ public void testSerializeDefaults() throws Exception { DocumentMapper mapper = createDocumentMapper( fieldMapping(b -> b.field("type", "geo_shape").field("tree", "quadtree").field("tree_levels", "6")) ); - String serialized = Strings.toString(XContentType.JSON, mapper.mappers().getMapper("field"), includeDefaults); + String serialized = Strings.toString(MediaTypeRegistry.JSON, mapper.mappers().getMapper("field"), includeDefaults); assertFalse(serialized, serialized.contains("\"precision\":")); assertTrue(serialized, serialized.contains("\"tree_levels\":6")); } @@ -561,7 +561,7 @@ public void testSerializeDefaults() throws Exception { DocumentMapper mapper = createDocumentMapper( fieldMapping(b -> b.field("type", "geo_shape").field("tree", "quadtree").field("precision", "6")) ); - String serialized = Strings.toString(XContentType.JSON, mapper.mappers().getMapper("field"), includeDefaults); + String serialized = Strings.toString(MediaTypeRegistry.JSON, mapper.mappers().getMapper("field"), includeDefaults); assertTrue(serialized, serialized.contains("\"precision\":\"6.0m\"")); assertFalse(serialized, serialized.contains("\"tree_levels\":")); } @@ -569,7 +569,7 @@ public void testSerializeDefaults() throws Exception { DocumentMapper mapper = createDocumentMapper( fieldMapping(b -> b.field("type", "geo_shape").field("tree", "quadtree").field("precision", "6m").field("tree_levels", "5")) ); - String serialized = Strings.toString(XContentType.JSON, mapper.mappers().getMapper("field"), includeDefaults); + String serialized = Strings.toString(MediaTypeRegistry.JSON, mapper.mappers().getMapper("field"), includeDefaults); assertTrue(serialized, serialized.contains("\"precision\":\"6.0m\"")); assertTrue(serialized, serialized.contains("\"tree_levels\":5")); } @@ -591,7 +591,7 @@ public void testPointsOnlyDefaultsWithTermStrategy() throws IOException { assertThat(strategy.getGrid().getMaxLevels(), equalTo(23)); assertThat(strategy.isPointsOnly(), equalTo(true)); // term strategy changes the default for points_only, check that we handle it correctly - assertThat(Strings.toString(XContentType.JSON, geoShapeFieldMapper), not(containsString("points_only"))); + assertThat(Strings.toString(MediaTypeRegistry.JSON, geoShapeFieldMapper), not(containsString("points_only"))); assertFieldWarnings("tree", "precision", "strategy"); } diff --git a/server/src/test/java/org/opensearch/index/mapper/MultiFieldTests.java b/server/src/test/java/org/opensearch/index/mapper/MultiFieldTests.java index 6d483959289f4..dc7f9d1f96f92 100644 --- a/server/src/test/java/org/opensearch/index/mapper/MultiFieldTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/MultiFieldTests.java @@ -38,9 +38,9 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.support.XContentMapValues; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.ParseContext.Document; @@ -75,7 +75,7 @@ private void testMultiField(String mapping) throws Exception { .merge(MapperService.SINGLE_MAPPING_NAME, new CompressedXContent(mapping), MapperService.MergeReason.MAPPING_UPDATE); BytesReference json = new BytesArray(copyToBytesFromClasspath("/org/opensearch/index/mapper/multifield/test-data.json")); - Document doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, XContentType.JSON)).rootDoc(); + Document doc = mapperService.documentMapper().parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)).rootDoc(); IndexableField f = doc.getField("name"); assertThat(f.name(), equalTo("name")); @@ -154,7 +154,7 @@ public void testBuildThenParse() throws Exception { .parse(MapperService.SINGLE_MAPPING_NAME, new CompressedXContent(builtMapping)); BytesReference json = new BytesArray(copyToBytesFromClasspath("/org/opensearch/index/mapper/multifield/test-data.json")); - Document doc = docMapper.parse(new SourceToParse("test", "1", json, XContentType.JSON)).rootDoc(); + Document doc = docMapper.parse(new SourceToParse("test", "1", json, MediaTypeRegistry.JSON)).rootDoc(); IndexableField f = doc.getField("name"); assertThat(f.name(), equalTo("name")); diff --git a/server/src/test/java/org/opensearch/index/mapper/NestedObjectMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/NestedObjectMapperTests.java index 4d9bef87ddc41..20a2204f123fc 100644 --- a/server/src/test/java/org/opensearch/index/mapper/NestedObjectMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/NestedObjectMapperTests.java @@ -36,9 +36,9 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.MapperService.MergeReason; import org.opensearch.index.mapper.ObjectMapper.Dynamic; import org.opensearch.plugins.Plugin; @@ -86,7 +86,7 @@ public void testEmptyNested() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "value").nullField("nested1").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -99,7 +99,7 @@ public void testEmptyNested() throws Exception { BytesReference.bytes( XContentFactory.jsonBuilder().startObject().field("field", "value").startArray("nested").endArray().endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -141,7 +141,7 @@ public void testSingleNested() throws Exception { .endObject() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -172,7 +172,7 @@ public void testSingleNested() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -253,7 +253,7 @@ public void testMultiNested() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -346,7 +346,7 @@ public void testMultiObjectAndNested1() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -440,7 +440,7 @@ public void testMultiObjectAndNested2() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -533,7 +533,7 @@ public void testMultiRootAndNested1() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -610,7 +610,7 @@ public void testMultipleLevelsIncludeRoot1() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -682,7 +682,7 @@ public void testMultipleLevelsIncludeRoot2() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -760,7 +760,7 @@ public void testMultipleLevelsIncludeRootWithMerge() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -814,7 +814,7 @@ public void testNestedArrayStrict() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -949,7 +949,7 @@ public void testLimitNestedDocsDefaultSettings() throws Exception { docBuilder.endArray(); } docBuilder.endObject(); - SourceToParse source1 = new SourceToParse("test1", "1", BytesReference.bytes(docBuilder), XContentType.JSON); + SourceToParse source1 = new SourceToParse("test1", "1", BytesReference.bytes(docBuilder), MediaTypeRegistry.JSON); MapperParsingException e = expectThrows(MapperParsingException.class, () -> docMapper.parse(source1)); assertEquals( "The number of nested documents has exceeded the allowed limit of [" @@ -993,7 +993,7 @@ public void testLimitNestedDocs() throws Exception { docBuilder.endArray(); } docBuilder.endObject(); - SourceToParse source1 = new SourceToParse("test1", "1", BytesReference.bytes(docBuilder), XContentType.JSON); + SourceToParse source1 = new SourceToParse("test1", "1", BytesReference.bytes(docBuilder), MediaTypeRegistry.JSON); ParsedDocument doc = docMapper.parse(source1); assertThat(doc.docs().size(), equalTo(3)); @@ -1010,7 +1010,7 @@ public void testLimitNestedDocs() throws Exception { docBuilder2.endArray(); } docBuilder2.endObject(); - SourceToParse source2 = new SourceToParse("test1", "2", BytesReference.bytes(docBuilder2), XContentType.JSON); + SourceToParse source2 = new SourceToParse("test1", "2", BytesReference.bytes(docBuilder2), MediaTypeRegistry.JSON); MapperParsingException e = expectThrows(MapperParsingException.class, () -> docMapper.parse(source2)); assertEquals( "The number of nested documents has exceeded the allowed limit of [" @@ -1061,7 +1061,7 @@ public void testLimitNestedDocsMultipleNestedFields() throws Exception { docBuilder.endArray(); } docBuilder.endObject(); - SourceToParse source1 = new SourceToParse("test1", "1", BytesReference.bytes(docBuilder), XContentType.JSON); + SourceToParse source1 = new SourceToParse("test1", "1", BytesReference.bytes(docBuilder), MediaTypeRegistry.JSON); ParsedDocument doc = docMapper.parse(source1); assertThat(doc.docs().size(), equalTo(3)); @@ -1083,7 +1083,7 @@ public void testLimitNestedDocsMultipleNestedFields() throws Exception { } docBuilder2.endObject(); - SourceToParse source2 = new SourceToParse("test1", "2", BytesReference.bytes(docBuilder2), XContentType.JSON); + SourceToParse source2 = new SourceToParse("test1", "2", BytesReference.bytes(docBuilder2), MediaTypeRegistry.JSON); MapperParsingException e = expectThrows(MapperParsingException.class, () -> docMapper.parse(source2)); assertEquals( "The number of nested documents has exceeded the allowed limit of [" diff --git a/server/src/test/java/org/opensearch/index/mapper/NestedPathFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/NestedPathFieldMapperTests.java index 9823c54b4ab13..c27134e283e9d 100644 --- a/server/src/test/java/org/opensearch/index/mapper/NestedPathFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/NestedPathFieldMapperTests.java @@ -12,7 +12,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchSingleNodeTestCase; import java.io.IOException; @@ -30,7 +30,7 @@ public void testDefaultConfig() throws IOException { new CompressedXContent("{\"" + MapperService.SINGLE_MAPPING_NAME + "\":{}}"), MapperService.MergeReason.MAPPING_UPDATE ); - ParsedDocument document = mapper.parse(new SourceToParse("index", "id", new BytesArray("{}"), XContentType.JSON)); + ParsedDocument document = mapper.parse(new SourceToParse("index", "id", new BytesArray("{}"), MediaTypeRegistry.JSON)); assertEquals(Collections.emptyList(), Arrays.asList(document.rootDoc().getFields(NestedPathFieldMapper.NAME))); } diff --git a/server/src/test/java/org/opensearch/index/mapper/NullValueObjectMappingTests.java b/server/src/test/java/org/opensearch/index/mapper/NullValueObjectMappingTests.java index 565031a603360..c9b5e8292d78b 100644 --- a/server/src/test/java/org/opensearch/index/mapper/NullValueObjectMappingTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/NullValueObjectMappingTests.java @@ -35,7 +35,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchSingleNodeTestCase; import java.io.IOException; @@ -67,7 +67,7 @@ public void testNullValueObject() throws IOException { BytesReference.bytes( XContentFactory.jsonBuilder().startObject().startObject("obj1").endObject().field("value1", "test1").endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -78,7 +78,7 @@ public void testNullValueObject() throws IOException { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().nullField("obj1").field("value1", "test1").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -97,7 +97,7 @@ public void testNullValueObject() throws IOException { .field("value1", "test1") .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); diff --git a/server/src/test/java/org/opensearch/index/mapper/NumberFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/NumberFieldMapperTests.java index e2524808409b0..610b69a7fdf88 100644 --- a/server/src/test/java/org/opensearch/index/mapper/NumberFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/NumberFieldMapperTests.java @@ -35,8 +35,8 @@ import org.apache.lucene.index.DocValuesType; import org.apache.lucene.index.IndexableField; import org.opensearch.core.common.bytes.BytesArray; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.NumberFieldMapper.NumberType; import org.opensearch.index.mapper.NumberFieldTypeTests.OutOfRangeSpec; import org.opensearch.index.termvectors.TermVectorsService; @@ -315,7 +315,7 @@ public void testOutOfRangeValues() throws IOException { public void testLongIndexingOutOfRange() throws Exception { DocumentMapper mapper = createDocumentMapper(fieldMapping(b -> b.field("type", "long").field("ignore_malformed", true))); ParsedDocument doc = mapper.parse( - source(b -> b.rawField("field", new BytesArray("9223372036854775808").streamInput(), XContentType.JSON)) + source(b -> b.rawField("field", new BytesArray("9223372036854775808").streamInput(), MediaTypeRegistry.JSON)) ); assertEquals(0, doc.rootDoc().getFields("field").length); } diff --git a/server/src/test/java/org/opensearch/index/mapper/NumberFieldTypeTests.java b/server/src/test/java/org/opensearch/index/mapper/NumberFieldTypeTests.java index 547c4696ce3ed..8776cfac918c2 100644 --- a/server/src/test/java/org/opensearch/index/mapper/NumberFieldTypeTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/NumberFieldTypeTests.java @@ -60,8 +60,8 @@ import org.opensearch.common.Numbers; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.BigArrays; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.index.IndexSettings; import org.opensearch.index.document.SortedUnsignedLongDocValuesRangeQuery; @@ -798,7 +798,7 @@ static OutOfRangeSpec of(NumberType t, Object v, String m) { public void write(XContentBuilder b) throws IOException { if (value instanceof BigInteger) { - b.rawField("field", new ByteArrayInputStream(value.toString().getBytes("UTF-8")), XContentType.JSON); + b.rawField("field", new ByteArrayInputStream(value.toString().getBytes("UTF-8")), MediaTypeRegistry.JSON); } else { b.field("field", value); } diff --git a/server/src/test/java/org/opensearch/index/mapper/ObjectMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/ObjectMapperTests.java index 61d64431abdbb..4892e5c2524a7 100644 --- a/server/src/test/java/org/opensearch/index/mapper/ObjectMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/ObjectMapperTests.java @@ -35,7 +35,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.mapper.MapperService.MergeReason; import org.opensearch.index.mapper.ObjectMapper.Dynamic; import org.opensearch.plugins.Plugin; @@ -74,7 +74,7 @@ public void testDifferentInnerObjectTokenFailure() throws Exception { + " \"value\":\"value\"\n" + " }" ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); }); diff --git a/server/src/test/java/org/opensearch/index/mapper/PathMatchDynamicTemplateTests.java b/server/src/test/java/org/opensearch/index/mapper/PathMatchDynamicTemplateTests.java index 36f63f9d90ab0..1fed040a449e8 100644 --- a/server/src/test/java/org/opensearch/index/mapper/PathMatchDynamicTemplateTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/PathMatchDynamicTemplateTests.java @@ -34,7 +34,7 @@ import org.apache.lucene.index.IndexableField; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.mapper.ParseContext.Document; import org.opensearch.test.OpenSearchSingleNodeTestCase; @@ -47,17 +47,17 @@ public class PathMatchDynamicTemplateTests extends OpenSearchSingleNodeTestCase public void testSimple() throws Exception { String mapping = copyToStringFromClasspath("/org/opensearch/index/mapper/dynamictemplate/pathmatch/test-mapping.json"); IndexService index = createIndex("test"); - client().admin().indices().preparePutMapping("test").setSource(mapping, XContentType.JSON).get(); + client().admin().indices().preparePutMapping("test").setSource(mapping, MediaTypeRegistry.JSON).get(); MapperService mapperService = index.mapperService(); byte[] json = copyToBytesFromClasspath("/org/opensearch/index/mapper/dynamictemplate/pathmatch/test-data.json"); ParsedDocument parsedDoc = mapperService.documentMapper() - .parse(new SourceToParse("test", "1", new BytesArray(json), XContentType.JSON)); + .parse(new SourceToParse("test", "1", new BytesArray(json), MediaTypeRegistry.JSON)); client().admin() .indices() .preparePutMapping("test") - .setSource(parsedDoc.dynamicMappingsUpdate().toString(), XContentType.JSON) + .setSource(parsedDoc.dynamicMappingsUpdate().toString(), MediaTypeRegistry.JSON) .get(); Document doc = parsedDoc.rootDoc(); diff --git a/server/src/test/java/org/opensearch/index/mapper/RoutingFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/RoutingFieldMapperTests.java index 8c0c5e2eaa7e6..9182efaf59ecf 100644 --- a/server/src/test/java/org/opensearch/index/mapper/RoutingFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/RoutingFieldMapperTests.java @@ -35,7 +35,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.OpenSearchSingleNodeTestCase; import static org.hamcrest.Matchers.containsString; @@ -54,7 +54,7 @@ public void testRoutingMapper() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "value").endObject()), - XContentType.JSON, + MediaTypeRegistry.JSON, "routing_value" ) ); @@ -75,7 +75,7 @@ public void testIncludeInObjectNotAllowed() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("_routing", "foo").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); fail("Expected failure to parse metadata field"); diff --git a/server/src/test/java/org/opensearch/index/mapper/SourceFieldMapperTests.java b/server/src/test/java/org/opensearch/index/mapper/SourceFieldMapperTests.java index 425a0fd1f1bdd..c7a1ea57d12d8 100644 --- a/server/src/test/java/org/opensearch/index/mapper/SourceFieldMapperTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/SourceFieldMapperTests.java @@ -75,11 +75,11 @@ public void testNoFormat() throws Exception { "test", "1", BytesReference.bytes(XContentFactory.jsonBuilder().startObject().field("field", "value").endObject()), - XContentType.JSON + MediaTypeRegistry.JSON ) ); - assertThat(MediaTypeRegistry.xContent(doc.source().toBytesRef().bytes), equalTo(XContentType.JSON)); + assertThat(MediaTypeRegistry.xContent(doc.source().toBytesRef().bytes), equalTo(MediaTypeRegistry.JSON)); documentMapper = parser.parse("type", new CompressedXContent(mapping)); doc = documentMapper.parse( @@ -124,7 +124,7 @@ public void testIncludes() throws Exception { .endObject() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -167,7 +167,7 @@ public void testExcludes() throws Exception { .endObject() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); @@ -314,8 +314,8 @@ public void testSourceObjectContainsExtraTokens() throws Exception { .parse("type", new CompressedXContent(mapping)); try { - documentMapper.parse(new SourceToParse("test", "1", new BytesArray("{}}"), XContentType.JSON)); // extra end object - // (invalid JSON) + documentMapper.parse(new SourceToParse("test", "1", new BytesArray("{}}"), MediaTypeRegistry.JSON)); // extra end object + // (invalid JSON) fail("Expected parse exception"); } catch (MapperParsingException e) { assertNotNull(e.getRootCause()); diff --git a/server/src/test/java/org/opensearch/index/mapper/StoredNumericValuesTests.java b/server/src/test/java/org/opensearch/index/mapper/StoredNumericValuesTests.java index 055f41b157205..4e7482c0557d1 100644 --- a/server/src/test/java/org/opensearch/index/mapper/StoredNumericValuesTests.java +++ b/server/src/test/java/org/opensearch/index/mapper/StoredNumericValuesTests.java @@ -42,7 +42,7 @@ import org.opensearch.common.lucene.Lucene; import org.opensearch.common.util.set.Sets; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.fieldvisitor.CustomFieldsVisitor; import org.opensearch.index.mapper.MapperService.MergeReason; import org.opensearch.test.OpenSearchSingleNodeTestCase; @@ -135,7 +135,7 @@ public void testBytesAndNumericRepresentation() throws Exception { .field("field11", "1") .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); diff --git a/server/src/test/java/org/opensearch/index/query/WrapperQueryBuilderTests.java b/server/src/test/java/org/opensearch/index/query/WrapperQueryBuilderTests.java index 09605bcd0a8dd..4135f6e0ef049 100644 --- a/server/src/test/java/org/opensearch/index/query/WrapperQueryBuilderTests.java +++ b/server/src/test/java/org/opensearch/index/query/WrapperQueryBuilderTests.java @@ -40,8 +40,7 @@ import org.opensearch.core.common.ParsingException; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.test.AbstractQueryTestCase; import java.io.IOException; @@ -70,7 +69,7 @@ protected WrapperQueryBuilder doCreateTestQueryBuilder() { QueryBuilder wrappedQuery = RandomQueryBuilder.createQuery(random()); BytesReference bytes; try { - bytes = XContentHelper.toXContent(wrappedQuery, XContentType.JSON, false); + bytes = org.opensearch.core.xcontent.XContentHelper.toXContent(wrappedQuery, MediaTypeRegistry.JSON, false); } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/server/src/test/java/org/opensearch/index/replication/IndexLevelReplicationTests.java b/server/src/test/java/org/opensearch/index/replication/IndexLevelReplicationTests.java index d262b5abec0f3..9465f73394e40 100644 --- a/server/src/test/java/org/opensearch/index/replication/IndexLevelReplicationTests.java +++ b/server/src/test/java/org/opensearch/index/replication/IndexLevelReplicationTests.java @@ -48,7 +48,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.iterable.Iterables; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.engine.Engine; import org.opensearch.index.engine.EngineFactory; @@ -173,7 +173,7 @@ public void cleanFiles( public void testRetryAppendOnlyAfterRecovering() throws Exception { try (ReplicationGroup shards = createGroup(0)) { shards.startAll(); - final IndexRequest originalRequest = new IndexRequest(index.getName()).source("{}", XContentType.JSON); + final IndexRequest originalRequest = new IndexRequest(index.getName()).source("{}", MediaTypeRegistry.JSON); originalRequest.process(Version.CURRENT, null, index.getName()); final IndexRequest retryRequest = copyIndexRequest(originalRequest); retryRequest.onRetry(); @@ -214,7 +214,7 @@ public IndexResult index(Index op) throws IOException { }) { shards.startAll(); Thread thread = new Thread(() -> { - IndexRequest indexRequest = new IndexRequest(index.getName()).source("{}", XContentType.JSON); + IndexRequest indexRequest = new IndexRequest(index.getName()).source("{}", MediaTypeRegistry.JSON); try { shards.index(indexRequest); } catch (Exception e) { @@ -244,7 +244,7 @@ public void prepareForTranslogOperations(int totalTranslogOps, ActionListener replicas = shards.getReplicas(); IndexShard replica1 = replicas.get(0); - IndexRequest indexRequest = new IndexRequest(index.getName()).id("1").source("{ \"f\": \"1\"}", XContentType.JSON); + IndexRequest indexRequest = new IndexRequest(index.getName()).id("1").source("{ \"f\": \"1\"}", MediaTypeRegistry.JSON); logger.info("--> isolated replica " + replica1.routingEntry()); BulkShardRequest replicationRequest = indexOnPrimary(indexRequest, shards.getPrimary()); for (int i = 1; i < replicas.size(); i++) { @@ -329,7 +329,7 @@ public void testConflictingOpsOnReplica() throws Exception { logger.info("--> promoting replica to primary " + replica1.routingEntry()); shards.promoteReplicaToPrimary(replica1).get(); - indexRequest = new IndexRequest(index.getName()).id("1").source("{ \"f\": \"2\"}", XContentType.JSON); + indexRequest = new IndexRequest(index.getName()).id("1").source("{ \"f\": \"2\"}", MediaTypeRegistry.JSON); shards.index(indexRequest); shards.refresh("test"); for (IndexShard shard : shards) { @@ -356,7 +356,7 @@ public void testReplicaTermIncrementWithConcurrentPrimaryPromotion() throws Exce assertEquals(primaryPrimaryTerm, replica2.getPendingPrimaryTerm()); - IndexRequest indexRequest = new IndexRequest(index.getName()).id("1").source("{ \"f\": \"1\"}", XContentType.JSON); + IndexRequest indexRequest = new IndexRequest(index.getName()).id("1").source("{ \"f\": \"1\"}", MediaTypeRegistry.JSON); BulkShardRequest replicationRequest = indexOnPrimary(indexRequest, replica1); CyclicBarrier barrier = new CyclicBarrier(2); @@ -396,7 +396,7 @@ public void testReplicaOperationWithConcurrentPrimaryPromotion() throws Exceptio try (ReplicationGroup shards = new ReplicationGroup(buildIndexMetadata(1, mappings))) { shards.startAll(); long primaryPrimaryTerm = shards.getPrimary().getPendingPrimaryTerm(); - IndexRequest indexRequest = new IndexRequest(index.getName()).id("1").source("{ \"f\": \"1\"}", XContentType.JSON); + IndexRequest indexRequest = new IndexRequest(index.getName()).id("1").source("{ \"f\": \"1\"}", MediaTypeRegistry.JSON); BulkShardRequest replicationRequest = indexOnPrimary(indexRequest, shards.getPrimary()); List replicas = shards.getReplicas(); @@ -476,7 +476,7 @@ protected EngineFactory getEngineFactory(ShardRouting routing) { shards.startPrimary(); long primaryTerm = shards.getPrimary().getPendingPrimaryTerm(); List expectedTranslogOps = new ArrayList<>(); - BulkItemResponse indexResp = shards.index(new IndexRequest(index.getName()).id("1").source("{}", XContentType.JSON)); + BulkItemResponse indexResp = shards.index(new IndexRequest(index.getName()).id("1").source("{}", MediaTypeRegistry.JSON)); assertThat(indexResp.isFailed(), equalTo(true)); assertThat(indexResp.getFailure().getCause(), equalTo(indexException)); expectedTranslogOps.add(new Translog.NoOp(0, primaryTerm, indexException.toString())); @@ -504,7 +504,7 @@ protected EngineFactory getEngineFactory(ShardRouting routing) { } } // the failure replicated directly from the replication channel. - indexResp = shards.index(new IndexRequest(index.getName()).id("any").source("{}", XContentType.JSON)); + indexResp = shards.index(new IndexRequest(index.getName()).id("any").source("{}", MediaTypeRegistry.JSON)); assertThat(indexResp.getFailure().getCause(), equalTo(indexException)); Translog.NoOp noop2 = new Translog.NoOp(1, primaryTerm, indexException.toString()); expectedTranslogOps.add(noop2); @@ -531,7 +531,9 @@ protected EngineFactory getEngineFactory(ShardRouting routing) { public void testRequestFailureReplication() throws Exception { try (ReplicationGroup shards = createGroup(0)) { shards.startAll(); - BulkItemResponse response = shards.index(new IndexRequest(index.getName()).id("1").source("{}", XContentType.JSON).version(2)); + BulkItemResponse response = shards.index( + new IndexRequest(index.getName()).id("1").source("{}", MediaTypeRegistry.JSON).version(2) + ); assertTrue(response.isFailed()); assertThat(response.getFailure().getCause(), instanceOf(VersionConflictEngineException.class)); shards.assertAllEqual(0); @@ -549,7 +551,7 @@ public void testRequestFailureReplication() throws Exception { shards.addReplica(); } shards.startReplicas(nReplica); - response = shards.index(new IndexRequest(index.getName()).id("1").source("{}", XContentType.JSON).version(2)); + response = shards.index(new IndexRequest(index.getName()).id("1").source("{}", MediaTypeRegistry.JSON).version(2)); assertTrue(response.isFailed()); assertThat(response.getFailure().getCause(), instanceOf(VersionConflictEngineException.class)); shards.assertAllEqual(0); @@ -582,7 +584,7 @@ public void testSeqNoCollision() throws Exception { shards.syncGlobalCheckpoint(); logger.info("--> Isolate replica1"); - IndexRequest indexDoc1 = new IndexRequest(index.getName()).id("d1").source("{}", XContentType.JSON); + IndexRequest indexDoc1 = new IndexRequest(index.getName()).id("d1").source("{}", MediaTypeRegistry.JSON); BulkShardRequest replicationRequest = indexOnPrimary(indexDoc1, shards.getPrimary()); indexOnReplica(replicationRequest, shards, replica2); @@ -602,7 +604,7 @@ public void testSeqNoCollision() throws Exception { } logger.info("--> Promote replica1 as the primary"); shards.promoteReplicaToPrimary(replica1).get(); // wait until resync completed. - shards.index(new IndexRequest(index.getName()).id("d2").source("{}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id("d2").source("{}", MediaTypeRegistry.JSON)); final Translog.Operation op2; try (Translog.Snapshot snapshot = getTranslog(replica2).newSnapshot()) { assertThat(snapshot.totalOperations(), equalTo(1)); @@ -652,7 +654,7 @@ public void testLateDeliveryAfterGCTriggeredOnReplica() throws Exception { updateGCDeleteCycle(replica, gcInterval); final BulkShardRequest indexRequest = indexOnPrimary( - new IndexRequest(index.getName()).id("d1").source("{}", XContentType.JSON), + new IndexRequest(index.getName()).id("d1").source("{}", MediaTypeRegistry.JSON), primary ); final BulkShardRequest deleteRequest = deleteOnPrimary(new DeleteRequest(index.getName()).id("d1"), primary); @@ -689,7 +691,7 @@ public void testOutOfOrderDeliveryForAppendOnlyOperations() throws Exception { final IndexShard replica = shards.getReplicas().get(0); // Append-only request - without id final BulkShardRequest indexRequest = indexOnPrimary( - new IndexRequest(index.getName()).id(null).source("{}", XContentType.JSON), + new IndexRequest(index.getName()).id(null).source("{}", MediaTypeRegistry.JSON), primary ); final String docId = Iterables.get(getShardDocUIDs(primary), 0); @@ -709,7 +711,7 @@ public void testIndexingOptimizationUsingSequenceNumbers() throws Exception { for (int i = 0; i < numDocs; i++) { String id = Integer.toString(randomIntBetween(1, 100)); if (randomBoolean()) { - group.index(new IndexRequest(index.getName()).id(id).source("{}", XContentType.JSON)); + group.index(new IndexRequest(index.getName()).id(id).source("{}", MediaTypeRegistry.JSON)); if (liveDocs.add(id) == false) { versionLookups++; } diff --git a/server/src/test/java/org/opensearch/index/replication/RecoveryDuringReplicationTests.java b/server/src/test/java/org/opensearch/index/replication/RecoveryDuringReplicationTests.java index b61150a9a81e2..13566a66034bd 100644 --- a/server/src/test/java/org/opensearch/index/replication/RecoveryDuringReplicationTests.java +++ b/server/src/test/java/org/opensearch/index/replication/RecoveryDuringReplicationTests.java @@ -49,8 +49,8 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.lucene.uid.Versions; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.lease.Releasable; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.VersionType; import org.opensearch.index.engine.DocIdSeqNoAndSource; @@ -141,7 +141,7 @@ public void testRecoveryToReplicaThatReceivedExtraDocument() throws Exception { shards.startAll(); final int docs = randomIntBetween(0, 16); for (int i = 0; i < docs; i++) { - shards.index(new IndexRequest("index").id(Integer.toString(i)).source("{}", XContentType.JSON)); + shards.index(new IndexRequest("index").id(Integer.toString(i)).source("{}", MediaTypeRegistry.JSON)); } shards.flush(); @@ -158,7 +158,7 @@ public void testRecoveryToReplicaThatReceivedExtraDocument() throws Exception { 1, randomNonNegativeLong(), false, - new SourceToParse("index", "replica", new BytesArray("{}"), XContentType.JSON) + new SourceToParse("index", "replica", new BytesArray("{}"), MediaTypeRegistry.JSON) ); shards.promoteReplicaToPrimary(promotedReplica).get(); oldPrimary.close("demoted", randomBoolean(), false); @@ -172,7 +172,7 @@ public void testRecoveryToReplicaThatReceivedExtraDocument() throws Exception { promotedReplica.applyIndexOperationOnPrimary( Versions.MATCH_ANY, VersionType.INTERNAL, - new SourceToParse("index", "primary", new BytesArray("{}"), XContentType.JSON), + new SourceToParse("index", "primary", new BytesArray("{}"), MediaTypeRegistry.JSON), SequenceNumbers.UNASSIGNED_SEQ_NO, 0, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, @@ -209,7 +209,8 @@ public void testRecoveryAfterPrimaryPromotion() throws Exception { final int rollbackDocs = randomIntBetween(1, 5); logger.info("--> indexing {} rollback docs", rollbackDocs); for (int i = 0; i < rollbackDocs; i++) { - final IndexRequest indexRequest = new IndexRequest(index.getName()).id("rollback_" + i).source("{}", XContentType.JSON); + final IndexRequest indexRequest = new IndexRequest(index.getName()).id("rollback_" + i) + .source("{}", MediaTypeRegistry.JSON); final BulkShardRequest bulkShardRequest = indexOnPrimary(indexRequest, oldPrimary); indexOnReplica(bulkShardRequest, shards, replica); } @@ -327,7 +328,7 @@ public void testReplicaRollbackStaleDocumentsInPeerRecovery() throws Exception { int staleDocs = scaledRandomIntBetween(1, 10); logger.info("--> indexing {} stale docs", staleDocs); for (int i = 0; i < staleDocs; i++) { - final IndexRequest indexRequest = new IndexRequest(index.getName()).id("stale_" + i).source("{}", XContentType.JSON); + final IndexRequest indexRequest = new IndexRequest(index.getName()).id("stale_" + i).source("{}", MediaTypeRegistry.JSON); final BulkShardRequest bulkShardRequest = indexOnPrimary(indexRequest, oldPrimary); indexOnReplica(bulkShardRequest, shards, replica); } @@ -364,7 +365,7 @@ public void testResyncAfterPrimaryPromotion() throws Exception { for (int i = 0; i < initialDocs; i++) { final IndexRequest indexRequest = new IndexRequest(index.getName()).id("initial_doc_" + i) - .source("{ \"f\": \"normal\"}", XContentType.JSON); + .source("{ \"f\": \"normal\"}", MediaTypeRegistry.JSON); shards.index(indexRequest); } @@ -382,7 +383,7 @@ public void testResyncAfterPrimaryPromotion() throws Exception { logger.info("--> indexing {} extra docs", extraDocs); for (int i = 0; i < extraDocs; i++) { final IndexRequest indexRequest = new IndexRequest(index.getName()).id("extra_doc_" + i) - .source("{ \"f\": \"normal\"}", XContentType.JSON); + .source("{ \"f\": \"normal\"}", MediaTypeRegistry.JSON); final BulkShardRequest bulkShardRequest = indexOnPrimary(indexRequest, oldPrimary); indexOnReplica(bulkShardRequest, shards, newPrimary); } @@ -391,7 +392,7 @@ public void testResyncAfterPrimaryPromotion() throws Exception { logger.info("--> indexing {} extra docs to be trimmed", extraDocsToBeTrimmed); for (int i = 0; i < extraDocsToBeTrimmed; i++) { final IndexRequest indexRequest = new IndexRequest(index.getName()).id("extra_trimmed_" + i) - .source("{ \"f\": \"trimmed\"}", XContentType.JSON); + .source("{ \"f\": \"trimmed\"}", MediaTypeRegistry.JSON); final BulkShardRequest bulkShardRequest = indexOnPrimary(indexRequest, oldPrimary); // have to replicate to another replica != newPrimary one - the subject to trim indexOnReplica(bulkShardRequest, shards, justReplica); @@ -459,7 +460,7 @@ protected EngineFactory getEngineFactory(ShardRouting routing) { final String id = "pending_" + i; threadPool.generic().submit(() -> { try { - shards.index(new IndexRequest(index.getName()).id(id).source("{}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(id).source("{}", MediaTypeRegistry.JSON)); } catch (Exception e) { throw new AssertionError(e); } finally { @@ -550,7 +551,7 @@ public void indexTranslogOperations( replicaEngineFactory.latchIndexers(1); threadPool.generic().submit(() -> { try { - shards.index(new IndexRequest(index.getName()).id("pending").source("{}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id("pending").source("{}", MediaTypeRegistry.JSON)); } catch (final Exception e) { throw new RuntimeException(e); } finally { @@ -562,7 +563,7 @@ public void indexTranslogOperations( replicaEngineFactory.awaitIndexersLatch(); // unblock indexing for the next doc replicaEngineFactory.allowIndexing(); - shards.index(new IndexRequest(index.getName()).id("completed").source("{}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id("completed").source("{}", MediaTypeRegistry.JSON)); pendingDocActiveWithExtraDocIndexed.countDown(); } catch (final Exception e) { throw new AssertionError(e); @@ -602,7 +603,7 @@ public void indexTranslogOperations( // wait for the translog phase to complete and the recovery to block global checkpoint advancement assertBusy(() -> assertTrue(shards.getPrimary().pendingInSync())); { - shards.index(new IndexRequest(index.getName()).id("last").source("{}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id("last").source("{}", MediaTypeRegistry.JSON)); final long expectedDocs = docs + 3L; assertThat(shards.getPrimary().getLocalCheckpoint(), equalTo(expectedDocs - 1)); // recovery is now in the process of being completed, therefore the global checkpoint can not have advanced on the primary @@ -637,7 +638,7 @@ public void testTransferMaxSeenAutoIdTimestampOnResync() throws Exception { long maxTimestampOnReplica2 = -1; List replicationRequests = new ArrayList<>(); for (int numDocs = between(1, 10), i = 0; i < numDocs; i++) { - final IndexRequest indexRequest = new IndexRequest(index.getName()).source("{}", XContentType.JSON); + final IndexRequest indexRequest = new IndexRequest(index.getName()).source("{}", MediaTypeRegistry.JSON); indexRequest.process(Version.CURRENT, null, index.getName()); final IndexRequest copyRequest; if (randomBoolean()) { @@ -695,10 +696,10 @@ public void testAddNewReplicas() throws Exception { int nextId = docId.incrementAndGet(); if (appendOnly) { String id = randomBoolean() ? Integer.toString(nextId) : null; - shards.index(new IndexRequest(index.getName()).id(id).source("{}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(id).source("{}", MediaTypeRegistry.JSON)); } else if (frequently()) { String id = Integer.toString(frequently() ? nextId : between(0, nextId)); - shards.index(new IndexRequest(index.getName()).id(id).source("{}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(id).source("{}", MediaTypeRegistry.JSON)); } else { String id = Integer.toString(between(0, nextId)); shards.delete(new DeleteRequest(index.getName()).id(id)); @@ -736,7 +737,7 @@ public void testRollbackOnPromotion() throws Exception { int inFlightOps = scaledRandomIntBetween(10, 200); for (int i = 0; i < inFlightOps; i++) { String id = "extra-" + i; - IndexRequest primaryRequest = new IndexRequest(index.getName()).id(id).source("{}", XContentType.JSON); + IndexRequest primaryRequest = new IndexRequest(index.getName()).id(id).source("{}", MediaTypeRegistry.JSON); BulkShardRequest replicationRequest = indexOnPrimary(primaryRequest, shards.getPrimary()); for (IndexShard replica : shards.getReplicas()) { if (randomBoolean()) { diff --git a/server/src/test/java/org/opensearch/index/shard/IndexShardTests.java b/server/src/test/java/org/opensearch/index/shard/IndexShardTests.java index 061e5431f66c4..a42d5ddf5d610 100644 --- a/server/src/test/java/org/opensearch/index/shard/IndexShardTests.java +++ b/server/src/test/java/org/opensearch/index/shard/IndexShardTests.java @@ -87,11 +87,11 @@ import org.opensearch.common.util.concurrent.AtomicArray; import org.opensearch.common.util.concurrent.ConcurrentCollections; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.Assertions; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.index.shard.ShardId; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.env.NodeEnvironment; @@ -2309,7 +2309,7 @@ public void testRecoverFromStoreWithOutOfOrderDelete() throws IOException { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(shard.shardId().getIndexName(), "id", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(shard.shardId().getIndexName(), "id", new BytesArray("{}"), MediaTypeRegistry.JSON) ); shard.applyIndexOperationOnReplica( UUID.randomUUID().toString(), @@ -2318,7 +2318,7 @@ public void testRecoverFromStoreWithOutOfOrderDelete() throws IOException { 3, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(shard.shardId().getIndexName(), "id-3", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(shard.shardId().getIndexName(), "id-3", new BytesArray("{}"), MediaTypeRegistry.JSON) ); // Flushing a new commit with local checkpoint=1 allows to skip the translog gen #1 in recovery. shard.flush(new FlushRequest().force(true).waitIfOngoing(true)); @@ -2329,7 +2329,7 @@ public void testRecoverFromStoreWithOutOfOrderDelete() throws IOException { 3, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(shard.shardId().getIndexName(), "id-2", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(shard.shardId().getIndexName(), "id-2", new BytesArray("{}"), MediaTypeRegistry.JSON) ); shard.applyIndexOperationOnReplica( UUID.randomUUID().toString(), @@ -2338,7 +2338,7 @@ public void testRecoverFromStoreWithOutOfOrderDelete() throws IOException { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(shard.shardId().getIndexName(), "id-5", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(shard.shardId().getIndexName(), "id-5", new BytesArray("{}"), MediaTypeRegistry.JSON) ); shard.sync(); // advance local checkpoint @@ -2478,7 +2478,7 @@ public void testRecoverFromStoreWithNoOps() throws IOException { // start a replica shard and index the second doc final IndexShard otherShard = newStartedShard(false); updateMappings(otherShard, shard.indexSettings().getIndexMetadata()); - SourceToParse sourceToParse = new SourceToParse(shard.shardId().getIndexName(), "1", new BytesArray("{}"), XContentType.JSON); + SourceToParse sourceToParse = new SourceToParse(shard.shardId().getIndexName(), "1", new BytesArray("{}"), MediaTypeRegistry.JSON); otherShard.applyIndexOperationOnReplica( UUID.randomUUID().toString(), 1, @@ -2614,7 +2614,7 @@ public void testRecoverFromStoreRemoveStaleOperations() throws Exception { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(indexName, "doc-0", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(indexName, "doc-0", new BytesArray("{}"), MediaTypeRegistry.JSON) ); flushShard(shard); shard.updateGlobalCheckpointOnReplica(0, "test"); // stick the global checkpoint here. @@ -2625,7 +2625,7 @@ public void testRecoverFromStoreRemoveStaleOperations() throws Exception { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(indexName, "doc-1", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(indexName, "doc-1", new BytesArray("{}"), MediaTypeRegistry.JSON) ); flushShard(shard); assertThat(getShardDocUIDs(shard), containsInAnyOrder("doc-0", "doc-1")); @@ -2638,7 +2638,7 @@ public void testRecoverFromStoreRemoveStaleOperations() throws Exception { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(indexName, "doc-2", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(indexName, "doc-2", new BytesArray("{}"), MediaTypeRegistry.JSON) ); flushShard(shard); assertThat(getShardDocUIDs(shard), containsInAnyOrder("doc-0", "doc-1", "doc-2")); @@ -4051,7 +4051,7 @@ private Result indexOnReplicaWithGaps(final IndexShard indexShard, final int ope indexShard.shardId().getIndexName(), id, new BytesArray("{}"), - XContentType.JSON + MediaTypeRegistry.JSON ); indexShard.applyIndexOperationOnReplica( UUID.randomUUID().toString(), @@ -4685,7 +4685,7 @@ public void testDoNotTrimCommitsWhenOpenReadOnlyEngine() throws Exception { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(shard.shardId.getIndexName(), Long.toString(i), new BytesArray("{}"), XContentType.JSON) + new SourceToParse(shard.shardId.getIndexName(), Long.toString(i), new BytesArray("{}"), MediaTypeRegistry.JSON) ); shard.updateGlobalCheckpointOnReplica(shard.getLocalCheckpoint(), "test"); if (randomInt(100) < 10) { diff --git a/server/src/test/java/org/opensearch/index/shard/PrimaryReplicaSyncerTests.java b/server/src/test/java/org/opensearch/index/shard/PrimaryReplicaSyncerTests.java index f7991a3c42db8..65b823c643f8f 100644 --- a/server/src/test/java/org/opensearch/index/shard/PrimaryReplicaSyncerTests.java +++ b/server/src/test/java/org/opensearch/index/shard/PrimaryReplicaSyncerTests.java @@ -47,10 +47,10 @@ import org.opensearch.common.network.NetworkModule; import org.opensearch.common.settings.Settings; import org.opensearch.core.common.unit.ByteSizeValue; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.VersionType; import org.opensearch.index.mapper.SourceToParse; import org.opensearch.index.seqno.SequenceNumbers; @@ -93,7 +93,7 @@ public void testSyncerSendsOffCorrectDocuments() throws Exception { shard.applyIndexOperationOnPrimary( Versions.MATCH_ANY, VersionType.INTERNAL, - new SourceToParse(shard.shardId().getIndexName(), Integer.toString(i), new BytesArray("{}"), XContentType.JSON), + new SourceToParse(shard.shardId().getIndexName(), Integer.toString(i), new BytesArray("{}"), MediaTypeRegistry.JSON), SequenceNumbers.UNASSIGNED_SEQ_NO, 0, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, @@ -175,7 +175,7 @@ public void testSyncerOnClosingShard() throws Exception { shard.applyIndexOperationOnPrimary( Versions.MATCH_ANY, VersionType.INTERNAL, - new SourceToParse(shard.shardId().getIndexName(), Integer.toString(i), new BytesArray("{}"), XContentType.JSON), + new SourceToParse(shard.shardId().getIndexName(), Integer.toString(i), new BytesArray("{}"), MediaTypeRegistry.JSON), SequenceNumbers.UNASSIGNED_SEQ_NO, 0, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, diff --git a/server/src/test/java/org/opensearch/index/shard/RefreshListenersTests.java b/server/src/test/java/org/opensearch/index/shard/RefreshListenersTests.java index f3cffa4721ee5..c649ca13e3f5f 100644 --- a/server/src/test/java/org/opensearch/index/shard/RefreshListenersTests.java +++ b/server/src/test/java/org/opensearch/index/shard/RefreshListenersTests.java @@ -51,11 +51,11 @@ import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.BigArrays; import org.opensearch.common.util.concurrent.ThreadContext; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.common.lease.Releasable; import org.opensearch.core.index.shard.ShardId; import org.opensearch.core.index.Index; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.codec.CodecService; import org.opensearch.index.engine.Engine; @@ -438,7 +438,16 @@ private Engine.IndexResult index(String id, String testFieldValue) throws IOExce document.add(seqID.seqNoDocValue); document.add(seqID.primaryTerm); BytesReference source = new BytesArray(new byte[] { 1 }); - ParsedDocument doc = new ParsedDocument(versionField, seqID, id, null, Arrays.asList(document), source, XContentType.JSON, null); + ParsedDocument doc = new ParsedDocument( + versionField, + seqID, + id, + null, + Arrays.asList(document), + source, + MediaTypeRegistry.JSON, + null + ); Engine.Index index = new Engine.Index(new Term("_id", doc.id()), engine.config().getPrimaryTermSupplier().getAsLong(), doc); return engine.index(index); } diff --git a/server/src/test/java/org/opensearch/index/shard/SegmentReplicationIndexShardTests.java b/server/src/test/java/org/opensearch/index/shard/SegmentReplicationIndexShardTests.java index 58ae4b404e69c..549909dfc55e6 100644 --- a/server/src/test/java/org/opensearch/index/shard/SegmentReplicationIndexShardTests.java +++ b/server/src/test/java/org/opensearch/index/shard/SegmentReplicationIndexShardTests.java @@ -29,7 +29,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.CancellableThreads; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.engine.Engine; import org.opensearch.index.engine.InternalEngineFactory; @@ -274,7 +274,7 @@ public void testSegmentReplication_With_ReaderClosedConcurrently() throws Except final int numDocs = randomIntBetween(10, 20); logger.info("--> Inserting documents {}", numDocs); for (int i = 0; i < numDocs; i++) { - shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON)); } assertEqualTranslogOperations(shards, primaryShard); primaryShard.refresh("Test"); @@ -288,7 +288,7 @@ public void testSegmentReplication_With_ReaderClosedConcurrently() throws Except // Step 2. Ingest numDocs documents again & replicate to replica shard logger.info("--> Ingest {} docs again", numDocs); for (int i = 0; i < numDocs; i++) { - shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON)); } assertEqualTranslogOperations(shards, primaryShard); primaryShard.flush(new FlushRequest().waitIfOngoing(true).force(true)); @@ -323,7 +323,7 @@ public void testSegmentReplication_With_EngineClosedConcurrently() throws Except final int numDocs = randomIntBetween(10, 20); logger.info("--> Inserting documents {}", numDocs); for (int i = 0; i < numDocs; i++) { - shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON)); } assertEqualTranslogOperations(shards, primaryShard); primaryShard.refresh("Test"); @@ -334,7 +334,7 @@ public void testSegmentReplication_With_EngineClosedConcurrently() throws Except // Step 2. Ingest numDocs documents again to create a new commit logger.info("--> Ingest {} docs again", numDocs); for (int i = 0; i < numDocs; i++) { - shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON)); } assertEqualTranslogOperations(shards, primaryShard); primaryShard.flush(new FlushRequest().waitIfOngoing(true).force(true)); diff --git a/server/src/test/java/org/opensearch/index/shard/SegmentReplicationWithNodeToNodeIndexShardTests.java b/server/src/test/java/org/opensearch/index/shard/SegmentReplicationWithNodeToNodeIndexShardTests.java index a6634c0741cd4..b7b9d15457755 100644 --- a/server/src/test/java/org/opensearch/index/shard/SegmentReplicationWithNodeToNodeIndexShardTests.java +++ b/server/src/test/java/org/opensearch/index/shard/SegmentReplicationWithNodeToNodeIndexShardTests.java @@ -20,7 +20,7 @@ import org.opensearch.common.settings.ClusterSettings; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.CancellableThreads; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.engine.DocIdSeqNoAndSource; import org.opensearch.index.engine.InternalEngine; import org.opensearch.index.engine.NRTReplicationEngine; @@ -366,7 +366,7 @@ public void testTemporaryFilesNotCleanup() throws Exception { final int numDocs = randomIntBetween(100, 200); logger.info("--> Inserting documents {}", numDocs); for (int i = 0; i < numDocs; i++) { - shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON)); } assertEqualTranslogOperations(shards, primaryShard); primaryShard.flush(new FlushRequest().waitIfOngoing(true).force(true)); @@ -376,7 +376,7 @@ public void testTemporaryFilesNotCleanup() throws Exception { // Step 2. Ingest numDocs documents again to create a new commit on primary logger.info("--> Ingest {} docs again", numDocs); for (int i = 0; i < numDocs; i++) { - shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON)); } assertEqualTranslogOperations(shards, primaryShard); primaryShard.flush(new FlushRequest().waitIfOngoing(true).force(true)); @@ -656,7 +656,7 @@ public void testSegmentReplication_Index_Update_Delete() throws Exception { final int numDocs = randomIntBetween(100, 200); for (int i = 0; i < numDocs; i++) { - shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", XContentType.JSON)); + shards.index(new IndexRequest(index.getName()).id(String.valueOf(i)).source("{\"foo\": \"bar\"}", MediaTypeRegistry.JSON)); } assertEqualTranslogOperations(shards, primaryShard); @@ -669,7 +669,7 @@ public void testSegmentReplication_Index_Update_Delete() throws Exception { // randomly update docs. if (randomBoolean()) { shards.index( - new IndexRequest(index.getName()).id(String.valueOf(i)).source("{ \"foo\" : \"baz\" }", XContentType.JSON) + new IndexRequest(index.getName()).id(String.valueOf(i)).source("{ \"foo\" : \"baz\" }", MediaTypeRegistry.JSON) ); } } diff --git a/server/src/test/java/org/opensearch/index/shard/ShardGetServiceTests.java b/server/src/test/java/org/opensearch/index/shard/ShardGetServiceTests.java index 34d6233c8202f..0f27bc2bd126b 100644 --- a/server/src/test/java/org/opensearch/index/shard/ShardGetServiceTests.java +++ b/server/src/test/java/org/opensearch/index/shard/ShardGetServiceTests.java @@ -34,8 +34,8 @@ import org.opensearch.Version; import org.opensearch.cluster.metadata.IndexMetadata; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.index.shard.ShardId; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.VersionType; import org.opensearch.index.engine.Engine; import org.opensearch.index.engine.VersionConflictEngineException; @@ -74,7 +74,7 @@ public void testGetForUpdate() throws IOException { assertEquals(searcher.getIndexReader().maxDoc(), 1); // we refreshed } - Engine.IndexResult test1 = indexDoc(primary, "1", "{\"foo\" : \"baz\"}", XContentType.JSON, "foobar"); + Engine.IndexResult test1 = indexDoc(primary, "1", "{\"foo\" : \"baz\"}", MediaTypeRegistry.JSON, "foobar"); assertTrue(primary.getEngine().refreshNeeded()); GetResult testGet1 = primary.getService().getForUpdate("1", UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM); assertEquals(new String(testGet1.source(), StandardCharsets.UTF_8), "{\"foo\" : \"baz\"}"); @@ -89,7 +89,7 @@ public void testGetForUpdate() throws IOException { } // now again from the reader - Engine.IndexResult test2 = indexDoc(primary, "1", "{\"foo\" : \"baz\"}", XContentType.JSON, "foobar"); + Engine.IndexResult test2 = indexDoc(primary, "1", "{\"foo\" : \"baz\"}", MediaTypeRegistry.JSON, "foobar"); assertTrue(primary.getEngine().refreshNeeded()); testGet1 = primary.getService().getForUpdate("1", UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM); assertEquals(new String(testGet1.source(), StandardCharsets.UTF_8), "{\"foo\" : \"baz\"}"); @@ -157,7 +157,7 @@ private void runGetFromTranslogWithOptions( assertEquals(searcher.getIndexReader().maxDoc(), 1); // we refreshed } - Engine.IndexResult test1 = indexDoc(primary, "1", docToIndex, XContentType.JSON, "foobar"); + Engine.IndexResult test1 = indexDoc(primary, "1", docToIndex, MediaTypeRegistry.JSON, "foobar"); assertTrue(primary.getEngine().refreshNeeded()); GetResult testGet1 = primary.getService().getForUpdate("1", UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM); assertEquals(new String(testGet1.source() == null ? new byte[0] : testGet1.source(), StandardCharsets.UTF_8), expectedResult); @@ -171,7 +171,7 @@ private void runGetFromTranslogWithOptions( assertEquals(searcher.getIndexReader().maxDoc(), 2); } - Engine.IndexResult test2 = indexDoc(primary, "2", docToIndex, XContentType.JSON, "foobar"); + Engine.IndexResult test2 = indexDoc(primary, "2", docToIndex, MediaTypeRegistry.JSON, "foobar"); assertTrue(primary.getEngine().refreshNeeded()); GetResult testGet2 = primary.getService() .get("2", new String[] { "foo" }, true, 1, VersionType.INTERNAL, FetchSourceContext.FETCH_SOURCE); diff --git a/server/src/test/java/org/opensearch/index/snapshots/blobstore/FileInfoTests.java b/server/src/test/java/org/opensearch/index/snapshots/blobstore/FileInfoTests.java index 566a53c2508c8..057cffe94eace 100644 --- a/server/src/test/java/org/opensearch/index/snapshots/blobstore/FileInfoTests.java +++ b/server/src/test/java/org/opensearch/index/snapshots/blobstore/FileInfoTests.java @@ -40,7 +40,6 @@ import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.index.snapshots.blobstore.BlobStoreIndexShardSnapshot.FileInfo; import org.opensearch.index.store.StoreFileMetadata; @@ -73,7 +72,7 @@ public void testToFromXContent() throws IOException { ); ByteSizeValue size = new ByteSizeValue(Math.abs(randomLong())); BlobStoreIndexShardSnapshot.FileInfo info = new BlobStoreIndexShardSnapshot.FileInfo("_foobar", meta, size); - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON).prettyPrint(); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON).prettyPrint(); BlobStoreIndexShardSnapshot.FileInfo.toXContent(info, builder, ToXContent.EMPTY_PARAMS); byte[] xcontent = BytesReference.toBytes(BytesReference.bytes(shuffleXContent(builder))); @@ -126,7 +125,7 @@ public void testInvalidFieldsInFromXContent() throws IOException { fail("shouldn't be here"); } - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.startObject(); builder.field(FileInfo.NAME, name); builder.field(FileInfo.PHYSICAL_NAME, physicalName); diff --git a/server/src/test/java/org/opensearch/index/snapshots/blobstore/RemoteStoreShardShallowCopySnapshotTests.java b/server/src/test/java/org/opensearch/index/snapshots/blobstore/RemoteStoreShardShallowCopySnapshotTests.java index 6dc5cc23d2ff2..5dd4bf35cb422 100644 --- a/server/src/test/java/org/opensearch/index/snapshots/blobstore/RemoteStoreShardShallowCopySnapshotTests.java +++ b/server/src/test/java/org/opensearch/index/snapshots/blobstore/RemoteStoreShardShallowCopySnapshotTests.java @@ -9,7 +9,6 @@ package org.opensearch.index.snapshots.blobstore; import org.opensearch.core.common.bytes.BytesReference; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; @@ -56,7 +55,7 @@ public void testToXContent() throws IOException { fileNames ); String actual; - try (XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent())) { + try (XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder()) { builder.startObject(); shardShallowCopySnapshot.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); @@ -176,7 +175,7 @@ public void testFromXContentInvalid() throws IOException { fail("shouldn't be here"); } - XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); builder.startObject(); builder.field(RemoteStoreShardShallowCopySnapshot.VERSION, version); builder.field(RemoteStoreShardShallowCopySnapshot.NAME, snapshot); diff --git a/server/src/test/java/org/opensearch/index/translog/LocalTranslogTests.java b/server/src/test/java/org/opensearch/index/translog/LocalTranslogTests.java index 2433a33ebc7f2..7d681b3d57a4f 100644 --- a/server/src/test/java/org/opensearch/index/translog/LocalTranslogTests.java +++ b/server/src/test/java/org/opensearch/index/translog/LocalTranslogTests.java @@ -67,10 +67,10 @@ import org.opensearch.common.util.concurrent.AbstractRunnable; import org.opensearch.common.util.concurrent.ConcurrentCollections; import org.opensearch.common.util.concurrent.ReleasableLock; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.index.IndexSettings; import org.opensearch.index.VersionType; @@ -3505,7 +3505,7 @@ public void testTranslogOpSerialization() throws Exception { document.add(seqID.seqNo); document.add(seqID.seqNoDocValue); document.add(seqID.primaryTerm); - ParsedDocument doc = new ParsedDocument(versionField, seqID, "1", null, Arrays.asList(document), B_1, XContentType.JSON, null); + ParsedDocument doc = new ParsedDocument(versionField, seqID, "1", null, Arrays.asList(document), B_1, MediaTypeRegistry.JSON, null); Engine.Index eIndex = new Engine.Index( newUid(doc), diff --git a/server/src/test/java/org/opensearch/index/translog/TranslogManagerTestCase.java b/server/src/test/java/org/opensearch/index/translog/TranslogManagerTestCase.java index 91694060617ab..6975f101c72f7 100644 --- a/server/src/test/java/org/opensearch/index/translog/TranslogManagerTestCase.java +++ b/server/src/test/java/org/opensearch/index/translog/TranslogManagerTestCase.java @@ -23,9 +23,9 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.BigArrays; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.core.index.Index; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.engine.Engine; import org.opensearch.index.engine.EngineConfig; @@ -182,7 +182,7 @@ protected static ParsedDocument testParsedDocument( } else { document.add(new StoredField(SourceFieldMapper.NAME, ref.bytes, ref.offset, ref.length)); } - return new ParsedDocument(versionField, seqID, id, routing, List.of(document), source, XContentType.JSON, mappingUpdate); + return new ParsedDocument(versionField, seqID, id, routing, List.of(document), source, MediaTypeRegistry.JSON, mappingUpdate); } protected static ParseContext.Document testDocumentWithTextField() { diff --git a/server/src/test/java/org/opensearch/indices/IndexingMemoryControllerTests.java b/server/src/test/java/org/opensearch/indices/IndexingMemoryControllerTests.java index 19ed7122741aa..c91ed00547bff 100644 --- a/server/src/test/java/org/opensearch/indices/IndexingMemoryControllerTests.java +++ b/server/src/test/java/org/opensearch/indices/IndexingMemoryControllerTests.java @@ -38,7 +38,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.core.common.unit.ByteSizeUnit; import org.opensearch.core.common.unit.ByteSizeValue; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.codec.CodecService; import org.opensearch.index.engine.EngineConfig; import org.opensearch.index.engine.InternalEngine; @@ -367,7 +367,7 @@ public void testThrottling() throws Exception { public void testTranslogRecoveryWorksWithIMC() throws IOException { IndexShard shard = newStartedShard(true); for (int i = 0; i < 100; i++) { - indexDoc(shard, Integer.toString(i), "{\"foo\" : \"bar\"}", XContentType.JSON, null); + indexDoc(shard, Integer.toString(i), "{\"foo\" : \"bar\"}", MediaTypeRegistry.JSON, null); } shard.close("simon says", false, false); AtomicReference shardRef = new AtomicReference<>(); diff --git a/server/src/test/java/org/opensearch/indices/IndicesRequestCacheTests.java b/server/src/test/java/org/opensearch/indices/IndicesRequestCacheTests.java index 2a03ddc6f46e4..9ebab1a9022a7 100644 --- a/server/src/test/java/org/opensearch/indices/IndicesRequestCacheTests.java +++ b/server/src/test/java/org/opensearch/indices/IndicesRequestCacheTests.java @@ -52,9 +52,9 @@ import org.opensearch.common.lucene.index.OpenSearchDirectoryReader; import org.opensearch.common.settings.Settings; import org.opensearch.core.common.unit.ByteSizeValue; -import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.XContentHelper; import org.opensearch.common.util.io.IOUtils; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.cache.request.ShardRequestCache; import org.opensearch.index.query.TermQueryBuilder; import org.opensearch.core.index.shard.ShardId; @@ -75,7 +75,7 @@ public void testBasicOperationsCache() throws Exception { writer.addDocument(newDoc(0, "foo")); DirectoryReader reader = OpenSearchDirectoryReader.wrap(DirectoryReader.open(writer), new ShardId("foo", "bar", 1)); TermQueryBuilder termQuery = new TermQueryBuilder("id", "0"); - BytesReference termBytes = XContentHelper.toXContent(termQuery, XContentType.JSON, false); + BytesReference termBytes = XContentHelper.toXContent(termQuery, MediaTypeRegistry.JSON, false); AtomicBoolean indexShard = new AtomicBoolean(true); // initial cache @@ -131,7 +131,7 @@ public void testCacheDifferentReaders() throws Exception { writer.addDocument(newDoc(0, "foo")); DirectoryReader reader = OpenSearchDirectoryReader.wrap(DirectoryReader.open(writer), new ShardId("foo", "bar", 1)); TermQueryBuilder termQuery = new TermQueryBuilder("id", "0"); - BytesReference termBytes = XContentHelper.toXContent(termQuery, XContentType.JSON, false); + BytesReference termBytes = XContentHelper.toXContent(termQuery, MediaTypeRegistry.JSON, false); if (randomBoolean()) { writer.flush(); IOUtils.close(writer); @@ -227,7 +227,7 @@ public void testEviction() throws Exception { writer.addDocument(newDoc(0, "foo")); DirectoryReader reader = OpenSearchDirectoryReader.wrap(DirectoryReader.open(writer), new ShardId("foo", "bar", 1)); TermQueryBuilder termQuery = new TermQueryBuilder("id", "0"); - BytesReference termBytes = XContentHelper.toXContent(termQuery, XContentType.JSON, false); + BytesReference termBytes = XContentHelper.toXContent(termQuery, MediaTypeRegistry.JSON, false); TestEntity entity = new TestEntity(requestCacheStats, indexShard); Loader loader = new Loader(reader, 0); @@ -254,7 +254,7 @@ public void testEviction() throws Exception { writer.addDocument(newDoc(0, "foo")); DirectoryReader reader = OpenSearchDirectoryReader.wrap(DirectoryReader.open(writer), new ShardId("foo", "bar", 1)); TermQueryBuilder termQuery = new TermQueryBuilder("id", "0"); - BytesReference termBytes = XContentHelper.toXContent(termQuery, XContentType.JSON, false); + BytesReference termBytes = XContentHelper.toXContent(termQuery, MediaTypeRegistry.JSON, false); TestEntity entity = new TestEntity(requestCacheStats, indexShard); Loader loader = new Loader(reader, 0); @@ -291,7 +291,7 @@ public void testClearAllEntityIdentity() throws Exception { writer.addDocument(newDoc(0, "foo")); DirectoryReader reader = OpenSearchDirectoryReader.wrap(DirectoryReader.open(writer), new ShardId("foo", "bar", 1)); TermQueryBuilder termQuery = new TermQueryBuilder("id", "0"); - BytesReference termBytes = XContentHelper.toXContent(termQuery, XContentType.JSON, false); + BytesReference termBytes = XContentHelper.toXContent(termQuery, MediaTypeRegistry.JSON, false); TestEntity entity = new TestEntity(requestCacheStats, indexShard); Loader loader = new Loader(reader, 0); @@ -373,7 +373,7 @@ public void testInvalidate() throws Exception { writer.addDocument(newDoc(0, "foo")); DirectoryReader reader = OpenSearchDirectoryReader.wrap(DirectoryReader.open(writer), new ShardId("foo", "bar", 1)); TermQueryBuilder termQuery = new TermQueryBuilder("id", "0"); - BytesReference termBytes = XContentHelper.toXContent(termQuery, XContentType.JSON, false); + BytesReference termBytes = XContentHelper.toXContent(termQuery, MediaTypeRegistry.JSON, false); AtomicBoolean indexShard = new AtomicBoolean(true); // initial cache diff --git a/server/src/test/java/org/opensearch/indices/recovery/LocalStorePeerRecoverySourceHandlerTests.java b/server/src/test/java/org/opensearch/indices/recovery/LocalStorePeerRecoverySourceHandlerTests.java index 0b2de2acbb1d0..0eacb2c6c5b22 100644 --- a/server/src/test/java/org/opensearch/indices/recovery/LocalStorePeerRecoverySourceHandlerTests.java +++ b/server/src/test/java/org/opensearch/indices/recovery/LocalStorePeerRecoverySourceHandlerTests.java @@ -70,9 +70,9 @@ import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.CancellableThreads; import org.opensearch.common.util.concurrent.ConcurrentCollections; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.common.lease.Releasable; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.engine.Engine; import org.opensearch.index.engine.RecoveryEngineException; @@ -487,7 +487,7 @@ private Engine.Index getIndex(final String id) { null, Arrays.asList(document), source, - XContentType.JSON, + MediaTypeRegistry.JSON, null ); return new Engine.Index(new Term("_id", Uid.encodeId(doc.id())), randomNonNegativeLong(), doc); diff --git a/server/src/test/java/org/opensearch/indices/recovery/PeerRecoveryTargetServiceTests.java b/server/src/test/java/org/opensearch/indices/recovery/PeerRecoveryTargetServiceTests.java index 67811e24b03c4..cde2c4d5a677f 100644 --- a/server/src/test/java/org/opensearch/indices/recovery/PeerRecoveryTargetServiceTests.java +++ b/server/src/test/java/org/opensearch/indices/recovery/PeerRecoveryTargetServiceTests.java @@ -47,8 +47,8 @@ import org.opensearch.common.UUIDs; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.engine.EngineConfigFactory; import org.opensearch.index.engine.NoOpEngine; import org.opensearch.index.mapper.SourceToParse; @@ -189,7 +189,7 @@ private SeqNoStats populateRandomData(IndexShard shard) throws IOException { shard.getOperationPrimaryTerm(), IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(shard.shardId().getIndexName(), UUIDs.randomBase64UUID(), new BytesArray("{}"), XContentType.JSON) + new SourceToParse(shard.shardId().getIndexName(), UUIDs.randomBase64UUID(), new BytesArray("{}"), MediaTypeRegistry.JSON) ); if (randomInt(100) < 5) { shard.flush(new FlushRequest().waitIfOngoing(true)); diff --git a/server/src/test/java/org/opensearch/indices/recovery/RecoveryTests.java b/server/src/test/java/org/opensearch/indices/recovery/RecoveryTests.java index 2c45c9e177c52..de25d7cf527ee 100644 --- a/server/src/test/java/org/opensearch/indices/recovery/RecoveryTests.java +++ b/server/src/test/java/org/opensearch/indices/recovery/RecoveryTests.java @@ -51,7 +51,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.lucene.uid.Versions; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.MergePolicyConfig; import org.opensearch.index.VersionType; @@ -188,7 +188,7 @@ public void testRecoveryWithOutOfOrderDeleteWithSoftDeletes() throws Exception { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(indexName, "id", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(indexName, "id", new BytesArray("{}"), MediaTypeRegistry.JSON) ); // index #3 orgReplica.applyIndexOperationOnReplica( @@ -198,7 +198,7 @@ public void testRecoveryWithOutOfOrderDeleteWithSoftDeletes() throws Exception { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(indexName, "id-3", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(indexName, "id-3", new BytesArray("{}"), MediaTypeRegistry.JSON) ); // Flushing a new commit with local checkpoint=1 allows to delete the translog gen #1. orgReplica.flush(new FlushRequest().force(true).waitIfOngoing(true)); @@ -210,7 +210,7 @@ public void testRecoveryWithOutOfOrderDeleteWithSoftDeletes() throws Exception { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(indexName, "id-2", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(indexName, "id-2", new BytesArray("{}"), MediaTypeRegistry.JSON) ); orgReplica.sync(); // advance local checkpoint orgReplica.updateGlobalCheckpointOnReplica(3L, "test"); @@ -222,7 +222,7 @@ public void testRecoveryWithOutOfOrderDeleteWithSoftDeletes() throws Exception { 1, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, - new SourceToParse(indexName, "id-5", new BytesArray("{}"), XContentType.JSON) + new SourceToParse(indexName, "id-5", new BytesArray("{}"), MediaTypeRegistry.JSON) ); if (randomBoolean()) { @@ -331,7 +331,7 @@ public void testPeerRecoverySendSafeCommitInFileBased() throws Exception { Engine.IndexResult result = primaryShard.applyIndexOperationOnPrimary( Versions.MATCH_ANY, VersionType.INTERNAL, - new SourceToParse(primaryShard.shardId().getIndexName(), Integer.toString(i), new BytesArray("{}"), XContentType.JSON), + new SourceToParse(primaryShard.shardId().getIndexName(), Integer.toString(i), new BytesArray("{}"), MediaTypeRegistry.JSON), SequenceNumbers.UNASSIGNED_SEQ_NO, 0, IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, @@ -498,7 +498,7 @@ public void testRecoveryTrimsLocalTranslog() throws Exception { } int inflightDocs = scaledRandomIntBetween(1, 100); for (int i = 0; i < inflightDocs; i++) { - final IndexRequest indexRequest = new IndexRequest(index.getName()).id("extra_" + i).source("{}", XContentType.JSON); + final IndexRequest indexRequest = new IndexRequest(index.getName()).id("extra_" + i).source("{}", MediaTypeRegistry.JSON); final BulkShardRequest bulkShardRequest = indexOnPrimary(indexRequest, oldPrimary); for (IndexShard replica : randomSubsetOf(shards.getReplicas())) { indexOnReplica(bulkShardRequest, shards, replica); diff --git a/server/src/test/java/org/opensearch/indices/replication/OngoingSegmentReplicationsTests.java b/server/src/test/java/org/opensearch/indices/replication/OngoingSegmentReplicationsTests.java index 84a53ae22a6bc..84f781b08e5f3 100644 --- a/server/src/test/java/org/opensearch/indices/replication/OngoingSegmentReplicationsTests.java +++ b/server/src/test/java/org/opensearch/indices/replication/OngoingSegmentReplicationsTests.java @@ -15,7 +15,7 @@ import org.opensearch.common.settings.ClusterSettings; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.CancellableThreads; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexService; import org.opensearch.index.codec.CodecService; import org.opensearch.index.engine.NRTReplicationEngineFactory; @@ -94,7 +94,7 @@ public void tearDown() throws Exception { } public void testPrepareAndSendSegments() throws IOException { - indexDoc(primary, "1", "{\"foo\" : \"baz\"}", XContentType.JSON, "foobar"); + indexDoc(primary, "1", "{\"foo\" : \"baz\"}", MediaTypeRegistry.JSON, "foobar"); primary.refresh("Test"); OngoingSegmentReplications replications = spy(new OngoingSegmentReplications(mockIndicesService, recoverySettings)); final CheckpointInfoRequest request = new CheckpointInfoRequest( @@ -162,7 +162,7 @@ public void testCancelReplication_AfterSendFilesStarts() throws IOException, Int CountDownLatch latch = new CountDownLatch(1); OngoingSegmentReplications replications = new OngoingSegmentReplications(mockIndicesService, recoverySettings); // add a doc and refresh so primary has more than one segment. - indexDoc(primary, "1", "{\"foo\" : \"baz\"}", XContentType.JSON, "foobar"); + indexDoc(primary, "1", "{\"foo\" : \"baz\"}", MediaTypeRegistry.JSON, "foobar"); primary.refresh("Test"); final CheckpointInfoRequest request = new CheckpointInfoRequest( 1L, diff --git a/server/src/test/java/org/opensearch/indices/replication/SegmentReplicationSourceHandlerTests.java b/server/src/test/java/org/opensearch/indices/replication/SegmentReplicationSourceHandlerTests.java index b4e9166f377ec..ba993feb13362 100644 --- a/server/src/test/java/org/opensearch/indices/replication/SegmentReplicationSourceHandlerTests.java +++ b/server/src/test/java/org/opensearch/indices/replication/SegmentReplicationSourceHandlerTests.java @@ -19,7 +19,7 @@ import org.opensearch.cluster.node.DiscoveryNode; import org.opensearch.common.settings.Settings; import org.opensearch.common.util.CancellableThreads; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.engine.NRTReplicationEngineFactory; import org.opensearch.index.shard.IndexShard; import org.opensearch.index.shard.IndexShardTestCase; @@ -140,7 +140,7 @@ public void onFailure(Exception e) { public void testSendFileFails() throws IOException { // index some docs on the primary so a segment is created. - indexDoc(primary, "1", "{\"foo\" : \"baz\"}", XContentType.JSON, "foobar"); + indexDoc(primary, "1", "{\"foo\" : \"baz\"}", MediaTypeRegistry.JSON, "foobar"); primary.refresh("Test"); chunkWriter = (fileMetadata, position, content, lastChunk, totalTranslogOps, listener) -> listener.onFailure( new OpenSearchException("Test") diff --git a/server/src/test/java/org/opensearch/ingest/IngestMetadataTests.java b/server/src/test/java/org/opensearch/ingest/IngestMetadataTests.java index 82e6e1c9ff450..dff9aaef81b53 100644 --- a/server/src/test/java/org/opensearch/ingest/IngestMetadataTests.java +++ b/server/src/test/java/org/opensearch/ingest/IngestMetadataTests.java @@ -57,12 +57,12 @@ public void testFromXContent() throws IOException { PipelineConfiguration pipeline = new PipelineConfiguration( "1", new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); PipelineConfiguration pipeline2 = new PipelineConfiguration( "2", new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field1\", \"value\": \"_value1\"}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); Map map = new HashMap<>(); map.put(pipeline.getId(), pipeline); @@ -90,14 +90,14 @@ public void testDiff() throws Exception { BytesReference pipelineConfig = new BytesArray("{}"); Map pipelines = new HashMap<>(); - pipelines.put("1", new PipelineConfiguration("1", pipelineConfig, XContentType.JSON)); - pipelines.put("2", new PipelineConfiguration("2", pipelineConfig, XContentType.JSON)); + pipelines.put("1", new PipelineConfiguration("1", pipelineConfig, MediaTypeRegistry.JSON)); + pipelines.put("2", new PipelineConfiguration("2", pipelineConfig, MediaTypeRegistry.JSON)); IngestMetadata ingestMetadata1 = new IngestMetadata(pipelines); pipelines = new HashMap<>(); - pipelines.put("1", new PipelineConfiguration("1", pipelineConfig, XContentType.JSON)); - pipelines.put("3", new PipelineConfiguration("3", pipelineConfig, XContentType.JSON)); - pipelines.put("4", new PipelineConfiguration("4", pipelineConfig, XContentType.JSON)); + pipelines.put("1", new PipelineConfiguration("1", pipelineConfig, MediaTypeRegistry.JSON)); + pipelines.put("3", new PipelineConfiguration("3", pipelineConfig, MediaTypeRegistry.JSON)); + pipelines.put("4", new PipelineConfiguration("4", pipelineConfig, MediaTypeRegistry.JSON)); IngestMetadata ingestMetadata2 = new IngestMetadata(pipelines); IngestMetadata.IngestMetadataDiff diff = (IngestMetadata.IngestMetadataDiff) ingestMetadata2.diff(ingestMetadata1); @@ -110,13 +110,13 @@ public void testDiff() throws Exception { IngestMetadata endResult = (IngestMetadata) diff.apply(ingestMetadata2); assertThat(endResult, not(equalTo(ingestMetadata1))); assertThat(endResult.getPipelines().size(), equalTo(3)); - assertThat(endResult.getPipelines().get("1"), equalTo(new PipelineConfiguration("1", pipelineConfig, XContentType.JSON))); - assertThat(endResult.getPipelines().get("3"), equalTo(new PipelineConfiguration("3", pipelineConfig, XContentType.JSON))); - assertThat(endResult.getPipelines().get("4"), equalTo(new PipelineConfiguration("4", pipelineConfig, XContentType.JSON))); + assertThat(endResult.getPipelines().get("1"), equalTo(new PipelineConfiguration("1", pipelineConfig, MediaTypeRegistry.JSON))); + assertThat(endResult.getPipelines().get("3"), equalTo(new PipelineConfiguration("3", pipelineConfig, MediaTypeRegistry.JSON))); + assertThat(endResult.getPipelines().get("4"), equalTo(new PipelineConfiguration("4", pipelineConfig, MediaTypeRegistry.JSON))); pipelines = new HashMap<>(); - pipelines.put("1", new PipelineConfiguration("1", new BytesArray("{}"), XContentType.JSON)); - pipelines.put("2", new PipelineConfiguration("2", new BytesArray("{}"), XContentType.JSON)); + pipelines.put("1", new PipelineConfiguration("1", new BytesArray("{}"), MediaTypeRegistry.JSON)); + pipelines.put("2", new PipelineConfiguration("2", new BytesArray("{}"), MediaTypeRegistry.JSON)); IngestMetadata ingestMetadata3 = new IngestMetadata(pipelines); diff = (IngestMetadata.IngestMetadataDiff) ingestMetadata3.diff(ingestMetadata1); @@ -126,12 +126,12 @@ public void testDiff() throws Exception { endResult = (IngestMetadata) diff.apply(ingestMetadata3); assertThat(endResult, equalTo(ingestMetadata1)); assertThat(endResult.getPipelines().size(), equalTo(2)); - assertThat(endResult.getPipelines().get("1"), equalTo(new PipelineConfiguration("1", pipelineConfig, XContentType.JSON))); - assertThat(endResult.getPipelines().get("2"), equalTo(new PipelineConfiguration("2", pipelineConfig, XContentType.JSON))); + assertThat(endResult.getPipelines().get("1"), equalTo(new PipelineConfiguration("1", pipelineConfig, MediaTypeRegistry.JSON))); + assertThat(endResult.getPipelines().get("2"), equalTo(new PipelineConfiguration("2", pipelineConfig, MediaTypeRegistry.JSON))); pipelines = new HashMap<>(); - pipelines.put("1", new PipelineConfiguration("1", new BytesArray("{}"), XContentType.JSON)); - pipelines.put("2", new PipelineConfiguration("2", new BytesArray("{\"key\" : \"value\"}"), XContentType.JSON)); + pipelines.put("1", new PipelineConfiguration("1", new BytesArray("{}"), MediaTypeRegistry.JSON)); + pipelines.put("2", new PipelineConfiguration("2", new BytesArray("{\"key\" : \"value\"}"), MediaTypeRegistry.JSON)); IngestMetadata ingestMetadata4 = new IngestMetadata(pipelines); diff = (IngestMetadata.IngestMetadataDiff) ingestMetadata4.diff(ingestMetadata1); @@ -141,10 +141,10 @@ public void testDiff() throws Exception { endResult = (IngestMetadata) diff.apply(ingestMetadata4); assertThat(endResult, not(equalTo(ingestMetadata1))); assertThat(endResult.getPipelines().size(), equalTo(2)); - assertThat(endResult.getPipelines().get("1"), equalTo(new PipelineConfiguration("1", pipelineConfig, XContentType.JSON))); + assertThat(endResult.getPipelines().get("1"), equalTo(new PipelineConfiguration("1", pipelineConfig, MediaTypeRegistry.JSON))); assertThat( endResult.getPipelines().get("2"), - equalTo(new PipelineConfiguration("2", new BytesArray("{\"key\" : \"value\"}"), XContentType.JSON)) + equalTo(new PipelineConfiguration("2", new BytesArray("{\"key\" : \"value\"}"), MediaTypeRegistry.JSON)) ); } } diff --git a/server/src/test/java/org/opensearch/ingest/IngestServiceTests.java b/server/src/test/java/org/opensearch/ingest/IngestServiceTests.java index 7f5ec52c3620c..ddc27f15ff18b 100644 --- a/server/src/test/java/org/opensearch/ingest/IngestServiceTests.java +++ b/server/src/test/java/org/opensearch/ingest/IngestServiceTests.java @@ -61,6 +61,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.util.concurrent.OpenSearchExecutors; import org.opensearch.core.common.bytes.BytesArray; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.cbor.CborXContent; @@ -221,7 +222,7 @@ public void testUpdatePipelines() { PipelineConfiguration pipeline = new PipelineConfiguration( "_id", new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); IngestMetadata ingestMetadata = new IngestMetadata(Collections.singletonMap("_id", pipeline)); clusterState = ClusterState.builder(clusterState) @@ -239,7 +240,7 @@ public void testInnerUpdatePipelines() { IngestService ingestService = createWithProcessors(); assertThat(ingestService.pipelines().size(), is(0)); - PipelineConfiguration pipeline1 = new PipelineConfiguration("_id1", new BytesArray("{\"processors\": []}"), XContentType.JSON); + PipelineConfiguration pipeline1 = new PipelineConfiguration("_id1", new BytesArray("{\"processors\": []}"), MediaTypeRegistry.JSON); IngestMetadata ingestMetadata = new IngestMetadata(mapOf("_id1", pipeline1)); ingestService.innerUpdatePipelines(ingestMetadata); @@ -247,7 +248,7 @@ public void testInnerUpdatePipelines() { assertThat(ingestService.pipelines().get("_id1").pipeline.getId(), equalTo("_id1")); assertThat(ingestService.pipelines().get("_id1").pipeline.getProcessors().size(), equalTo(0)); - PipelineConfiguration pipeline2 = new PipelineConfiguration("_id2", new BytesArray("{\"processors\": []}"), XContentType.JSON); + PipelineConfiguration pipeline2 = new PipelineConfiguration("_id2", new BytesArray("{\"processors\": []}"), MediaTypeRegistry.JSON); ingestMetadata = new IngestMetadata(mapOf("_id1", pipeline1, "_id2", pipeline2)); ingestService.innerUpdatePipelines(ingestMetadata); @@ -257,7 +258,7 @@ public void testInnerUpdatePipelines() { assertThat(ingestService.pipelines().get("_id2").pipeline.getId(), equalTo("_id2")); assertThat(ingestService.pipelines().get("_id2").pipeline.getProcessors().size(), equalTo(0)); - PipelineConfiguration pipeline3 = new PipelineConfiguration("_id3", new BytesArray("{\"processors\": []}"), XContentType.JSON); + PipelineConfiguration pipeline3 = new PipelineConfiguration("_id3", new BytesArray("{\"processors\": []}"), MediaTypeRegistry.JSON); ingestMetadata = new IngestMetadata(mapOf("_id1", pipeline1, "_id2", pipeline2, "_id3", pipeline3)); ingestService.innerUpdatePipelines(ingestMetadata); @@ -281,7 +282,7 @@ public void testInnerUpdatePipelines() { pipeline3 = new PipelineConfiguration( "_id3", new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ingestMetadata = new IngestMetadata(mapOf("_id1", pipeline1, "_id3", pipeline3)); @@ -323,7 +324,7 @@ public void testDelete() { PipelineConfiguration config = new PipelineConfiguration( "_id", new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); IngestMetadata ingestMetadata = new IngestMetadata(Collections.singletonMap("_id", config)); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); @@ -355,7 +356,7 @@ public void testValidateNoIngestInfo() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); Exception e = expectThrows(IllegalStateException.class, () -> ingestService.validatePipeline(emptyMap(), putRequest)); assertEquals("Ingest info is empty", e.getMessage()); @@ -384,7 +385,7 @@ public void testGetProcessorsInPipeline() throws Exception { "{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\", \"tag\": \"tag1\"}}," + "{\"remove\" : {\"field\": \"_field\", \"tag\": \"tag2\"}}]}" ), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); @@ -450,7 +451,7 @@ public void testGetProcessorsInPipelineComplexConditional() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( id, new BytesArray("{\"processors\": [{\"complexSet\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); @@ -476,7 +477,7 @@ public void testCrud() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( id, new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); @@ -504,7 +505,7 @@ public void testPut() { ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // add a new pipeline: - PutPipelineRequest putRequest = new PutPipelineRequest(id, new BytesArray("{\"processors\": []}"), XContentType.JSON); + PutPipelineRequest putRequest = new PutPipelineRequest(id, new BytesArray("{\"processors\": []}"), MediaTypeRegistry.JSON); ClusterState previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); ingestService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState)); @@ -518,7 +519,7 @@ public void testPut() { putRequest = new PutPipelineRequest( id, new BytesArray("{\"processors\": [], \"description\": \"_description\"}"), - XContentType.JSON + MediaTypeRegistry.JSON ); previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); @@ -540,7 +541,7 @@ public void testPutWithErrorResponse() throws IllegalAccessException { PutPipelineRequest putRequest = new PutPipelineRequest( id, new BytesArray("{\"description\": \"empty processors\"}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); @@ -572,9 +573,9 @@ public void testDeleteUsingWildcard() { IngestService ingestService = createWithProcessors(); HashMap pipelines = new HashMap<>(); BytesArray definition = new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"); - pipelines.put("p1", new PipelineConfiguration("p1", definition, XContentType.JSON)); - pipelines.put("p2", new PipelineConfiguration("p2", definition, XContentType.JSON)); - pipelines.put("q1", new PipelineConfiguration("q1", definition, XContentType.JSON)); + pipelines.put("p1", new PipelineConfiguration("p1", definition, MediaTypeRegistry.JSON)); + pipelines.put("p2", new PipelineConfiguration("p2", definition, MediaTypeRegistry.JSON)); + pipelines.put("q1", new PipelineConfiguration("q1", definition, MediaTypeRegistry.JSON)); IngestMetadata ingestMetadata = new IngestMetadata(pipelines); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); ClusterState previousClusterState = clusterState; @@ -620,7 +621,7 @@ public void testDeleteWithExistingUnmatchedPipelines() { IngestService ingestService = createWithProcessors(); HashMap pipelines = new HashMap<>(); BytesArray definition = new BytesArray("{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\"}}]}"); - pipelines.put("p1", new PipelineConfiguration("p1", definition, XContentType.JSON)); + pipelines.put("p1", new PipelineConfiguration("p1", definition, MediaTypeRegistry.JSON)); IngestMetadata ingestMetadata = new IngestMetadata(pipelines); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); ClusterState previousClusterState = clusterState; @@ -641,8 +642,8 @@ public void testDeleteWithExistingUnmatchedPipelines() { public void testGetPipelines() { Map configs = new HashMap<>(); - configs.put("_id1", new PipelineConfiguration("_id1", new BytesArray("{\"processors\": []}"), XContentType.JSON)); - configs.put("_id2", new PipelineConfiguration("_id2", new BytesArray("{\"processors\": []}"), XContentType.JSON)); + configs.put("_id1", new PipelineConfiguration("_id1", new BytesArray("{\"processors\": []}"), MediaTypeRegistry.JSON)); + configs.put("_id2", new PipelineConfiguration("_id2", new BytesArray("{\"processors\": []}"), MediaTypeRegistry.JSON)); assertThat(IngestService.innerGetPipelines(null, "_id1").isEmpty(), is(true)); @@ -684,7 +685,7 @@ public void testValidate() throws Exception { "{\"processors\": [{\"set\" : {\"field\": \"_field\", \"value\": \"_value\", \"tag\": \"tag1\"}}," + "{\"remove\" : {\"field\": \"_field\", \"tag\": \"tag2\"}}]}" ), - XContentType.JSON + MediaTypeRegistry.JSON ); DiscoveryNode node1 = new DiscoveryNode("_node_id1", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT); @@ -724,7 +725,7 @@ public String getType() { PutPipelineRequest putRequest = new PutPipelineRequest( id, new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); @@ -770,7 +771,7 @@ public void testExecuteBulkPipelineDoesNotExist() { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -817,7 +818,7 @@ public void testExecuteSuccess() { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -848,7 +849,7 @@ public void testExecuteEmptyPipeline() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [], \"description\": \"_description\"}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -882,7 +883,7 @@ public void testExecutePropagateAllMetadataUpdates() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -949,7 +950,7 @@ public void testExecuteFailure() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -1009,7 +1010,7 @@ public void testExecuteSuccessWithOnFailure() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -1052,7 +1053,7 @@ public void testExecuteFailureWithNestedOnFailure() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -1123,7 +1124,7 @@ public void testBulkRequestExecutionWithFailures() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -1181,7 +1182,7 @@ public void testBulkRequestExecution() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"mock\": {}}], \"description\": \"_description\"}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); ClusterState previousClusterState = clusterState; @@ -1241,13 +1242,13 @@ public void testStats() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id1", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); ingestService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState)); - putRequest = new PutPipelineRequest("_id2", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), XContentType.JSON); + putRequest = new PutPipelineRequest("_id2", new BytesArray("{\"processors\": [{\"mock\" : {}}]}"), MediaTypeRegistry.JSON); previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); ingestService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState)); @@ -1307,7 +1308,7 @@ public void testStats() throws Exception { putRequest = new PutPipelineRequest( "_id1", new BytesArray("{\"processors\": [{\"mock\" : {}}, {\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); @@ -1340,7 +1341,7 @@ public void testStats() throws Exception { putRequest = new PutPipelineRequest( "_id1", new BytesArray("{\"processors\": [{\"failure-mock\" : { \"on_failure\": [{\"mock\" : {}}]}}, {\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); previousClusterState = clusterState; clusterState = IngestService.innerPut(putRequest, clusterState); @@ -1418,7 +1419,7 @@ public String getDescription() { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"drop\" : {}}, {\"mock\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -1491,7 +1492,7 @@ public Map getProcessors(Processor.Parameters paramet PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"test\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); // Start empty ClusterState previousClusterState = clusterState; @@ -1514,7 +1515,7 @@ public void testCBORParsing() throws Exception { PutPipelineRequest putRequest = new PutPipelineRequest( "_id", new BytesArray("{\"processors\": [{\"foo\" : {}}]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); clusterState = IngestService.innerPut(putRequest, clusterState); ingestService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState)); diff --git a/server/src/test/java/org/opensearch/ingest/PipelineConfigurationTests.java b/server/src/test/java/org/opensearch/ingest/PipelineConfigurationTests.java index aed08c2d1875a..c3ff0f19aafa5 100644 --- a/server/src/test/java/org/opensearch/ingest/PipelineConfigurationTests.java +++ b/server/src/test/java/org/opensearch/ingest/PipelineConfigurationTests.java @@ -38,6 +38,7 @@ import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.xcontent.ContextParser; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; @@ -56,15 +57,15 @@ public void testSerialization() throws IOException { PipelineConfiguration configuration = new PipelineConfiguration( "1", new BytesArray("{}".getBytes(StandardCharsets.UTF_8)), - XContentType.JSON + MediaTypeRegistry.JSON ); - assertEquals(XContentType.JSON, configuration.getMediaType()); + assertEquals(MediaTypeRegistry.JSON, configuration.getMediaType()); BytesStreamOutput out = new BytesStreamOutput(); configuration.writeTo(out); StreamInput in = StreamInput.wrap(out.bytes().toBytesRef().bytes); PipelineConfiguration serialized = PipelineConfiguration.readFrom(in); - assertEquals(XContentType.JSON, serialized.getMediaType()); + assertEquals(MediaTypeRegistry.JSON, serialized.getMediaType()); assertEquals("{}", serialized.getConfig().utf8ToString()); } @@ -73,7 +74,7 @@ public void testParser() throws IOException { XContentType xContentType = randomFrom(XContentType.values()); final BytesReference bytes; try (XContentBuilder builder = XContentBuilder.builder(xContentType.xContent())) { - new PipelineConfiguration("1", new BytesArray("{}".getBytes(StandardCharsets.UTF_8)), XContentType.JSON).toXContent( + new PipelineConfiguration("1", new BytesArray("{}".getBytes(StandardCharsets.UTF_8)), MediaTypeRegistry.JSON).toXContent( builder, ToXContent.EMPTY_PARAMS ); @@ -96,7 +97,7 @@ protected PipelineConfiguration createTestInstance() { } else { config = new BytesArray("{\"foo\": \"bar\"}".getBytes(StandardCharsets.UTF_8)); } - return new PipelineConfiguration(randomAlphaOfLength(4), config, XContentType.JSON); + return new PipelineConfiguration(randomAlphaOfLength(4), config, MediaTypeRegistry.JSON); } @Override diff --git a/server/src/test/java/org/opensearch/persistent/TestPersistentTasksPlugin.java b/server/src/test/java/org/opensearch/persistent/TestPersistentTasksPlugin.java index a0f58e68fcbb4..217fa7cf2d56c 100644 --- a/server/src/test/java/org/opensearch/persistent/TestPersistentTasksPlugin.java +++ b/server/src/test/java/org/opensearch/persistent/TestPersistentTasksPlugin.java @@ -60,9 +60,9 @@ import org.opensearch.core.common.io.stream.StreamOutput; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.settings.SettingsModule; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.ParseField; import org.opensearch.core.xcontent.ConstructingObjectParser; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -300,7 +300,7 @@ public void writeTo(StreamOutput out) throws IOException { @Override public String toString() { - return Strings.toString(XContentType.JSON, this); + return Strings.toString(MediaTypeRegistry.JSON, this); } // Implements equals and hashcode for testing diff --git a/server/src/test/java/org/opensearch/repositories/RepositoryDataTests.java b/server/src/test/java/org/opensearch/repositories/RepositoryDataTests.java index 26e4a2844a4ce..5bd366d7cea9d 100644 --- a/server/src/test/java/org/opensearch/repositories/RepositoryDataTests.java +++ b/server/src/test/java/org/opensearch/repositories/RepositoryDataTests.java @@ -36,6 +36,7 @@ import org.opensearch.Version; import org.opensearch.common.UUIDs; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -296,7 +297,7 @@ public void testIndexThatReferencesAnUnknownSnapshot() throws IOException { } public void testIndexThatReferenceANullSnapshot() throws IOException { - final XContentBuilder builder = XContentBuilder.builder(randomFrom(XContentType.JSON).xContent()); + final XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder(); builder.startObject(); { builder.startArray("snapshots"); diff --git a/server/src/test/java/org/opensearch/rest/BaseRestHandlerTests.java b/server/src/test/java/org/opensearch/rest/BaseRestHandlerTests.java index 1f5e0cda883c5..efc6645ed83d4 100644 --- a/server/src/test/java/org/opensearch/rest/BaseRestHandlerTests.java +++ b/server/src/test/java/org/opensearch/rest/BaseRestHandlerTests.java @@ -36,8 +36,8 @@ import org.opensearch.common.Table; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.rest.action.cat.AbstractCatAction; import org.opensearch.test.OpenSearchTestCase; @@ -299,7 +299,7 @@ public String getName() { try (XContentBuilder builder = JsonXContent.contentBuilder().startObject().endObject()) { final RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(builder.toString()), - XContentType.JSON + MediaTypeRegistry.JSON ).build(); final RestChannel channel = new FakeRestChannel(request, randomBoolean(), 1); handler.handleRequest(request, channel, mockClient); @@ -344,7 +344,7 @@ public String getName() { try (XContentBuilder builder = JsonXContent.contentBuilder().startObject().endObject()) { final RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray(builder.toString()), - XContentType.JSON + MediaTypeRegistry.JSON ).build(); final RestChannel channel = new FakeRestChannel(request, randomBoolean(), 1); final IllegalArgumentException e = expectThrows( diff --git a/server/src/test/java/org/opensearch/rest/RestControllerTests.java b/server/src/test/java/org/opensearch/rest/RestControllerTests.java index b4fa7574f0ff0..77883491ce5d8 100644 --- a/server/src/test/java/org/opensearch/rest/RestControllerTests.java +++ b/server/src/test/java/org/opensearch/rest/RestControllerTests.java @@ -44,6 +44,8 @@ import org.opensearch.core.common.unit.ByteSizeValue; import org.opensearch.common.util.concurrent.ThreadContext; import org.opensearch.core.rest.RestStatus; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.yaml.YamlXContent; @@ -290,7 +292,7 @@ public void testRestHandlerWrapper() throws Exception { return (RestRequest request, RestChannel channel, NodeClient client) -> wrapperCalled.set(true); }, client, circuitBreakerService, usageService, identityService); restController.registerHandler(RestRequest.Method.GET, "/wrapped", handler); - RestRequest request = testRestRequest("/wrapped", "{}", XContentType.JSON); + RestRequest request = testRestRequest("/wrapped", "{}", MediaTypeRegistry.JSON); AssertingChannel channel = new AssertingChannel(request, true, RestStatus.BAD_REQUEST); restController.dispatchRequest(request, channel, client.threadPool().getThreadContext()); httpServerTransport.start(); @@ -301,7 +303,7 @@ public void testRestHandlerWrapper() throws Exception { public void testDispatchRequestAddsAndFreesBytesOnSuccess() { int contentLength = BREAKER_LIMIT.bytesAsInt(); String content = randomAlphaOfLength((int) Math.round(contentLength / inFlightRequestsBreaker.getOverhead())); - RestRequest request = testRestRequest("/", content, XContentType.JSON); + RestRequest request = testRestRequest("/", content, MediaTypeRegistry.JSON); AssertingChannel channel = new AssertingChannel(request, true, RestStatus.OK); restController.dispatchRequest(request, channel, client.threadPool().getThreadContext()); @@ -313,7 +315,7 @@ public void testDispatchRequestAddsAndFreesBytesOnSuccess() { public void testDispatchRequestAddsAndFreesBytesOnError() { int contentLength = BREAKER_LIMIT.bytesAsInt(); String content = randomAlphaOfLength((int) Math.round(contentLength / inFlightRequestsBreaker.getOverhead())); - RestRequest request = testRestRequest("/error", content, XContentType.JSON); + RestRequest request = testRestRequest("/error", content, MediaTypeRegistry.JSON); AssertingChannel channel = new AssertingChannel(request, true, RestStatus.BAD_REQUEST); restController.dispatchRequest(request, channel, client.threadPool().getThreadContext()); @@ -326,7 +328,7 @@ public void testDispatchRequestAddsAndFreesBytesOnlyOnceOnError() { int contentLength = BREAKER_LIMIT.bytesAsInt(); String content = randomAlphaOfLength((int) Math.round(contentLength / inFlightRequestsBreaker.getOverhead())); // we will produce an error in the rest handler and one more when sending the error response - RestRequest request = testRestRequest("/error", content, XContentType.JSON); + RestRequest request = testRestRequest("/error", content, MediaTypeRegistry.JSON); ExceptionThrowingChannel channel = new ExceptionThrowingChannel(request, true); restController.dispatchRequest(request, channel, client.threadPool().getThreadContext()); @@ -338,7 +340,7 @@ public void testDispatchRequestAddsAndFreesBytesOnlyOnceOnError() { public void testDispatchRequestLimitsBytes() { int contentLength = BREAKER_LIMIT.bytesAsInt() + 1; String content = randomAlphaOfLength((int) Math.round(contentLength / inFlightRequestsBreaker.getOverhead())); - RestRequest request = testRestRequest("/", content, XContentType.JSON); + RestRequest request = testRestRequest("/", content, MediaTypeRegistry.JSON); AssertingChannel channel = new AssertingChannel(request, true, RestStatus.TOO_MANY_REQUESTS); restController.dispatchRequest(request, channel, client.threadPool().getThreadContext()); @@ -576,7 +578,7 @@ public void testHandleBadRequestWithHtmlSpecialCharsInUri() { public void testHandleBadInputWithCreateIndex() { final FakeRestRequest fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withPath("/foo") .withMethod(RestRequest.Method.PUT) - .withContent(new BytesArray("ddd"), XContentType.JSON) + .withContent(new BytesArray("ddd"), MediaTypeRegistry.JSON) .build(); final AssertingChannel channel = new AssertingChannel(fakeRestRequest, true, RestStatus.BAD_REQUEST); restController.registerHandler(RestRequest.Method.PUT, "/foo", new RestCreateIndexAction()); @@ -731,10 +733,10 @@ public void sendResponse(RestResponse response) { } } - private static RestRequest testRestRequest(String path, String content, XContentType xContentType) { + private static RestRequest testRestRequest(String path, String content, MediaType mediaType) { FakeRestRequest.Builder builder = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY); builder.withPath(path); - builder.withContent(new BytesArray(content), xContentType); + builder.withContent(new BytesArray(content), mediaType); return builder.build(); } } diff --git a/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestClusterAddWeightedRoutingActionTests.java b/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestClusterAddWeightedRoutingActionTests.java index 4d61ccad10b45..13dc418d07296 100644 --- a/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestClusterAddWeightedRoutingActionTests.java +++ b/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestClusterAddWeightedRoutingActionTests.java @@ -13,7 +13,7 @@ import org.opensearch.OpenSearchParseException; import org.opensearch.action.admin.cluster.shards.routing.weighted.put.ClusterPutWeightedRoutingRequest; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.rest.RestRequest; import org.opensearch.test.rest.FakeRestRequest; import org.opensearch.test.rest.RestActionTestCase; @@ -70,7 +70,7 @@ private RestRequest buildRestRequest(String content) { return new FakeRestRequest.Builder(xContentRegistry()).withMethod(RestRequest.Method.PUT) .withPath("/_cluster/routing/awareness/zone/weights") .withParams(singletonMap("attribute", "zone")) - .withContent(new BytesArray(content), XContentType.JSON) + .withContent(new BytesArray(content), MediaTypeRegistry.JSON) .build(); } diff --git a/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestClusterDeleteWeightedRoutingActionTests.java b/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestClusterDeleteWeightedRoutingActionTests.java index b11103a9cab11..1214accf91961 100644 --- a/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestClusterDeleteWeightedRoutingActionTests.java +++ b/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestClusterDeleteWeightedRoutingActionTests.java @@ -12,7 +12,7 @@ import org.opensearch.OpenSearchParseException; import org.opensearch.action.admin.cluster.shards.routing.weighted.delete.ClusterDeleteWeightedRoutingRequest; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.rest.RestRequest; import org.opensearch.test.rest.FakeRestRequest; import org.opensearch.test.rest.RestActionTestCase; @@ -57,14 +57,14 @@ private RestRequest buildRestRequestWithAwarenessAttribute(String content) { return new FakeRestRequest.Builder(xContentRegistry()).withMethod(RestRequest.Method.DELETE) .withPath("/_cluster/routing/awareness/zone/weights") .withParams(singletonMap("attribute", "zone")) - .withContent(new BytesArray(content), XContentType.JSON) + .withContent(new BytesArray(content), MediaTypeRegistry.JSON) .build(); } private RestRequest buildRestRequest(String content) { return new FakeRestRequest.Builder(xContentRegistry()).withMethod(RestRequest.Method.DELETE) .withPath("/_cluster/routing/awareness/weights") - .withContent(new BytesArray(content), XContentType.JSON) + .withContent(new BytesArray(content), MediaTypeRegistry.JSON) .build(); } diff --git a/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestReloadSecureSettingsActionTests.java b/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestReloadSecureSettingsActionTests.java index d8f460dccbf4e..e976886458f05 100644 --- a/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestReloadSecureSettingsActionTests.java +++ b/server/src/test/java/org/opensearch/rest/action/admin/cluster/RestReloadSecureSettingsActionTests.java @@ -34,9 +34,9 @@ import org.opensearch.action.admin.cluster.node.reload.NodesReloadSecureSettingsRequest; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.OpenSearchTestCase; import static org.hamcrest.Matchers.nullValue; @@ -46,7 +46,7 @@ public class RestReloadSecureSettingsActionTests extends OpenSearchTestCase { public void testParserWithPassword() throws Exception { final String request = "{" + "\"secure_settings_password\": \"secure_settings_password_string\"" + "}"; try ( - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, request) ) { NodesReloadSecureSettingsRequest reloadSecureSettingsRequest = RestReloadSecureSettingsAction.PARSER.parse(parser, null); @@ -57,7 +57,7 @@ public void testParserWithPassword() throws Exception { public void testParserWithoutPassword() throws Exception { final String request = "{" + "}"; try ( - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, request) ) { NodesReloadSecureSettingsRequest reloadSecureSettingsRequest = RestReloadSecureSettingsAction.PARSER.parse(parser, null); diff --git a/server/src/test/java/org/opensearch/rest/action/admin/indices/RestAnalyzeActionTests.java b/server/src/test/java/org/opensearch/rest/action/admin/indices/RestAnalyzeActionTests.java index 1c6c4eca6ca0d..ed16f3c681ae6 100644 --- a/server/src/test/java/org/opensearch/rest/action/admin/indices/RestAnalyzeActionTests.java +++ b/server/src/test/java/org/opensearch/rest/action/admin/indices/RestAnalyzeActionTests.java @@ -35,8 +35,8 @@ import org.opensearch.client.node.NodeClient; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.xcontent.XContentFactory; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.analysis.NameOrDefinition; import org.opensearch.rest.RestRequest; import org.opensearch.test.OpenSearchTestCase; @@ -118,7 +118,7 @@ public void testParseXContentForAnalyzeRequestWithInvalidJsonThrowsException() { RestAnalyzeAction action = new RestAnalyzeAction(); RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray("{invalid_json}"), - XContentType.JSON + MediaTypeRegistry.JSON ).build(); try (NodeClient client = new NoOpNodeClient(this.getClass().getSimpleName())) { IOException e = expectThrows(IOException.class, () -> action.handleRequest(request, null, client)); diff --git a/server/src/test/java/org/opensearch/rest/action/admin/indices/RestGetAliasesActionTests.java b/server/src/test/java/org/opensearch/rest/action/admin/indices/RestGetAliasesActionTests.java index 1fbc628ed7f2c..3d60f6029e564 100644 --- a/server/src/test/java/org/opensearch/rest/action/admin/indices/RestGetAliasesActionTests.java +++ b/server/src/test/java/org/opensearch/rest/action/admin/indices/RestGetAliasesActionTests.java @@ -35,7 +35,6 @@ import org.opensearch.cluster.metadata.AliasMetadata; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.rest.RestResponse; import org.opensearch.test.OpenSearchTestCase; @@ -60,7 +59,7 @@ public class RestGetAliasesActionTests extends OpenSearchTestCase { // }' public void testBareRequest() throws Exception { - final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); final Map> openMapBuilder = new HashMap<>(); final AliasMetadata foobarAliasMetadata = AliasMetadata.builder("foobar").build(); final AliasMetadata fooAliasMetadata = AliasMetadata.builder("foo").build(); @@ -72,7 +71,7 @@ public void testBareRequest() throws Exception { } public void testSimpleAliasWildcardMatchingNothing() throws Exception { - final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); final Map> openMapBuilder = new HashMap<>(); final RestResponse restResponse = RestGetAliasesAction.buildRestResponse( true, @@ -86,7 +85,7 @@ public void testSimpleAliasWildcardMatchingNothing() throws Exception { } public void testMultipleAliasWildcardsSomeMatching() throws Exception { - final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); final Map> openMapBuilder = new HashMap<>(); final AliasMetadata aliasMetadata = AliasMetadata.builder("foobar").build(); openMapBuilder.put("index", Arrays.asList(aliasMetadata)); @@ -102,7 +101,7 @@ public void testMultipleAliasWildcardsSomeMatching() throws Exception { } public void testAliasWildcardsIncludeAndExcludeAll() throws Exception { - final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); final Map> openMapBuilder = new HashMap<>(); final RestResponse restResponse = RestGetAliasesAction.buildRestResponse( true, @@ -116,7 +115,7 @@ public void testAliasWildcardsIncludeAndExcludeAll() throws Exception { } public void testAliasWildcardsIncludeAndExcludeSome() throws Exception { - final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); final Map> openMapBuilder = new HashMap<>(); final AliasMetadata aliasMetadata = AliasMetadata.builder("foo").build(); openMapBuilder.put("index", Arrays.asList(aliasMetadata)); @@ -132,7 +131,7 @@ public void testAliasWildcardsIncludeAndExcludeSome() throws Exception { } public void testAliasWildcardsIncludeAndExcludeSomeAndExplicitMissing() throws Exception { - final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); final Map> openMapBuilder = new HashMap<>(); final AliasMetadata aliasMetadata = AliasMetadata.builder("foo").build(); openMapBuilder.put("index", Arrays.asList(aliasMetadata)); @@ -153,7 +152,7 @@ public void testAliasWildcardsIncludeAndExcludeSomeAndExplicitMissing() throws E } public void testAliasWildcardsExcludeExplicitMissing() throws Exception { - final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(XContentType.JSON); + final XContentBuilder xContentBuilder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON); final Map> openMapBuilder = new HashMap<>(); final RestResponse restResponse = RestGetAliasesAction.buildRestResponse( true, diff --git a/server/src/test/java/org/opensearch/rest/action/admin/indices/RestValidateQueryActionTests.java b/server/src/test/java/org/opensearch/rest/action/admin/indices/RestValidateQueryActionTests.java index 2f15090e49f75..6b463c3697162 100644 --- a/server/src/test/java/org/opensearch/rest/action/admin/indices/RestValidateQueryActionTests.java +++ b/server/src/test/java/org/opensearch/rest/action/admin/indices/RestValidateQueryActionTests.java @@ -43,7 +43,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.io.stream.NamedWriteableRegistry; import org.opensearch.common.settings.Settings; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.identity.IdentityService; import org.opensearch.core.indices.breaker.NoneCircuitBreakerService; import org.opensearch.rest.RestController; @@ -182,7 +182,7 @@ public void testRestValidateQueryAction_malformedQuery() throws Exception { private RestRequest createRestRequest(String content) { return new FakeRestRequest.Builder(xContentRegistry()).withPath("index1/type1/_validate/query") .withParams(emptyMap()) - .withContent(new BytesArray(content), XContentType.JSON) + .withContent(new BytesArray(content), MediaTypeRegistry.JSON) .build(); } } diff --git a/server/src/test/java/org/opensearch/rest/action/cat/RestTableTests.java b/server/src/test/java/org/opensearch/rest/action/cat/RestTableTests.java index 89fbcf6a3506d..8183cb1d3b910 100644 --- a/server/src/test/java/org/opensearch/rest/action/cat/RestTableTests.java +++ b/server/src/test/java/org/opensearch/rest/action/cat/RestTableTests.java @@ -34,6 +34,7 @@ import org.opensearch.common.Table; import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.rest.AbstractRestChannel; import org.opensearch.rest.RestResponse; import org.opensearch.test.OpenSearchTestCase; @@ -55,7 +56,7 @@ public class RestTableTests extends OpenSearchTestCase { - private static final String APPLICATION_JSON = XContentType.JSON.mediaType(); + private static final String APPLICATION_JSON = MediaTypeRegistry.JSON.mediaType(); private static final String APPLICATION_YAML = XContentType.YAML.mediaType(); private static final String APPLICATION_SMILE = XContentType.SMILE.mediaType(); private static final String APPLICATION_CBOR = XContentType.CBOR.mediaType(); diff --git a/server/src/test/java/org/opensearch/rest/action/document/RestBulkActionTests.java b/server/src/test/java/org/opensearch/rest/action/document/RestBulkActionTests.java index f795d340778cf..9462a8f419bbf 100644 --- a/server/src/test/java/org/opensearch/rest/action/document/RestBulkActionTests.java +++ b/server/src/test/java/org/opensearch/rest/action/document/RestBulkActionTests.java @@ -40,7 +40,7 @@ import org.opensearch.client.node.NodeClient; import org.opensearch.common.SetOnce; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.rest.RestChannel; import org.opensearch.rest.RestRequest; import org.opensearch.test.OpenSearchTestCase; @@ -82,7 +82,7 @@ public void bulk(BulkRequest request, ActionListener listener) { + "{\"update\":{\"_id\":\"2\"}}\n" + "{\"script\":{\"source\":\"ctx._source.counter++;\"},\"upsert\":{\"field1\":\"upserted_val\"}}\n" ), - XContentType.JSON + MediaTypeRegistry.JSON ) .withMethod(RestRequest.Method.POST) .build(), diff --git a/server/src/test/java/org/opensearch/rest/action/document/RestIndexActionTests.java b/server/src/test/java/org/opensearch/rest/action/document/RestIndexActionTests.java index 4131e8d9a55c6..4bb11965a46e9 100644 --- a/server/src/test/java/org/opensearch/rest/action/document/RestIndexActionTests.java +++ b/server/src/test/java/org/opensearch/rest/action/document/RestIndexActionTests.java @@ -41,7 +41,7 @@ import org.opensearch.cluster.node.DiscoveryNodes; import org.opensearch.common.SetOnce; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.rest.RestRequest; import org.opensearch.rest.action.document.RestIndexAction.AutoIdHandler; import org.opensearch.rest.action.document.RestIndexAction.CreateHandler; @@ -104,7 +104,7 @@ private void checkAutoIdOpType(Version minClusterVersion, DocWriteRequest.OpType }); RestRequest autoIdRequest = new FakeRestRequest.Builder(xContentRegistry()).withMethod(RestRequest.Method.POST) .withPath("/some_index/_doc") - .withContent(new BytesArray("{}"), XContentType.JSON) + .withContent(new BytesArray("{}"), MediaTypeRegistry.JSON) .build(); clusterStateSupplier.set( ClusterState.builder(ClusterName.DEFAULT) diff --git a/server/src/test/java/org/opensearch/rest/action/document/RestUpdateActionTests.java b/server/src/test/java/org/opensearch/rest/action/document/RestUpdateActionTests.java index f66f07a22e660..67f45467d0052 100644 --- a/server/src/test/java/org/opensearch/rest/action/document/RestUpdateActionTests.java +++ b/server/src/test/java/org/opensearch/rest/action/document/RestUpdateActionTests.java @@ -35,7 +35,7 @@ import org.opensearch.action.ActionRequestValidationException; import org.opensearch.client.node.NodeClient; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.VersionType; import org.opensearch.rest.RestRequest; import org.opensearch.test.rest.FakeRestRequest; @@ -72,7 +72,7 @@ public void testUpdateDocVersion() { FakeRestRequest updateRequest = new FakeRestRequest.Builder(xContentRegistry()).withMethod(RestRequest.Method.POST) .withPath("test/_update/1") .withParams(params) - .withContent(new BytesArray(content), XContentType.JSON) + .withContent(new BytesArray(content), MediaTypeRegistry.JSON) .build(); ActionRequestValidationException e = expectThrows( ActionRequestValidationException.class, diff --git a/server/src/test/java/org/opensearch/script/ScriptContextInfoTests.java b/server/src/test/java/org/opensearch/script/ScriptContextInfoTests.java index e10e199c4415c..e4118401711d6 100644 --- a/server/src/test/java/org/opensearch/script/ScriptContextInfoTests.java +++ b/server/src/test/java/org/opensearch/script/ScriptContextInfoTests.java @@ -35,11 +35,11 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.collect.Tuple; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.script.ScriptContextInfo.ScriptMethodInfo; import org.opensearch.script.ScriptContextInfo.ScriptMethodInfo.ParameterInfo; import org.opensearch.test.OpenSearchTestCase; @@ -317,7 +317,7 @@ public void testGetterConditional() { public void testParameterInfoParser() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, @@ -330,7 +330,7 @@ public void testParameterInfoParser() throws IOException { public void testScriptMethodInfoParser() throws IOException { String json = "{\"name\": \"fooFunc\", \"return_type\": \"int\", \"params\": [{\"type\": \"int\", \"name\": \"fooParam\"}, " + "{\"type\": \"java.util.Map\", \"name\": \"barParam\"}]}"; - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new BytesArray(json).streamInput()); ScriptContextInfo.ScriptMethodInfo info = ScriptContextInfo.ScriptMethodInfo.fromXContent(parser); assertEquals( @@ -395,7 +395,7 @@ public void testScriptContextInfoParser() throws IOException { + " }" + " ]" + "}"; - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new BytesArray(json).streamInput()); ScriptContextInfo parsed = ScriptContextInfo.fromXContent(parser); ScriptContextInfo expected = new ScriptContextInfo( diff --git a/server/src/test/java/org/opensearch/script/ScriptMetadataTests.java b/server/src/test/java/org/opensearch/script/ScriptMetadataTests.java index 83e7a3712a9ad..0ac530e6d14f9 100644 --- a/server/src/test/java/org/opensearch/script/ScriptMetadataTests.java +++ b/server/src/test/java/org/opensearch/script/ScriptMetadataTests.java @@ -37,6 +37,7 @@ import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.xcontent.DeprecationHandler; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; @@ -54,7 +55,7 @@ public void testFromXContentLoading() throws Exception { // failure to load to old namespace scripts with the same id but different langs XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject().field("lang0#id0", "script0").field("lang1#id0", "script1").endObject(); - XContentParser parser0 = XContentType.JSON.xContent() + XContentParser parser0 = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, @@ -71,7 +72,7 @@ public void testFromXContentLoading() throws Exception { .field("source", "script1") .endObject() .endObject(); - XContentParser parser1 = XContentType.JSON.xContent() + XContentParser parser1 = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, @@ -93,7 +94,7 @@ public void testFromXContentLoading() throws Exception { .field("source", "script1") .endObject() .endObject(); - XContentParser parser2 = XContentType.JSON.xContent() + XContentParser parser2 = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, @@ -110,7 +111,7 @@ public void testFromXContentLoading() throws Exception { .field("source", "script1") .endObject() .endObject(); - XContentParser parser3 = XContentType.JSON.xContent() + XContentParser parser3 = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, @@ -148,15 +149,24 @@ public void testDiff() throws Exception { ScriptMetadata.Builder builder = new ScriptMetadata.Builder(null); builder.storeScript( "1", - StoredScriptSource.parse(new BytesArray("{\"script\":{\"lang\":\"mustache\",\"source\":{\"foo\":\"abc\"}}}"), XContentType.JSON) + StoredScriptSource.parse( + new BytesArray("{\"script\":{\"lang\":\"mustache\",\"source\":{\"foo\":\"abc\"}}}"), + MediaTypeRegistry.JSON + ) ); builder.storeScript( "2", - StoredScriptSource.parse(new BytesArray("{\"script\":{\"lang\":\"mustache\",\"source\":{\"foo\":\"def\"}}}"), XContentType.JSON) + StoredScriptSource.parse( + new BytesArray("{\"script\":{\"lang\":\"mustache\",\"source\":{\"foo\":\"def\"}}}"), + MediaTypeRegistry.JSON + ) ); builder.storeScript( "3", - StoredScriptSource.parse(new BytesArray("{\"script\":{\"lang\":\"mustache\",\"source\":{\"foo\":\"ghi\"}}}"), XContentType.JSON) + StoredScriptSource.parse( + new BytesArray("{\"script\":{\"lang\":\"mustache\",\"source\":{\"foo\":\"ghi\"}}}"), + MediaTypeRegistry.JSON + ) ); ScriptMetadata scriptMetadata1 = builder.build(); @@ -165,13 +175,16 @@ public void testDiff() throws Exception { "2", StoredScriptSource.parse( new BytesArray("{\"script\":{\"lang\":\"mustache\",\"source\":{\"foo\":\"changed\"}}}"), - XContentType.JSON + MediaTypeRegistry.JSON ) ); builder.deleteScript("3"); builder.storeScript( "4", - StoredScriptSource.parse(new BytesArray("{\"script\":{\"lang\":\"mustache\",\"source\":{\"foo\":\"jkl\"}}}"), XContentType.JSON) + StoredScriptSource.parse( + new BytesArray("{\"script\":{\"lang\":\"mustache\",\"source\":{\"foo\":\"jkl\"}}}"), + MediaTypeRegistry.JSON + ) ); ScriptMetadata scriptMetadata2 = builder.build(); @@ -193,7 +206,10 @@ public void testBuilder() { ScriptMetadata.Builder builder = new ScriptMetadata.Builder(null); builder.storeScript( "_id", - StoredScriptSource.parse(new BytesArray("{\"script\": {\"lang\": \"painless\", \"source\": \"1 + 1\"} }"), XContentType.JSON) + StoredScriptSource.parse( + new BytesArray("{\"script\": {\"lang\": \"painless\", \"source\": \"1 + 1\"} }"), + MediaTypeRegistry.JSON + ) ); ScriptMetadata result = builder.build(); @@ -203,7 +219,7 @@ public void testBuilder() { public void testLoadEmptyScripts() throws IOException { XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject().field("mustache#empty", "").endObject(); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, @@ -214,7 +230,7 @@ public void testLoadEmptyScripts() throws IOException { builder = XContentFactory.jsonBuilder(); builder.startObject().field("lang#empty", "").endObject(); - parser = XContentType.JSON.xContent() + parser = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, @@ -225,7 +241,7 @@ public void testLoadEmptyScripts() throws IOException { builder = XContentFactory.jsonBuilder(); builder.startObject().startObject("script").field("lang", "lang").field("source", "").endObject().endObject(); - parser = XContentType.JSON.xContent() + parser = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, @@ -236,7 +252,7 @@ public void testLoadEmptyScripts() throws IOException { builder = XContentFactory.jsonBuilder(); builder.startObject().startObject("script").field("lang", "mustache").field("source", "").endObject().endObject(); - parser = XContentType.JSON.xContent() + parser = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, @@ -247,7 +263,7 @@ public void testLoadEmptyScripts() throws IOException { } public void testOldStyleDropped() throws IOException { - XContentBuilder builder = XContentBuilder.builder(XContentType.JSON.xContent()); + XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder(); builder.startObject(); { @@ -272,7 +288,7 @@ public void testOldStyleDropped() throws IOException { } builder.endObject(); - XContentParser parser = XContentType.JSON.xContent() + XContentParser parser = MediaTypeRegistry.JSON.xContent() .createParser( NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, diff --git a/server/src/test/java/org/opensearch/script/ScriptServiceTests.java b/server/src/test/java/org/opensearch/script/ScriptServiceTests.java index a4288eeab4524..2c9e32acd0d91 100644 --- a/server/src/test/java/org/opensearch/script/ScriptServiceTests.java +++ b/server/src/test/java/org/opensearch/script/ScriptServiceTests.java @@ -44,7 +44,7 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.TimeValue; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.env.Environment; import org.opensearch.test.OpenSearchTestCase; import org.junit.Before; @@ -375,7 +375,11 @@ public void testStoreScript() throws Exception { .endObject() .endObject() ); - ScriptMetadata scriptMetadata = ScriptMetadata.putStoredScript(null, "_id", StoredScriptSource.parse(script, XContentType.JSON)); + ScriptMetadata scriptMetadata = ScriptMetadata.putStoredScript( + null, + "_id", + StoredScriptSource.parse(script, MediaTypeRegistry.JSON) + ); assertNotNull(scriptMetadata); assertEquals("abc", scriptMetadata.getStoredScript("_id").getSource()); } @@ -384,7 +388,7 @@ public void testDeleteScript() throws Exception { ScriptMetadata scriptMetadata = ScriptMetadata.putStoredScript( null, "_id", - StoredScriptSource.parse(new BytesArray("{\"script\": {\"lang\": \"_lang\", \"source\": \"abc\"} }"), XContentType.JSON) + StoredScriptSource.parse(new BytesArray("{\"script\": {\"lang\": \"_lang\", \"source\": \"abc\"} }"), MediaTypeRegistry.JSON) ); scriptMetadata = ScriptMetadata.deleteStoredScript(scriptMetadata, "_id"); assertNotNull(scriptMetadata); @@ -408,7 +412,7 @@ public void testGetStoredScript() throws Exception { "_id", StoredScriptSource.parse( new BytesArray("{\"script\": {\"lang\": \"_lang\", \"source\": \"abc\"} }"), - XContentType.JSON + MediaTypeRegistry.JSON ) ).build() ) diff --git a/server/src/test/java/org/opensearch/script/ScriptTests.java b/server/src/test/java/org/opensearch/script/ScriptTests.java index a884226ab300c..0b871ee4847cc 100644 --- a/server/src/test/java/org/opensearch/script/ScriptTests.java +++ b/server/src/test/java/org/opensearch/script/ScriptTests.java @@ -97,7 +97,9 @@ private Script createScript() throws IOException { scriptType, scriptType == ScriptType.STORED ? null : randomFrom("_lang1", "_lang2", "_lang3"), script, - scriptType == ScriptType.INLINE ? Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()) : null, + scriptType == ScriptType.INLINE + ? Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType()) + : null, params ); } @@ -168,8 +170,8 @@ public void testParseFromObjectFromScript() { } Script script = new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, "doc['field']", options, params); Map scriptObject = XContentHelper.convertToMap( - XContentType.JSON.xContent(), - Strings.toString(XContentType.JSON, script), + MediaTypeRegistry.JSON.xContent(), + Strings.toString(MediaTypeRegistry.JSON, script), false ); Script parsedScript = Script.parse(scriptObject); diff --git a/server/src/test/java/org/opensearch/script/StoredScriptSourceTests.java b/server/src/test/java/org/opensearch/script/StoredScriptSourceTests.java index f926c84596310..78cf9f632ae37 100644 --- a/server/src/test/java/org/opensearch/script/StoredScriptSourceTests.java +++ b/server/src/test/java/org/opensearch/script/StoredScriptSourceTests.java @@ -34,6 +34,8 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.Writeable.Reader; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -47,9 +49,9 @@ public class StoredScriptSourceTests extends AbstractSerializingTestCase options = new HashMap<>(); if (randomBoolean()) { - options.put(Script.CONTENT_TYPE_OPTION, xContentType.mediaType()); + options.put(Script.CONTENT_TYPE_OPTION, mediaType.mediaType()); } - return StoredScriptSource.parse(BytesReference.bytes(template), xContentType); + return StoredScriptSource.parse(BytesReference.bytes(template), mediaType); } catch (IOException e) { throw new AssertionError("Failed to create test instance", e); } @@ -87,7 +89,7 @@ protected StoredScriptSource mutateInstance(StoredScriptSource instance) throws String lang = instance.getLang(); Map options = instance.getOptions(); - XContentType newXContentType = randomFrom(XContentType.JSON, XContentType.YAML); + MediaType newXContentType = randomFrom(MediaTypeRegistry.JSON, XContentType.YAML); XContentBuilder newTemplate = XContentBuilder.builder(newXContentType.xContent()); newTemplate.startObject(); newTemplate.startObject("query"); diff --git a/server/src/test/java/org/opensearch/script/StoredScriptTests.java b/server/src/test/java/org/opensearch/script/StoredScriptTests.java index 09b4cce6bd19b..36d9f4dc6e601 100644 --- a/server/src/test/java/org/opensearch/script/StoredScriptTests.java +++ b/server/src/test/java/org/opensearch/script/StoredScriptTests.java @@ -39,7 +39,6 @@ import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.test.AbstractSerializingTestCase; import java.io.IOException; @@ -72,17 +71,17 @@ public void testInvalidDelete() { public void testSourceParsing() throws Exception { // simple script value string - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject().startObject("script").field("lang", "lang").field("source", "code").endObject().endObject(); - StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON); + StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON); StoredScriptSource source = new StoredScriptSource("lang", "code", Collections.emptyMap()); assertThat(parsed, equalTo(source)); } // complex template using script as the field name - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject() .startObject("script") .field("lang", "mustache") @@ -97,7 +96,7 @@ public void testSourceParsing() throws Exception { code = cb.startObject().field("query", "code").endObject().toString(); } - StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON); + StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON); StoredScriptSource source = new StoredScriptSource( "mustache", code, @@ -108,20 +107,20 @@ public void testSourceParsing() throws Exception { } // complex script with script object - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject().field("script").startObject().field("lang", "lang").field("source", "code").endObject().endObject(); - StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON); + StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON); StoredScriptSource source = new StoredScriptSource("lang", "code", Collections.emptyMap()); assertThat(parsed, equalTo(source)); } // complex script using "code" backcompat - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject().field("script").startObject().field("lang", "lang").field("code", "code").endObject().endObject(); - StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON); + StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON); StoredScriptSource source = new StoredScriptSource("lang", "code", Collections.emptyMap()); assertThat(parsed, equalTo(source)); @@ -129,7 +128,7 @@ public void testSourceParsing() throws Exception { assertWarnings("Deprecated field [code] used, expected [source] instead"); // complex script with script object and empty options - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject() .field("script") .startObject() @@ -141,14 +140,14 @@ public void testSourceParsing() throws Exception { .endObject() .endObject(); - StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON); + StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON); StoredScriptSource source = new StoredScriptSource("lang", "code", Collections.emptyMap()); assertThat(parsed, equalTo(source)); } // complex script with embedded template - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject() .field("script") .startObject() @@ -167,7 +166,7 @@ public void testSourceParsing() throws Exception { code = cb.startObject().field("query", "code").endObject().toString(); } - StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON); + StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON); StoredScriptSource source = new StoredScriptSource( "lang", code, @@ -180,29 +179,29 @@ public void testSourceParsing() throws Exception { public void testSourceParsingErrors() throws Exception { // check for missing lang parameter when parsing a script - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject().field("script").startObject().field("source", "code").endObject().endObject(); IllegalArgumentException iae = expectThrows( IllegalArgumentException.class, - () -> StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON) + () -> StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON) ); assertThat(iae.getMessage(), equalTo("must specify lang for stored script")); } // check for missing source parameter when parsing a script - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject().field("script").startObject().field("lang", "lang").endObject().endObject(); IllegalArgumentException iae = expectThrows( IllegalArgumentException.class, - () -> StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON) + () -> StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON) ); assertThat(iae.getMessage(), equalTo("must specify source for stored script")); } // check for illegal options parameter when parsing a script - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject() .field("script") .startObject() @@ -216,17 +215,17 @@ public void testSourceParsingErrors() throws Exception { IllegalArgumentException iae = expectThrows( IllegalArgumentException.class, - () -> StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON) + () -> StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON) ); assertThat(iae.getMessage(), equalTo("illegal compiler options [{option=option}] specified")); } // check for unsupported template context - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject().field("template", "code").endObject(); ParsingException pEx = expectThrows( ParsingException.class, - () -> StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON) + () -> StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON) ); assertThat( pEx.getMessage(), @@ -236,20 +235,20 @@ public void testSourceParsingErrors() throws Exception { } public void testEmptyTemplateDeprecations() throws IOException { - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject().endObject(); - StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON); + StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON); StoredScriptSource source = new StoredScriptSource(Script.DEFAULT_TEMPLATE_LANG, "", Collections.emptyMap()); assertThat(parsed, equalTo(source)); assertWarnings("empty templates should no longer be used"); } - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(XContentType.JSON)) { + try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.JSON)) { builder.startObject().field("script").startObject().field("lang", "mustache").field("source", "").endObject().endObject(); - StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), XContentType.JSON); + StoredScriptSource parsed = StoredScriptSource.parse(BytesReference.bytes(builder), MediaTypeRegistry.JSON); StoredScriptSource source = new StoredScriptSource(Script.DEFAULT_TEMPLATE_LANG, "", Collections.emptyMap()); assertThat(parsed, equalTo(source)); diff --git a/server/src/test/java/org/opensearch/search/SearchHitTests.java b/server/src/test/java/org/opensearch/search/SearchHitTests.java index af52bdb83916c..18bc3cac93eca 100644 --- a/server/src/test/java/org/opensearch/search/SearchHitTests.java +++ b/server/src/test/java/org/opensearch/search/SearchHitTests.java @@ -40,6 +40,8 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.document.DocumentField; import org.opensearch.core.common.io.stream.Writeable; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -63,7 +65,7 @@ import java.util.Map; import java.util.function.Predicate; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.test.XContentTestUtils.insertRandomFields; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; import static org.hamcrest.Matchers.containsString; @@ -78,7 +80,7 @@ public static SearchHit createTestItem(boolean withOptionalInnerHits, boolean wi return createTestItem(randomFrom(XContentType.values()), withOptionalInnerHits, withShardTarget); } - public static SearchHit createTestItem(XContentType xContentType, boolean withOptionalInnerHits, boolean transportSerialization) { + public static SearchHit createTestItem(final MediaType mediaType, boolean withOptionalInnerHits, boolean transportSerialization) { int internalId = randomInt(); String uid = randomAlphaOfLength(10); NestedIdentity nestedIdentity = null; @@ -89,8 +91,8 @@ public static SearchHit createTestItem(XContentType xContentType, boolean withOp Map documentFields = new HashMap<>(); if (frequently()) { if (randomBoolean()) { - metaFields = GetResultTests.randomDocumentFields(xContentType, true).v2(); - documentFields = GetResultTests.randomDocumentFields(xContentType, false).v2(); + metaFields = GetResultTests.randomDocumentFields(mediaType, true).v2(); + documentFields = GetResultTests.randomDocumentFields(mediaType, false).v2(); } } @@ -103,7 +105,7 @@ public static SearchHit createTestItem(XContentType xContentType, boolean withOp } } if (frequently()) { - hit.sourceRef(RandomObjects.randomSource(random(), xContentType)); + hit.sourceRef(RandomObjects.randomSource(random(), mediaType)); } if (randomBoolean()) { hit.version(randomLong()); @@ -114,7 +116,7 @@ public static SearchHit createTestItem(XContentType xContentType, boolean withOp hit.version(randomLongBetween(1, Long.MAX_VALUE)); } if (randomBoolean()) { - hit.sortValues(SearchSortValuesTests.createTestItem(xContentType, transportSerialization)); + hit.sortValues(SearchSortValuesTests.createTestItem(mediaType, transportSerialization)); } if (randomBoolean()) { int size = randomIntBetween(0, 5); @@ -141,7 +143,7 @@ public static SearchHit createTestItem(XContentType xContentType, boolean withOp if (innerHitsSize > 0) { Map innerHits = new HashMap<>(innerHitsSize); for (int i = 0; i < innerHitsSize; i++) { - innerHits.put(randomAlphaOfLength(5), SearchHitsTests.createTestItem(xContentType, false, transportSerialization)); + innerHits.put(randomAlphaOfLength(5), SearchHitsTests.createTestItem(mediaType, false, transportSerialization)); } hit.setInnerHits(innerHits); } @@ -318,7 +320,7 @@ public void testHasSource() { public void testWeirdScriptFields() throws Exception { { XContentParser parser = createParser( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), "{\n" + " \"_index\": \"twitter\",\n" + " \"_id\": \"1\",\n" @@ -338,7 +340,7 @@ public void testWeirdScriptFields() throws Exception { } { XContentParser parser = createParser( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), "{\n" + " \"_index\": \"twitter\",\n" + " \"_id\": \"1\",\n" @@ -394,11 +396,11 @@ public void testToXContentEmptyFields() throws IOException { fields.put("bar", new DocumentField("bar", Collections.emptyList())); SearchHit hit = new SearchHit(0, "_id", null, fields, Collections.emptyMap()); { - BytesReference originalBytes = toShuffledXContent(hit, XContentType.JSON, ToXContent.EMPTY_PARAMS, randomBoolean()); + BytesReference originalBytes = toShuffledXContent(hit, MediaTypeRegistry.JSON, ToXContent.EMPTY_PARAMS, randomBoolean()); // checks that the fields section is completely omitted in the rendering. assertThat(originalBytes.utf8ToString(), not(containsString("fields"))); final SearchHit parsed; - try (XContentParser parser = createParser(XContentType.JSON.xContent(), originalBytes)) { + try (XContentParser parser = createParser(MediaTypeRegistry.JSON.xContent(), originalBytes)) { parser.nextToken(); // jump to first START_OBJECT parsed = SearchHit.fromXContent(parser); assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken()); @@ -412,9 +414,9 @@ public void testToXContentEmptyFields() throws IOException { fields.put("bar", new DocumentField("bar", Collections.singletonList("value"))); hit = new SearchHit(0, "_id", null, fields, Collections.emptyMap()); { - BytesReference originalBytes = toShuffledXContent(hit, XContentType.JSON, ToXContent.EMPTY_PARAMS, randomBoolean()); + BytesReference originalBytes = toShuffledXContent(hit, MediaTypeRegistry.JSON, ToXContent.EMPTY_PARAMS, randomBoolean()); final SearchHit parsed; - try (XContentParser parser = createParser(XContentType.JSON.xContent(), originalBytes)) { + try (XContentParser parser = createParser(MediaTypeRegistry.JSON.xContent(), originalBytes)) { parser.nextToken(); // jump to first START_OBJECT parsed = SearchHit.fromXContent(parser); assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken()); @@ -428,9 +430,9 @@ public void testToXContentEmptyFields() throws IOException { metadata.put("_routing", new DocumentField("_routing", Collections.emptyList())); hit = new SearchHit(0, "_id", null, fields, Collections.emptyMap()); { - BytesReference originalBytes = toShuffledXContent(hit, XContentType.JSON, ToXContent.EMPTY_PARAMS, randomBoolean()); + BytesReference originalBytes = toShuffledXContent(hit, MediaTypeRegistry.JSON, ToXContent.EMPTY_PARAMS, randomBoolean()); final SearchHit parsed; - try (XContentParser parser = createParser(XContentType.JSON.xContent(), originalBytes)) { + try (XContentParser parser = createParser(MediaTypeRegistry.JSON.xContent(), originalBytes)) { parser.nextToken(); // jump to first START_OBJECT parsed = SearchHit.fromXContent(parser); assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken()); diff --git a/server/src/test/java/org/opensearch/search/SearchHitsTests.java b/server/src/test/java/org/opensearch/search/SearchHitsTests.java index 442dd4e8fc51b..ec0369602b537 100644 --- a/server/src/test/java/org/opensearch/search/SearchHitsTests.java +++ b/server/src/test/java/org/opensearch/search/SearchHitsTests.java @@ -40,6 +40,7 @@ import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.lucene.LuceneTests; import org.opensearch.common.xcontent.LoggingDeprecationHandler; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -61,13 +62,13 @@ public static SearchHits createTestItem(boolean withOptionalInnerHits, boolean w private static SearchHit[] createSearchHitArray( int size, - XContentType xContentType, + final MediaType mediaType, boolean withOptionalInnerHits, boolean transportSerialization ) { SearchHit[] hits = new SearchHit[size]; for (int i = 0; i < hits.length; i++) { - hits[i] = SearchHitTests.createTestItem(xContentType, withOptionalInnerHits, transportSerialization); + hits[i] = SearchHitTests.createTestItem(mediaType, withOptionalInnerHits, transportSerialization); } return hits; } @@ -77,18 +78,18 @@ private static TotalHits randomTotalHits(TotalHits.Relation relation) { return new TotalHits(totalHits, relation); } - public static SearchHits createTestItem(XContentType xContentType, boolean withOptionalInnerHits, boolean transportSerialization) { - return createTestItem(xContentType, withOptionalInnerHits, transportSerialization, randomFrom(TotalHits.Relation.values())); + public static SearchHits createTestItem(final MediaType mediaType, boolean withOptionalInnerHits, boolean transportSerialization) { + return createTestItem(mediaType, withOptionalInnerHits, transportSerialization, randomFrom(TotalHits.Relation.values())); } private static SearchHits createTestItem( - XContentType xContentType, + final MediaType mediaType, boolean withOptionalInnerHits, boolean transportSerialization, TotalHits.Relation totalHitsRelation ) { int searchHits = randomIntBetween(0, 5); - SearchHit[] hits = createSearchHitArray(searchHits, xContentType, withOptionalInnerHits, transportSerialization); + SearchHit[] hits = createSearchHitArray(searchHits, mediaType, withOptionalInnerHits, transportSerialization); TotalHits totalHits = frequently() ? randomTotalHits(totalHitsRelation) : null; float maxScore = frequently() ? randomFloat() : Float.NaN; SortField[] sortFields = null; @@ -223,13 +224,13 @@ protected SearchHits createTestInstance() { } @Override - protected SearchHits createXContextTestInstance(XContentType xContentType) { + protected SearchHits createXContextTestInstance(final MediaType mediaType) { // We don't set SearchHit#shard (withShardTarget is false) in this test // because the rest serialization does not render this information so the // deserialized hit cannot be equal to the original instance. // There is another test (#testFromXContentWithShards) that checks the // rest serialization with shard targets. - return createTestItem(xContentType, true, false); + return createTestItem(mediaType, true, false); } @Override diff --git a/server/src/test/java/org/opensearch/search/SearchSortValuesTests.java b/server/src/test/java/org/opensearch/search/SearchSortValuesTests.java index 7efe157f88bf0..8fb39339bc6e2 100644 --- a/server/src/test/java/org/opensearch/search/SearchSortValuesTests.java +++ b/server/src/test/java/org/opensearch/search/SearchSortValuesTests.java @@ -35,6 +35,7 @@ import org.apache.lucene.util.BytesRef; import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.common.lucene.LuceneTests; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -48,13 +49,13 @@ public class SearchSortValuesTests extends AbstractSerializingTestCase { - public static SearchSortValues createTestItem(XContentType xContentType, boolean transportSerialization) { + public static SearchSortValues createTestItem(final MediaType mediaType, boolean transportSerialization) { int size = randomIntBetween(1, 20); Object[] values = new Object[size]; if (transportSerialization) { DocValueFormat[] sortValueFormats = new DocValueFormat[size]; for (int i = 0; i < size; i++) { - Object sortValue = randomSortValue(xContentType, transportSerialization); + Object sortValue = randomSortValue(mediaType, transportSerialization); values[i] = sortValue; // make sure that for BytesRef, we provide a specific doc value format that overrides format(BytesRef) sortValueFormats[i] = sortValue instanceof BytesRef ? DocValueFormat.RAW : randomDocValueFormat(); @@ -63,7 +64,7 @@ public static SearchSortValues createTestItem(XContentType xContentType, boolean } else { // xcontent serialization doesn't write/parse the raw sort values, only the formatted ones for (int i = 0; i < size; i++) { - Object sortValue = randomSortValue(xContentType, transportSerialization); + Object sortValue = randomSortValue(mediaType, transportSerialization); // make sure that BytesRef are not provided as formatted values sortValue = sortValue instanceof BytesRef ? DocValueFormat.RAW.format((BytesRef) sortValue) : sortValue; values[i] = sortValue; @@ -72,10 +73,10 @@ public static SearchSortValues createTestItem(XContentType xContentType, boolean } } - private static Object randomSortValue(XContentType xContentType, boolean transportSerialization) { + private static Object randomSortValue(final MediaType mediaType, boolean transportSerialization) { Object randomSortValue = LuceneTests.randomSortValue(); // to simplify things, we directly serialize what we expect we would parse back when testing xcontent serialization - return transportSerialization ? randomSortValue : RandomObjects.getExpectedParsedValue(xContentType, randomSortValue); + return transportSerialization ? randomSortValue : RandomObjects.getExpectedParsedValue(mediaType, randomSortValue); } private static DocValueFormat randomDocValueFormat() { @@ -102,8 +103,8 @@ protected SearchSortValues doParseInstance(XContentParser parser) throws IOExcep } @Override - protected SearchSortValues createXContextTestInstance(XContentType xContentType) { - return createTestItem(xContentType, false); + protected SearchSortValues createXContextTestInstance(final MediaType mediaType) { + return createTestItem(mediaType, false); } @Override diff --git a/server/src/test/java/org/opensearch/search/geo/GeoQueryTests.java b/server/src/test/java/org/opensearch/search/geo/GeoQueryTests.java index 8af50bc498d90..03c5548071bda 100644 --- a/server/src/test/java/org/opensearch/search/geo/GeoQueryTests.java +++ b/server/src/test/java/org/opensearch/search/geo/GeoQueryTests.java @@ -42,9 +42,9 @@ import org.opensearch.common.geo.builders.GeometryCollectionBuilder; import org.opensearch.common.geo.builders.MultiPolygonBuilder; import org.opensearch.common.geo.builders.PolygonBuilder; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.geometry.Geometry; import org.opensearch.geometry.Rectangle; import org.opensearch.index.query.GeoShapeQueryBuilder; @@ -87,7 +87,7 @@ public void testNullShape() throws Exception { client().prepareIndex(defaultIndexName) .setId("aNullshape") - .setSource("{\"geo\": null}", XContentType.JSON) + .setSource("{\"geo\": null}", MediaTypeRegistry.JSON) .setRefreshPolicy(IMMEDIATE) .get(); GetResponse result = client().prepareGet(defaultIndexName, "aNullshape").get(); diff --git a/server/src/test/java/org/opensearch/search/geo/GeoShapeQueryTests.java b/server/src/test/java/org/opensearch/search/geo/GeoShapeQueryTests.java index ace4861b5c682..8e22acf8d1861 100644 --- a/server/src/test/java/org/opensearch/search/geo/GeoShapeQueryTests.java +++ b/server/src/test/java/org/opensearch/search/geo/GeoShapeQueryTests.java @@ -50,10 +50,10 @@ import org.opensearch.common.geo.builders.ShapeBuilder; import org.opensearch.common.settings.Settings; import org.opensearch.common.unit.DistanceUnit; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.index.mapper.LegacyGeoShapeFieldMapper; import org.opensearch.index.mapper.MapperParsingException; import org.opensearch.index.query.ExistsQueryBuilder; @@ -155,7 +155,7 @@ public void testShapeFetchingPath() throws Exception { .setId("1") .setSource( String.format(Locale.ROOT, "{ %s, \"1\" : { %s, \"2\" : { %s, \"3\" : { %s } }} }", location, location, location, location), - XContentType.JSON + MediaTypeRegistry.JSON ) .setRefreshPolicy(IMMEDIATE) .get(); @@ -291,7 +291,7 @@ public void testEnvelopeSpanningDateline() throws Exception { + "],\r\n" + "\"type\": \"Point\"\r\n" + "}}"; - client().index(new IndexRequest("test").id("1").source(doc1, XContentType.JSON).setRefreshPolicy(IMMEDIATE)).actionGet(); + client().index(new IndexRequest("test").id("1").source(doc1, MediaTypeRegistry.JSON).setRefreshPolicy(IMMEDIATE)).actionGet(); String doc2 = "{\"geo\": {\r\n" + "\"coordinates\": [\r\n" @@ -300,7 +300,7 @@ public void testEnvelopeSpanningDateline() throws Exception { + "],\r\n" + "\"type\": \"Point\"\r\n" + "}}"; - client().index(new IndexRequest("test").id("2").source(doc2, XContentType.JSON).setRefreshPolicy(IMMEDIATE)).actionGet(); + client().index(new IndexRequest("test").id("2").source(doc2, MediaTypeRegistry.JSON).setRefreshPolicy(IMMEDIATE)).actionGet(); String doc3 = "{\"geo\": {\r\n" + "\"coordinates\": [\r\n" @@ -309,7 +309,7 @@ public void testEnvelopeSpanningDateline() throws Exception { + "],\r\n" + "\"type\": \"Point\"\r\n" + "}}"; - client().index(new IndexRequest("test").id("3").source(doc3, XContentType.JSON).setRefreshPolicy(IMMEDIATE)).actionGet(); + client().index(new IndexRequest("test").id("3").source(doc3, MediaTypeRegistry.JSON).setRefreshPolicy(IMMEDIATE)).actionGet(); @SuppressWarnings("unchecked") CheckedSupplier querySupplier = randomFrom( diff --git a/server/src/test/java/org/opensearch/search/pipeline/SearchPipelineServiceTests.java b/server/src/test/java/org/opensearch/search/pipeline/SearchPipelineServiceTests.java index 9fc0be38d66a5..a7711d54ec8a9 100644 --- a/server/src/test/java/org/opensearch/search/pipeline/SearchPipelineServiceTests.java +++ b/server/src/test/java/org/opensearch/search/pipeline/SearchPipelineServiceTests.java @@ -44,9 +44,9 @@ import org.opensearch.common.settings.Settings; import org.opensearch.common.util.concurrent.AtomicArray; import org.opensearch.common.util.concurrent.OpenSearchExecutors; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.core.common.io.stream.NamedWriteableRegistry; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.index.IndexSettings; import org.opensearch.index.query.TermQueryBuilder; import org.opensearch.plugins.SearchPipelinePlugin; @@ -173,7 +173,7 @@ public void testResolveIndexDefaultPipeline() throws Exception { new PipelineConfiguration( "p1", new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ); @@ -403,7 +403,7 @@ public void testUpdatePipelines() { + "\"phase_results_processors\" : [ { \"max_score\" : { \"score\": 100 } } ]" + "}" ), - XContentType.JSON + MediaTypeRegistry.JSON ); SearchPipelineMetadata pipelineMetadata = new SearchPipelineMetadata(Map.of("_id", pipeline)); clusterState = ClusterState.builder(clusterState) @@ -438,7 +438,7 @@ public void testPutPipeline() { ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); - PutSearchPipelineRequest putRequest = new PutSearchPipelineRequest(id, new BytesArray("{}"), XContentType.JSON); + PutSearchPipelineRequest putRequest = new PutSearchPipelineRequest(id, new BytesArray("{}"), MediaTypeRegistry.JSON); ClusterState previousClusterState = clusterState; clusterState = SearchPipelineService.innerPut(putRequest, clusterState); searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState)); @@ -450,7 +450,7 @@ public void testPutPipeline() { assertEquals(0, pipeline.pipeline.getSearchResponseProcessors().size()); // Overwrite pipeline - putRequest = new PutSearchPipelineRequest(id, new BytesArray("{ \"description\": \"empty pipeline\"}"), XContentType.JSON); + putRequest = new PutSearchPipelineRequest(id, new BytesArray("{ \"description\": \"empty pipeline\"}"), MediaTypeRegistry.JSON); previousClusterState = clusterState; clusterState = SearchPipelineService.innerPut(putRequest, clusterState); searchPipelineService.applyClusterState(new ClusterChangedEvent("", clusterState, previousClusterState)); @@ -473,7 +473,7 @@ public void testPutInvalidPipeline() throws IllegalAccessException { PutSearchPipelineRequest putRequest = new PutSearchPipelineRequest( id, new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : \"foo\" } } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ); clusterState = SearchPipelineService.innerPut(putRequest, clusterState); try (MockLogAppender mockAppender = MockLogAppender.createForLoggers(LogManager.getLogger(SearchPipelineService.class))) { @@ -496,7 +496,7 @@ public void testDeletePipeline() { PipelineConfiguration config = new PipelineConfiguration( "_id", new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ); SearchPipelineMetadata searchPipelineMetadata = new SearchPipelineMetadata(Map.of("_id", config)); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); @@ -529,11 +529,11 @@ public void testDeletePipelinesWithWildcard() { SearchPipelineMetadata metadata = new SearchPipelineMetadata( Map.of( "p1", - new PipelineConfiguration("p1", definition, XContentType.JSON), + new PipelineConfiguration("p1", definition, MediaTypeRegistry.JSON), "p2", - new PipelineConfiguration("p2", definition, XContentType.JSON), + new PipelineConfiguration("p2", definition, MediaTypeRegistry.JSON), "q1", - new PipelineConfiguration("q1", definition, XContentType.JSON) + new PipelineConfiguration("q1", definition, MediaTypeRegistry.JSON) ) ); ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).build(); @@ -582,7 +582,7 @@ public void testTransformRequest() throws Exception { new PipelineConfiguration( "p1", new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ); @@ -617,7 +617,7 @@ public void testTransformResponse() throws Exception { new PipelineConfiguration( "p1", new BytesArray("{\"response_processors\" : [ { \"fixed_score\": { \"score\" : 2 } } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ); @@ -662,7 +662,7 @@ public void testTransformSearchPhase() { new PipelineConfiguration( "p1", new BytesArray("{\"phase_results_processors\" : [ { \"max_score\" : { } } ]}"), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ); @@ -747,19 +747,19 @@ public void testGetPipelines() { new PipelineConfiguration( "p1", new BytesArray("{\"request_processors\" : [ { \"scale_request_size\": { \"scale\" : 2 } } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ), "p2", new PipelineConfiguration( "p2", new BytesArray("{\"response_processors\" : [ { \"fixed_score\": { \"score\" : 2 } } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ), "p3", new PipelineConfiguration( "p3", new BytesArray("{\"phase_results_processors\" : [ { \"max_score\" : { } } ]}"), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ); @@ -818,7 +818,7 @@ public void testValidatePipeline() throws Exception { + "\"phase_results_processors\" : [ { \"max_score\" : { } } ]" + "}" ), - XContentType.JSON + MediaTypeRegistry.JSON ); SearchPipelineInfo completePipelineInfo = new SearchPipelineInfo( @@ -843,7 +843,7 @@ public void testValidatePipeline() throws Exception { + "\"response_processors\": [{ \"fixed_score\": { \"score\" : 2 } }]" + "}" ), - XContentType.JSON + MediaTypeRegistry.JSON ); expectThrows( ClassCastException.class, @@ -1241,25 +1241,25 @@ private SearchPipelineService getSearchPipelineService( new PipelineConfiguration( "good_response_pipeline", new BytesArray("{\"response_processors\" : [ { \"successful_response\": {} } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ), "bad_response_pipeline", new PipelineConfiguration( "bad_response_pipeline", new BytesArray("{\"response_processors\" : [ { \"throwing_response\": {} } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ), "good_request_pipeline", new PipelineConfiguration( "good_request_pipeline", new BytesArray("{\"request_processors\" : [ { \"successful_request\": {} } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ), "bad_request_pipeline", new PipelineConfiguration( "bad_request_pipeline", new BytesArray("{\"request_processors\" : [ { \"throwing_request\": {} } ] }"), - XContentType.JSON + MediaTypeRegistry.JSON ) ) ); @@ -1299,7 +1299,7 @@ public void testAdHocRejectingProcessor() { PutSearchPipelineRequest putRequest = new PutSearchPipelineRequest( id, new BytesArray("{\"request_processors\":[" + " { \"" + processorType + "\": {}}" + "]}"), - XContentType.JSON + MediaTypeRegistry.JSON ); ClusterState previousClusterState = clusterState; clusterState = SearchPipelineService.innerPut(putRequest, clusterState); diff --git a/server/src/test/java/org/opensearch/search/pipeline/SearchPipelineStatsTests.java b/server/src/test/java/org/opensearch/search/pipeline/SearchPipelineStatsTests.java index 90a6e99057b0e..2b904b5bc627f 100644 --- a/server/src/test/java/org/opensearch/search/pipeline/SearchPipelineStatsTests.java +++ b/server/src/test/java/org/opensearch/search/pipeline/SearchPipelineStatsTests.java @@ -11,12 +11,12 @@ import org.opensearch.common.io.stream.BytesStreamOutput; import org.opensearch.common.metrics.OperationStats; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.io.stream.StreamInput; import org.opensearch.core.xcontent.DeprecationHandler; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.test.OpenSearchTestCase; @@ -178,8 +178,8 @@ public void testToXContent() throws IOException { expectedBuilder.generator().copyCurrentStructure(expectedParser); assertEquals( - XContentHelper.convertToMap(BytesReference.bytes(expectedBuilder), false, (MediaType) XContentType.JSON), - XContentHelper.convertToMap(BytesReference.bytes(actualBuilder), false, (MediaType) XContentType.JSON) + XContentHelper.convertToMap(BytesReference.bytes(expectedBuilder), false, (MediaType) MediaTypeRegistry.JSON), + XContentHelper.convertToMap(BytesReference.bytes(actualBuilder), false, (MediaType) MediaTypeRegistry.JSON) ); } } diff --git a/server/src/test/java/org/opensearch/search/pit/RestDeletePitActionTests.java b/server/src/test/java/org/opensearch/search/pit/RestDeletePitActionTests.java index 4880afb896a40..d8e04519ed865 100644 --- a/server/src/test/java/org/opensearch/search/pit/RestDeletePitActionTests.java +++ b/server/src/test/java/org/opensearch/search/pit/RestDeletePitActionTests.java @@ -14,7 +14,7 @@ import org.opensearch.client.node.NodeClient; import org.opensearch.common.SetOnce; import org.opensearch.core.common.bytes.BytesArray; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.rest.RestRequest; import org.opensearch.rest.action.search.RestDeletePitAction; import org.opensearch.test.OpenSearchTestCase; @@ -35,7 +35,7 @@ public void testParseDeletePitRequestWithInvalidJsonThrowsException() throws Exc RestDeletePitAction action = new RestDeletePitAction(); RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withContent( new BytesArray("{invalid_json}"), - XContentType.JSON + MediaTypeRegistry.JSON ).build(); Exception e = expectThrows(IllegalArgumentException.class, () -> action.prepareRequest(request, null)); assertThat(e.getMessage(), equalTo("Failed to parse request body")); @@ -54,7 +54,7 @@ public void deletePits(DeletePitRequest request, ActionListener action.prepareRequest(request, null)); assertThat(e.getMessage(), equalTo("Failed to parse request body")); @@ -76,7 +76,7 @@ public void clearScroll(ClearScrollRequest request, ActionListener action.prepareRequest(request, null)); assertThat(e.getMessage(), equalTo("Failed to parse request body")); @@ -78,7 +78,7 @@ public void searchScroll(SearchScrollRequest request, ActionListener> contexts = Collections.singletonMap("key", Collections.singleton("value")); CompletionSuggestion.Entry.Option option = new CompletionSuggestion.Entry.Option(1, new Text("someText"), 1.3f, contexts); - BytesReference xContent = toXContent(option, XContentType.JSON, randomBoolean()); + BytesReference xContent = toXContent(option, MediaTypeRegistry.JSON, randomBoolean()); assertEquals("{\"text\":\"someText\",\"score\":1.3,\"contexts\":{\"key\":[\"value\"]}}", xContent.utf8ToString()); } } diff --git a/server/src/test/java/org/opensearch/search/suggest/SuggestTests.java b/server/src/test/java/org/opensearch/search/suggest/SuggestTests.java index e046b415dbcf3..606bf8d9d280d 100644 --- a/server/src/test/java/org/opensearch/search/suggest/SuggestTests.java +++ b/server/src/test/java/org/opensearch/search/suggest/SuggestTests.java @@ -41,6 +41,7 @@ import org.opensearch.core.common.io.stream.NamedWriteableRegistry; import org.opensearch.common.settings.Settings; import org.opensearch.core.common.text.Text; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; @@ -66,7 +67,7 @@ import static java.util.Collections.emptyList; import static org.opensearch.common.xcontent.XContentHelper.stripWhitespace; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.core.xcontent.XContentParserUtils.ensureFieldName; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; @@ -162,7 +163,7 @@ public void testToXContent() throws IOException { PhraseSuggestion suggestion = new PhraseSuggestion("suggestionName", 5); suggestion.addTerm(entry); Suggest suggest = new Suggest(Collections.singletonList(suggestion)); - BytesReference xContent = toXContent(suggest, XContentType.JSON, randomBoolean()); + BytesReference xContent = toXContent(suggest, MediaTypeRegistry.JSON, randomBoolean()); assertEquals( stripWhitespace( "{" diff --git a/server/src/test/java/org/opensearch/search/suggest/SuggestionEntryTests.java b/server/src/test/java/org/opensearch/search/suggest/SuggestionEntryTests.java index f8cc6bb5c9f2e..09bdfde4e7fa6 100644 --- a/server/src/test/java/org/opensearch/search/suggest/SuggestionEntryTests.java +++ b/server/src/test/java/org/opensearch/search/suggest/SuggestionEntryTests.java @@ -34,6 +34,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.text.Text; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -52,7 +53,7 @@ import java.util.function.Predicate; import java.util.function.Supplier; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.test.XContentTestUtils.insertRandomFields; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; @@ -156,7 +157,7 @@ public void testToXContent() throws IOException { ); PhraseSuggestion.Entry phraseEntry = new PhraseSuggestion.Entry(new Text("entryText"), 42, 313); phraseEntry.addOption(phraseOption); - BytesReference xContent = toXContent(phraseEntry, XContentType.JSON, randomBoolean()); + BytesReference xContent = toXContent(phraseEntry, MediaTypeRegistry.JSON, randomBoolean()); assertEquals( "{\"text\":\"entryText\"," + "\"offset\":42," @@ -173,7 +174,7 @@ public void testToXContent() throws IOException { TermSuggestion.Entry.Option termOption = new TermSuggestion.Entry.Option(new Text("termSuggestOption"), 42, 3.13f); TermSuggestion.Entry termEntry = new TermSuggestion.Entry(new Text("entryText"), 42, 313); termEntry.addOption(termOption); - xContent = toXContent(termEntry, XContentType.JSON, randomBoolean()); + xContent = toXContent(termEntry, MediaTypeRegistry.JSON, randomBoolean()); assertEquals( "{\"text\":\"entryText\"," + "\"offset\":42," @@ -194,7 +195,7 @@ public void testToXContent() throws IOException { ); CompletionSuggestion.Entry completionEntry = new CompletionSuggestion.Entry(new Text("entryText"), 42, 313); completionEntry.addOption(completionOption); - xContent = toXContent(completionEntry, XContentType.JSON, randomBoolean()); + xContent = toXContent(completionEntry, MediaTypeRegistry.JSON, randomBoolean()); assertEquals( "{\"text\":\"entryText\"," + "\"offset\":42," diff --git a/server/src/test/java/org/opensearch/search/suggest/SuggestionOptionTests.java b/server/src/test/java/org/opensearch/search/suggest/SuggestionOptionTests.java index 76d8301d6260d..d8a94aefa0c90 100644 --- a/server/src/test/java/org/opensearch/search/suggest/SuggestionOptionTests.java +++ b/server/src/test/java/org/opensearch/search/suggest/SuggestionOptionTests.java @@ -34,6 +34,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.text.Text; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -43,7 +44,7 @@ import java.io.IOException; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.test.XContentTestUtils.insertRandomFields; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; @@ -93,7 +94,7 @@ private void doTestFromXContent(boolean addRandomFields) throws IOException { public void testToXContent() throws IOException { Option option = new PhraseSuggestion.Entry.Option(new Text("someText"), new Text("somethingHighlighted"), 1.3f, true); - BytesReference xContent = toXContent(option, XContentType.JSON, randomBoolean()); + BytesReference xContent = toXContent(option, MediaTypeRegistry.JSON, randomBoolean()); assertEquals( ("{" + " \"text\": \"someText\"," diff --git a/server/src/test/java/org/opensearch/search/suggest/SuggestionTests.java b/server/src/test/java/org/opensearch/search/suggest/SuggestionTests.java index f1933ca43f2f9..ea55cf4f29771 100644 --- a/server/src/test/java/org/opensearch/search/suggest/SuggestionTests.java +++ b/server/src/test/java/org/opensearch/search/suggest/SuggestionTests.java @@ -35,6 +35,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.text.Text; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedObjectNotFoundException; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; @@ -58,7 +59,7 @@ import java.util.function.Predicate; import java.util.function.Supplier; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.test.XContentTestUtils.insertRandomFields; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; @@ -229,7 +230,7 @@ public void testToXContent() throws IOException { entry.addOption(option); PhraseSuggestion suggestion = new PhraseSuggestion("suggestionName", 5); suggestion.addTerm(entry); - BytesReference xContent = toXContent(suggestion, XContentType.JSON, params, randomBoolean()); + BytesReference xContent = toXContent(suggestion, MediaTypeRegistry.JSON, params, randomBoolean()); assertEquals( ("{" + " \"phrase#suggestionName\": [" @@ -262,7 +263,7 @@ public void testToXContent() throws IOException { entry.addOption(option); PhraseSuggestion suggestion = new PhraseSuggestion("suggestionName", 5); suggestion.addTerm(entry); - BytesReference xContent = toXContent(suggestion, XContentType.JSON, params, randomBoolean()); + BytesReference xContent = toXContent(suggestion, MediaTypeRegistry.JSON, params, randomBoolean()); assertEquals( ("{" + " \"phrase#suggestionName\": [" @@ -290,7 +291,7 @@ public void testToXContent() throws IOException { entry.addOption(option); TermSuggestion suggestion = new TermSuggestion("suggestionName", 5, SortBy.SCORE); suggestion.addTerm(entry); - BytesReference xContent = toXContent(suggestion, XContentType.JSON, params, randomBoolean()); + BytesReference xContent = toXContent(suggestion, MediaTypeRegistry.JSON, params, randomBoolean()); assertEquals( ("{" + " \"term#suggestionName\": [" @@ -318,7 +319,7 @@ public void testToXContent() throws IOException { entry.addOption(option); CompletionSuggestion suggestion = new CompletionSuggestion("suggestionName", 5, randomBoolean()); suggestion.addTerm(entry); - BytesReference xContent = toXContent(suggestion, XContentType.JSON, params, randomBoolean()); + BytesReference xContent = toXContent(suggestion, MediaTypeRegistry.JSON, params, randomBoolean()); assertEquals( ("{" + " \"completion#suggestionName\": [" diff --git a/server/src/test/java/org/opensearch/search/suggest/TermSuggestionOptionTests.java b/server/src/test/java/org/opensearch/search/suggest/TermSuggestionOptionTests.java index b032f7729cb1d..9371801c35d58 100644 --- a/server/src/test/java/org/opensearch/search/suggest/TermSuggestionOptionTests.java +++ b/server/src/test/java/org/opensearch/search/suggest/TermSuggestionOptionTests.java @@ -34,6 +34,7 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.text.Text; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -42,7 +43,7 @@ import java.io.IOException; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken; import static org.opensearch.test.XContentTestUtils.insertRandomFields; import static org.opensearch.test.hamcrest.OpenSearchAssertions.assertToXContentEquivalent; @@ -90,7 +91,7 @@ private void doTestFromXContent(boolean addRandomFields) throws IOException { public void testToXContent() throws IOException { Option option = new Option(new Text("someText"), 100, 1.3f); - BytesReference xContent = toXContent(option, XContentType.JSON, randomBoolean()); + BytesReference xContent = toXContent(option, MediaTypeRegistry.JSON, randomBoolean()); assertEquals("{\"text\":\"someText\",\"score\":1.3,\"freq\":100}", xContent.utf8ToString()); } diff --git a/server/src/test/java/org/opensearch/search/suggest/completion/CategoryContextMappingTests.java b/server/src/test/java/org/opensearch/search/suggest/completion/CategoryContextMappingTests.java index b617d83372e53..be8a94251df22 100644 --- a/server/src/test/java/org/opensearch/search/suggest/completion/CategoryContextMappingTests.java +++ b/server/src/test/java/org/opensearch/search/suggest/completion/CategoryContextMappingTests.java @@ -44,10 +44,10 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParseException; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.index.mapper.CompletionFieldMapper.CompletionFieldType; import org.opensearch.index.mapper.DocumentMapper; @@ -115,7 +115,7 @@ public void testIndexingWithNoContexts() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(fieldMapper.name()); @@ -159,7 +159,7 @@ public void testIndexingWithSimpleContexts() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(fieldMapper.name()); @@ -203,7 +203,7 @@ public void testIndexingWithSimpleNumberContexts() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(fieldMapper.name()); @@ -247,7 +247,7 @@ public void testIndexingWithSimpleBooleanContexts() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(fieldMapper.name()); @@ -287,7 +287,7 @@ public void testIndexingWithSimpleNULLContexts() throws Exception { Exception e = expectThrows( MapperParsingException.class, - () -> defaultMapper.parse(new SourceToParse("test", "1", BytesReference.bytes(builder), XContentType.JSON)) + () -> defaultMapper.parse(new SourceToParse("test", "1", BytesReference.bytes(builder), MediaTypeRegistry.JSON)) ); assertEquals( "contexts must be a string, number or boolean or a list of string, number or boolean, but was [VALUE_NULL]", @@ -330,7 +330,7 @@ public void testIndexingWithContextList() throws Exception { .endObject() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(fieldMapper.name()); @@ -372,7 +372,7 @@ public void testIndexingWithMixedTypeContextList() throws Exception { .endObject() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(fieldMapper.name()); @@ -410,7 +410,7 @@ public void testIndexingWithMixedTypeContextListHavingNULL() throws Exception { Exception e = expectThrows( MapperParsingException.class, - () -> defaultMapper.parse(new SourceToParse("test", "1", BytesReference.bytes(builder), XContentType.JSON)) + () -> defaultMapper.parse(new SourceToParse("test", "1", BytesReference.bytes(builder), MediaTypeRegistry.JSON)) ); assertEquals("context array must have string, number or boolean values, but was [VALUE_NULL]", e.getCause().getMessage()); } @@ -452,7 +452,7 @@ public void testIndexingWithMultipleContexts() throws Exception { .endArray() .endObject(); ParsedDocument parsedDocument = defaultMapper.parse( - new SourceToParse("test", "1", BytesReference.bytes(builder), XContentType.JSON) + new SourceToParse("test", "1", BytesReference.bytes(builder), MediaTypeRegistry.JSON) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(fieldMapper.name()); assertContextSuggestFields(fields, 3); diff --git a/server/src/test/java/org/opensearch/search/suggest/completion/GeoContextMappingTests.java b/server/src/test/java/org/opensearch/search/suggest/completion/GeoContextMappingTests.java index d641090f1a5aa..d6df208e3d1d9 100644 --- a/server/src/test/java/org/opensearch/search/suggest/completion/GeoContextMappingTests.java +++ b/server/src/test/java/org/opensearch/search/suggest/completion/GeoContextMappingTests.java @@ -36,9 +36,9 @@ import org.opensearch.OpenSearchParseException; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.index.mapper.MappedFieldType; import org.opensearch.index.mapper.MapperService; @@ -102,7 +102,7 @@ public void testIndexingWithNoContexts() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(completionFieldType.name()); @@ -147,7 +147,7 @@ public void testIndexingWithSimpleContexts() throws Exception { .endArray() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(completionFieldType.name()); @@ -196,7 +196,7 @@ public void testIndexingWithContextList() throws Exception { .endObject() .endObject() ), - XContentType.JSON + MediaTypeRegistry.JSON ) ); IndexableField[] fields = parsedDocument.rootDoc().getFields(completionFieldType.name()); @@ -237,7 +237,7 @@ public void testIndexingWithMultipleContexts() throws Exception { .endArray() .endObject(); ParsedDocument parsedDocument = mapperService.documentMapper() - .parse(new SourceToParse("test", "1", BytesReference.bytes(builder), XContentType.JSON)); + .parse(new SourceToParse("test", "1", BytesReference.bytes(builder), MediaTypeRegistry.JSON)); IndexableField[] fields = parsedDocument.rootDoc().getFields(completionFieldType.name()); assertContextSuggestFields(fields, 3); } diff --git a/server/src/test/java/org/opensearch/test/search/aggregations/bucket/SharedSignificantTermsTestMethods.java b/server/src/test/java/org/opensearch/test/search/aggregations/bucket/SharedSignificantTermsTestMethods.java index 34774758dcd0e..402f2002a0564 100644 --- a/server/src/test/java/org/opensearch/test/search/aggregations/bucket/SharedSignificantTermsTestMethods.java +++ b/server/src/test/java/org/opensearch/test/search/aggregations/bucket/SharedSignificantTermsTestMethods.java @@ -34,7 +34,7 @@ import org.opensearch.action.index.IndexRequestBuilder; import org.opensearch.action.search.SearchResponse; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.search.aggregations.Aggregation; import org.opensearch.search.aggregations.bucket.terms.SignificantTerms; import org.opensearch.search.aggregations.bucket.terms.StringTerms; @@ -99,7 +99,7 @@ public static void index01Docs(String type, String settings, OpenSearchIntegTest } assertAcked( testCase.prepareCreate(INDEX_NAME) - .setSettings(settings, XContentType.JSON) + .setSettings(settings, MediaTypeRegistry.JSON) .setMapping("text", textMappings, CLASS_FIELD, "type=keyword") ); String[] gb = { "0", "1" }; @@ -122,7 +122,7 @@ public static void index01DocsWithRouting(String type, String settings, OpenSear } assertAcked( testCase.prepareCreate(INDEX_NAME) - .setSettings(settings, XContentType.JSON) + .setSettings(settings, MediaTypeRegistry.JSON) .setMapping("text", textMappings, CLASS_FIELD, "type=keyword") ); String[] gb = { "0", "1" }; diff --git a/server/src/test/java/org/opensearch/threadpool/ThreadPoolStatsTests.java b/server/src/test/java/org/opensearch/threadpool/ThreadPoolStatsTests.java index e99a7aa462cbb..7b66fd276d573 100644 --- a/server/src/test/java/org/opensearch/threadpool/ThreadPoolStatsTests.java +++ b/server/src/test/java/org/opensearch/threadpool/ThreadPoolStatsTests.java @@ -33,10 +33,10 @@ package org.opensearch.threadpool; import org.opensearch.common.io.stream.BytesStreamOutput; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.test.OpenSearchTestCase; @@ -86,7 +86,7 @@ public void testThreadPoolStatsToXContent() throws IOException { stats.add(new ThreadPoolStats.Stats(ThreadPool.Names.SAME, -1, 0, 0, 0, 0, 0L)); ThreadPoolStats threadPoolStats = new ThreadPoolStats(stats); - try (XContentBuilder builder = new XContentBuilder(XContentType.JSON.xContent(), os)) { + try (XContentBuilder builder = new XContentBuilder(MediaTypeRegistry.JSON.xContent(), os)) { builder.startObject(); threadPoolStats.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); diff --git a/test/framework/src/main/java/org/opensearch/index/engine/EngineTestCase.java b/test/framework/src/main/java/org/opensearch/index/engine/EngineTestCase.java index 39d7edf8c4956..3e74a335e5af9 100644 --- a/test/framework/src/main/java/org/opensearch/index/engine/EngineTestCase.java +++ b/test/framework/src/main/java/org/opensearch/index/engine/EngineTestCase.java @@ -83,10 +83,10 @@ import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.BigArrays; import org.opensearch.common.util.set.Sets; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.util.io.IOUtils; import org.opensearch.core.index.Index; import org.opensearch.index.IndexSettings; @@ -422,7 +422,7 @@ protected static ParsedDocument testParsedDocument( } else { document.add(new StoredField(SourceFieldMapper.NAME, ref.bytes, ref.offset, ref.length)); } - return new ParsedDocument(versionField, seqID, id, routing, Arrays.asList(document), source, XContentType.JSON, mappingUpdate); + return new ParsedDocument(versionField, seqID, id, routing, Arrays.asList(document), source, MediaTypeRegistry.JSON, mappingUpdate); } public static CheckedBiFunction nestedParsedDocFactory() throws Exception { @@ -449,7 +449,7 @@ public static CheckedBiFunction ne source.endObject(); } source.endObject(); - return nestedMapper.parse(new SourceToParse("test", docId, BytesReference.bytes(source), XContentType.JSON)); + return nestedMapper.parse(new SourceToParse("test", docId, BytesReference.bytes(source), MediaTypeRegistry.JSON)); }; } @@ -478,7 +478,7 @@ public ParsedDocument newDeleteTombstoneDoc(String id) { null, Collections.singletonList(doc), new BytesArray("{}"), - XContentType.JSON, + MediaTypeRegistry.JSON, null ); } @@ -496,7 +496,16 @@ public ParsedDocument newNoopTombstoneDoc(String reason) { doc.add(versionField); BytesRef byteRef = new BytesRef(reason); doc.add(new StoredField(SourceFieldMapper.NAME, byteRef.bytes, byteRef.offset, byteRef.length)); - return new ParsedDocument(versionField, seqID, null, null, Collections.singletonList(doc), null, XContentType.JSON, null); + return new ParsedDocument( + versionField, + seqID, + null, + null, + Collections.singletonList(doc), + null, + MediaTypeRegistry.JSON, + null + ); } }; } diff --git a/test/framework/src/main/java/org/opensearch/index/mapper/MapperServiceTestCase.java b/test/framework/src/main/java/org/opensearch/index/mapper/MapperServiceTestCase.java index 9d39b488070be..2e01d73344043 100644 --- a/test/framework/src/main/java/org/opensearch/index/mapper/MapperServiceTestCase.java +++ b/test/framework/src/main/java/org/opensearch/index/mapper/MapperServiceTestCase.java @@ -44,10 +44,10 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.common.compress.CompressedXContent; import org.opensearch.common.settings.Settings; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.index.IndexSettings; import org.opensearch.index.analysis.AnalyzerScope; @@ -185,11 +185,11 @@ protected final SourceToParse source(CheckedConsumer extends diff --git a/test/framework/src/main/java/org/opensearch/test/AbstractBroadcastResponseTestCase.java b/test/framework/src/main/java/org/opensearch/test/AbstractBroadcastResponseTestCase.java index 1ecec0b9c9552..575765668abce 100644 --- a/test/framework/src/main/java/org/opensearch/test/AbstractBroadcastResponseTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/AbstractBroadcastResponseTestCase.java @@ -37,6 +37,7 @@ import org.opensearch.action.support.broadcast.BroadcastResponse; import org.opensearch.core.common.Strings; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -150,7 +151,7 @@ public void testFailuresDeduplication() throws IOException { public void testToXContent() { T response = createTestInstance(10, 10, 0, null); - String output = Strings.toString(XContentType.JSON, response); + String output = Strings.toString(MediaTypeRegistry.JSON, response); assertEquals("{\"_shards\":{\"total\":10,\"successful\":10,\"failed\":0}}", output); } } diff --git a/test/framework/src/main/java/org/opensearch/test/AbstractQueryTestCase.java b/test/framework/src/main/java/org/opensearch/test/AbstractQueryTestCase.java index aa43dac288cbd..3de1287ae2f10 100644 --- a/test/framework/src/main/java/org/opensearch/test/AbstractQueryTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/AbstractQueryTestCase.java @@ -51,12 +51,13 @@ import org.opensearch.core.common.io.stream.Writeable.Reader; import org.opensearch.common.unit.Fuzziness; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentGenerator; -import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParseException; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.common.xcontent.XContentType; @@ -262,7 +263,7 @@ static List> alterateQueries(Set queries, Set builder) throws IOException { - BytesReference bytes = XContentHelper.toXContent(builder, XContentType.JSON, false); + BytesReference bytes = org.opensearch.core.xcontent.XContentHelper.toXContent(builder, MediaTypeRegistry.JSON, false); return parseQuery(createParser(JsonXContent.jsonXContent, bytes)); } @@ -633,11 +634,11 @@ public QB mutateInstance(QB instance) throws IOException { public void testValidOutput() throws IOException { for (int runs = 0; runs < NUMBER_OF_TESTQUERIES; runs++) { QB testQuery = createTestQueryBuilder(); - XContentType xContentType = XContentType.JSON; - String toString = Strings.toString(XContentType.JSON, testQuery); - assertParsedQuery(createParser(xContentType.xContent(), toString), testQuery); - BytesReference bytes = XContentHelper.toXContent(testQuery, xContentType, false); - assertParsedQuery(createParser(xContentType.xContent(), bytes), testQuery); + MediaType mediaType = MediaTypeRegistry.JSON; + String toString = Strings.toString(MediaTypeRegistry.JSON, testQuery); + assertParsedQuery(createParser(mediaType.xContent(), toString), testQuery); + BytesReference bytes = org.opensearch.core.xcontent.XContentHelper.toXContent(testQuery, mediaType, false); + assertParsedQuery(createParser(mediaType.xContent(), bytes), testQuery); } } diff --git a/test/framework/src/main/java/org/opensearch/test/AbstractSerializingTestCase.java b/test/framework/src/main/java/org/opensearch/test/AbstractSerializingTestCase.java index f3496aabcb292..9eb7e164e41ec 100644 --- a/test/framework/src/main/java/org/opensearch/test/AbstractSerializingTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/AbstractSerializingTestCase.java @@ -34,6 +34,7 @@ import org.opensearch.core.common.io.stream.Writeable; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -75,7 +76,7 @@ public final void testFromXContent() throws IOException { * Override this method if the random instance that you build * should be aware of the {@link XContentType} used in the test. */ - protected T createXContextTestInstance(XContentType xContentType) { + protected T createXContextTestInstance(final MediaType mediaType) { return createTestInstance(); } diff --git a/test/framework/src/main/java/org/opensearch/test/AbstractXContentTestCase.java b/test/framework/src/main/java/org/opensearch/test/AbstractXContentTestCase.java index 00a20d4ff5b9c..01e96a345b32f 100644 --- a/test/framework/src/main/java/org/opensearch/test/AbstractXContentTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/AbstractXContentTestCase.java @@ -35,14 +35,15 @@ import org.opensearch.common.CheckedBiConsumer; import org.opensearch.common.CheckedBiFunction; import org.opensearch.common.CheckedFunction; +import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.common.Strings; +import org.opensearch.core.xcontent.MediaType; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContent; import org.opensearch.core.xcontent.XContentBuilder; -import org.opensearch.common.xcontent.XContentHelper; +import org.opensearch.core.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import java.io.IOException; import java.util.function.BiConsumer; @@ -93,7 +94,7 @@ public static XContentTester xContentTester( public static XContentTester xContentTester( CheckedBiFunction createParser, - Function instanceSupplier, + Function instanceSupplier, ToXContent.Params toXContentParams, CheckedFunction fromXContent ) { @@ -110,8 +111,8 @@ public static XContentTester xContentTester( */ public static class XContentTester { private final CheckedBiFunction createParser; - private final Function instanceSupplier; - private final CheckedBiFunction toXContent; + private final Function instanceSupplier; + private final CheckedBiFunction toXContent; private final CheckedFunction fromXContent; private int numberOfTestRuns = NUMBER_OF_TEST_RUNS; @@ -127,8 +128,8 @@ public static class XContentTester { private XContentTester( CheckedBiFunction createParser, - Function instanceSupplier, - CheckedBiFunction toXContent, + Function instanceSupplier, + CheckedBiFunction toXContent, CheckedFunction fromXContent ) { this.createParser = createParser; @@ -291,7 +292,7 @@ protected ToXContent.Params getToXContentParams() { static BytesReference insertRandomFieldsAndShuffle( BytesReference xContent, - XContentType xContentType, + MediaType mediaType, boolean supportsUnknownFields, String[] shuffleFieldsExceptions, Predicate randomFieldsExcludeFilter, @@ -300,11 +301,11 @@ static BytesReference insertRandomFieldsAndShuffle( BytesReference withRandomFields; if (supportsUnknownFields) { // add a few random fields to check that the parser is lenient on new fields - withRandomFields = XContentTestUtils.insertRandomFields(xContentType, xContent, randomFieldsExcludeFilter, random()); + withRandomFields = XContentTestUtils.insertRandomFields(mediaType, xContent, randomFieldsExcludeFilter, random()); } else { withRandomFields = xContent; } - XContentParser parserWithRandonFields = createParserFunction.apply(xContentType.xContent(), withRandomFields); + XContentParser parserWithRandonFields = createParserFunction.apply(mediaType.xContent(), withRandomFields); return BytesReference.bytes(shuffleXContent(parserWithRandonFields, false, shuffleFieldsExceptions)); } diff --git a/test/framework/src/main/java/org/opensearch/test/InternalAggregationTestCase.java b/test/framework/src/main/java/org/opensearch/test/InternalAggregationTestCase.java index a9e7b7d500cf1..56aa05b5a261f 100644 --- a/test/framework/src/main/java/org/opensearch/test/InternalAggregationTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/InternalAggregationTestCase.java @@ -175,7 +175,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.singletonMap; -import static org.opensearch.common.xcontent.XContentHelper.toXContent; +import static org.opensearch.core.xcontent.XContentHelper.toXContent; import static org.opensearch.search.aggregations.InternalMultiBucketAggregation.countInnerBucket; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasSize; diff --git a/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java b/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java index 0d81008686093..58c71b1c792df 100644 --- a/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java @@ -118,6 +118,7 @@ import org.opensearch.common.util.io.IOUtils; import org.opensearch.core.common.Strings; import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContentBuilder; @@ -1405,7 +1406,7 @@ protected final IndexResponse index(String index, String type, String id, Object */ @Deprecated protected final IndexResponse index(String index, String type, String id, String source) { - return client().prepareIndex(index).setId(id).setSource(source, XContentType.JSON).execute().actionGet(); + return client().prepareIndex(index).setId(id).setSource(source, MediaTypeRegistry.JSON).execute().actionGet(); } /** @@ -1577,7 +1578,7 @@ public void indexRandom(boolean forceRefresh, boolean dummyDocuments, boolean ma String index = RandomPicks.randomFrom(random, indices); bogusIds.add(Arrays.asList(index, id)); // We configure a routing key in case the mapping requires it - builders.add(client().prepareIndex().setIndex(index).setId(id).setSource("{}", XContentType.JSON).setRouting(id)); + builders.add(client().prepareIndex().setIndex(index).setId(id).setSource("{}", MediaTypeRegistry.JSON).setRouting(id)); } } Collections.shuffle(builders, random()); diff --git a/test/framework/src/main/java/org/opensearch/test/OpenSearchTestCase.java b/test/framework/src/main/java/org/opensearch/test/OpenSearchTestCase.java index f0453ab11f2ac..e15ce3530cde9 100644 --- a/test/framework/src/main/java/org/opensearch/test/OpenSearchTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/OpenSearchTestCase.java @@ -95,7 +95,6 @@ import org.opensearch.common.util.concurrent.ThreadContext; import org.opensearch.common.util.set.Sets; import org.opensearch.common.xcontent.LoggingDeprecationHandler; -import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.common.xcontent.XContentType; import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.MediaType; @@ -103,6 +102,7 @@ import org.opensearch.core.xcontent.ToXContent; import org.opensearch.core.xcontent.XContent; import org.opensearch.core.xcontent.XContentBuilder; +import org.opensearch.core.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; import org.opensearch.core.xcontent.XContentParser.Token; import org.opensearch.env.Environment; @@ -364,7 +364,7 @@ public static void setContentType() throws Exception { @AfterClass public static void restoreContentType() { Requests.CONTENT_TYPE = XContentType.SMILE; - Requests.INDEX_CONTENT_TYPE = XContentType.JSON; + Requests.INDEX_CONTENT_TYPE = MediaTypeRegistry.JSON; } @BeforeClass @@ -1311,7 +1311,7 @@ protected final BytesReference toShuffledXContent( boolean humanReadable, String... exceptFieldNames ) throws IOException { - BytesReference bytes = XContentHelper.toXContent(toXContent, mediaType, params, humanReadable); + BytesReference bytes = org.opensearch.core.xcontent.XContentHelper.toXContent(toXContent, mediaType, params, humanReadable); try (XContentParser parser = createParser(mediaType.xContent(), bytes)) { try (XContentBuilder builder = shuffleXContent(parser, rarely(), exceptFieldNames)) { return BytesReference.bytes(builder); diff --git a/test/framework/src/main/java/org/opensearch/test/RandomObjects.java b/test/framework/src/main/java/org/opensearch/test/RandomObjects.java index 3711e39720835..a8704fa5b6051 100644 --- a/test/framework/src/main/java/org/opensearch/test/RandomObjects.java +++ b/test/framework/src/main/java/org/opensearch/test/RandomObjects.java @@ -156,7 +156,7 @@ private static List randomStoredFieldValues(Random random, int numValues */ public static Object getExpectedParsedValue(MediaType mediaType, Object value) { if (value instanceof BytesArray) { - if (mediaType == XContentType.JSON) { + if (mediaType == MediaTypeRegistry.JSON) { // JSON writes base64 format return Base64.getEncoder().encodeToString(((BytesArray) value).toBytesRef().bytes); } @@ -194,8 +194,8 @@ public static BytesReference randomSource(Random random) { * * @param random Random generator */ - public static BytesReference randomSource(Random random, XContentType xContentType) { - return randomSource(random, xContentType, 1); + public static BytesReference randomSource(Random random, final MediaType mediaType) { + return randomSource(random, mediaType, 1); } /** @@ -204,8 +204,8 @@ public static BytesReference randomSource(Random random, XContentType xContentTy * * @param random Random generator */ - public static BytesReference randomSource(Random random, XContentType xContentType, int minNumFields) { - try (XContentBuilder builder = MediaTypeRegistry.contentBuilder(xContentType)) { + public static BytesReference randomSource(Random random, final MediaType mediaType, int minNumFields) { + try (XContentBuilder builder = mediaType.contentBuilder()) { builder.startObject(); addFields(random, builder, minNumFields, 0); builder.endObject(); diff --git a/test/framework/src/main/java/org/opensearch/test/hamcrest/OpenSearchAssertions.java b/test/framework/src/main/java/org/opensearch/test/hamcrest/OpenSearchAssertions.java index 230cc50f427f9..808d9766dc49b 100644 --- a/test/framework/src/main/java/org/opensearch/test/hamcrest/OpenSearchAssertions.java +++ b/test/framework/src/main/java/org/opensearch/test/hamcrest/OpenSearchAssertions.java @@ -687,8 +687,7 @@ public static void assertFileNotExists(Path file) { * 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, MediaType xContentType) - throws IOException { + public static void assertToXContentEquivalent(BytesReference expected, BytesReference actual, MediaType mediaType) 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) @@ -696,12 +695,12 @@ public static void assertToXContentEquivalent(BytesReference expected, BytesRefe Map actualMap = null; Map expectedMap = null; try ( - XContentParser actualParser = xContentType.xContent() + XContentParser actualParser = mediaType.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, actual.streamInput()) ) { actualMap = actualParser.map(); try ( - XContentParser expectedParser = xContentType.xContent() + XContentParser expectedParser = mediaType.xContent() .createParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, expected.streamInput()) ) { expectedMap = expectedParser.map(); diff --git a/test/framework/src/main/java/org/opensearch/test/rest/OpenSearchRestTestCase.java b/test/framework/src/main/java/org/opensearch/test/rest/OpenSearchRestTestCase.java index 762f43adbb3db..7a6400518fa5f 100644 --- a/test/framework/src/main/java/org/opensearch/test/rest/OpenSearchRestTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/rest/OpenSearchRestTestCase.java @@ -65,13 +65,13 @@ import org.opensearch.common.unit.TimeValue; import org.opensearch.common.util.concurrent.ThreadContext; import org.opensearch.common.xcontent.XContentHelper; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import org.opensearch.common.xcontent.support.XContentMapValues; import org.opensearch.common.util.io.IOUtils; import org.opensearch.core.common.Strings; import org.opensearch.core.xcontent.DeprecationHandler; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.core.xcontent.XContentParser; @@ -607,7 +607,7 @@ protected static void wipeAllIndices() throws IOException { deleteRequest.setOptions(allowSystemIndexAccessWarningOptions); final Response response = adminClient().performRequest(deleteRequest); try (InputStream is = response.getEntity().getContent()) { - assertTrue((boolean) XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true).get("acknowledged")); + assertTrue((boolean) XContentHelper.convertToMap(MediaTypeRegistry.JSON.xContent(), is, true).get("acknowledged")); } } catch (ResponseException e) { // 404 here just means we had no indexes @@ -974,7 +974,7 @@ protected static void createIndex(String name, Settings settings, String mapping protected static void createIndex(String name, Settings settings, String mapping, String aliases) throws IOException { Request request = new Request("PUT", "/" + name); - String entity = "{\"settings\": " + Strings.toString(XContentType.JSON, settings); + String entity = "{\"settings\": " + Strings.toString(MediaTypeRegistry.JSON, settings); if (mapping != null) { entity += ",\"mappings\" : {" + mapping + "}"; } @@ -1000,7 +1000,7 @@ protected static void updateIndexSettings(String index, Settings.Builder setting private static void updateIndexSettings(String index, Settings settings) throws IOException { Request request = new Request("PUT", "/" + index + "/_settings"); - request.setJsonEntity(Strings.toString(XContentType.JSON, settings)); + request.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, settings)); client().performRequest(request); } @@ -1021,7 +1021,7 @@ protected static Map getIndexSettings(String index) throws IOExc request.addParameter("flat_settings", "true"); Response response = client().performRequest(request); try (InputStream is = response.getEntity().getContent()) { - return XContentHelper.convertToMap(XContentType.JSON.xContent(), is, true); + return XContentHelper.convertToMap(MediaTypeRegistry.JSON.xContent(), is, true); } } @@ -1088,7 +1088,7 @@ protected static Map responseAsMap(Response response) throws IOE protected static void registerRepository(String repository, String type, boolean verify, Settings settings) throws IOException { final Request request = new Request(HttpPut.METHOD_NAME, "_snapshot/" + repository); request.addParameter("verify", Boolean.toString(verify)); - request.setJsonEntity(Strings.toString(XContentType.JSON, new PutRepositoryRequest(repository).type(type).settings(settings))); + request.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, new PutRepositoryRequest(repository).type(type).settings(settings))); final Response response = client().performRequest(request); assertAcked("Failed to create repository [" + repository + "] of type [" + type + "]: " + response, response); diff --git a/test/framework/src/main/java/org/opensearch/test/rest/yaml/ClientYamlTestExecutionContext.java b/test/framework/src/main/java/org/opensearch/test/rest/yaml/ClientYamlTestExecutionContext.java index 3045b3fe66edc..f7585ae6f5799 100644 --- a/test/framework/src/main/java/org/opensearch/test/rest/yaml/ClientYamlTestExecutionContext.java +++ b/test/framework/src/main/java/org/opensearch/test/rest/yaml/ClientYamlTestExecutionContext.java @@ -64,7 +64,7 @@ public class ClientYamlTestExecutionContext { private static final Logger logger = LogManager.getLogger(ClientYamlTestExecutionContext.class); - private static final XContentType[] STREAMING_CONTENT_TYPES = new XContentType[] { XContentType.JSON, XContentType.SMILE }; + private static final MediaType[] STREAMING_CONTENT_TYPES = new MediaType[] { MediaTypeRegistry.JSON, XContentType.SMILE }; private final Stash stash = new Stash(); private final ClientYamlTestClient clientYamlTestClient; @@ -168,7 +168,7 @@ private HttpEntity createEntity(List> bodies, Map headers, XContentType[] supportedContentTypes) { + private MediaType getContentType(Map headers, MediaType[] supportedContentTypes) { MediaType mediaType = null; String contentType = headers.get("Content-Type"); if (contentType != null) { @@ -180,7 +180,7 @@ private MediaType getContentType(Map headers, XContentType[] sup if (randomizeContentType) { return RandomizedTest.randomFrom(supportedContentTypes); } - return XContentType.JSON; + return MediaTypeRegistry.JSON; } private BytesRef bodyAsBytesRef(Map bodyAsMap, MediaType mediaType) throws IOException { diff --git a/test/framework/src/main/java/org/opensearch/test/rest/yaml/ClientYamlTestResponse.java b/test/framework/src/main/java/org/opensearch/test/rest/yaml/ClientYamlTestResponse.java index bba72c7ad758e..24506f207f219 100644 --- a/test/framework/src/main/java/org/opensearch/test/rest/yaml/ClientYamlTestResponse.java +++ b/test/framework/src/main/java/org/opensearch/test/rest/yaml/ClientYamlTestResponse.java @@ -38,6 +38,7 @@ import org.opensearch.core.common.bytes.BytesArray; import org.opensearch.common.xcontent.LoggingDeprecationHandler; import org.opensearch.core.xcontent.MediaType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; @@ -124,7 +125,7 @@ public Object getBody() throws IOException { public String getBodyAsString() { if (bodyAsString == null && body != null) { // content-type null means that text was returned - if (bodyContentType == null || bodyContentType == XContentType.JSON || bodyContentType == XContentType.YAML) { + if (bodyContentType == null || bodyContentType == MediaTypeRegistry.JSON || bodyContentType == XContentType.YAML) { bodyAsString = new String(body, StandardCharsets.UTF_8); } else { // if the body is in a binary format and gets requested as a string (e.g. to log a test failure), we convert it to json diff --git a/test/framework/src/main/java/org/opensearch/test/rest/yaml/OpenSearchClientYamlSuiteTestCase.java b/test/framework/src/main/java/org/opensearch/test/rest/yaml/OpenSearchClientYamlSuiteTestCase.java index 14c0f2a5a9206..094af1efa208a 100644 --- a/test/framework/src/main/java/org/opensearch/test/rest/yaml/OpenSearchClientYamlSuiteTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/rest/yaml/OpenSearchClientYamlSuiteTestCase.java @@ -49,7 +49,7 @@ import org.opensearch.core.common.Strings; import org.opensearch.common.collect.Tuple; import org.opensearch.common.io.PathUtils; -import org.opensearch.common.xcontent.XContentType; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.common.util.io.IOUtils; import org.opensearch.test.rest.OpenSearchRestTestCase; @@ -451,7 +451,7 @@ private void executeSection(ExecutableSection executableSection) { // Dump the stash on failure. Instead of dumping it in true json we escape `\n`s so stack traces are easier to read logger.info( "Stash dump on test failure [{}]", - Strings.toString(XContentType.JSON, restTestExecutionContext.stash(), true, true) + Strings.toString(MediaTypeRegistry.JSON, restTestExecutionContext.stash(), true, true) .replace("\\n", "\n") .replace("\\r", "\r") .replace("\\t", "\t") diff --git a/test/framework/src/test/java/org/opensearch/test/AbstractXContentTestCaseTests.java b/test/framework/src/test/java/org/opensearch/test/AbstractXContentTestCaseTests.java index f47e0f9ea75b5..d880967c4452a 100644 --- a/test/framework/src/test/java/org/opensearch/test/AbstractXContentTestCaseTests.java +++ b/test/framework/src/test/java/org/opensearch/test/AbstractXContentTestCaseTests.java @@ -35,10 +35,10 @@ import com.carrotsearch.randomizedtesting.RandomizedContext; import org.opensearch.core.common.bytes.BytesReference; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import java.util.Map; @@ -59,14 +59,14 @@ public void testInsertRandomFieldsAndShuffle() throws Exception { 1, () -> AbstractXContentTestCase.insertRandomFieldsAndShuffle( BytesReference.bytes(builder), - XContentType.JSON, + MediaTypeRegistry.JSON, true, new String[] {}, null, this::createParser ) ); - try (XContentParser parser = createParser(XContentType.JSON.xContent(), insertRandomFieldsAndShuffle)) { + try (XContentParser parser = createParser(MediaTypeRegistry.JSON.xContent(), insertRandomFieldsAndShuffle)) { Map mapOrdered = parser.mapOrdered(); assertThat(mapOrdered.size(), equalTo(2)); assertThat(mapOrdered.keySet().iterator().next(), not(equalTo("field"))); diff --git a/test/framework/src/test/java/org/opensearch/test/XContentTestUtilsTests.java b/test/framework/src/test/java/org/opensearch/test/XContentTestUtilsTests.java index 4e1cb8debb4fc..cc5c9230e6f39 100644 --- a/test/framework/src/test/java/org/opensearch/test/XContentTestUtilsTests.java +++ b/test/framework/src/test/java/org/opensearch/test/XContentTestUtilsTests.java @@ -34,12 +34,12 @@ import org.opensearch.core.common.bytes.BytesReference; import org.opensearch.core.xcontent.DeprecationHandler; +import org.opensearch.core.xcontent.MediaTypeRegistry; import org.opensearch.core.xcontent.NamedXContentRegistry; import org.opensearch.core.xcontent.XContentBuilder; import org.opensearch.common.xcontent.XContentFactory; import org.opensearch.common.xcontent.XContentHelper; import org.opensearch.core.xcontent.XContentParser; -import org.opensearch.common.xcontent.XContentType; import org.opensearch.common.xcontent.json.JsonXContent; import java.io.IOException; @@ -111,28 +111,28 @@ public void testInsertIntoXContent() throws IOException { builder.startObject(); builder.endObject(); builder = XContentTestUtils.insertIntoXContent( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), BytesReference.bytes(builder), Collections.singletonList(""), () -> "inn.er1", () -> new HashMap<>() ); builder = XContentTestUtils.insertIntoXContent( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), BytesReference.bytes(builder), Collections.singletonList(""), () -> "field1", () -> "value1" ); builder = XContentTestUtils.insertIntoXContent( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), BytesReference.bytes(builder), Collections.singletonList("inn\\.er1"), () -> "inner2", () -> new HashMap<>() ); builder = XContentTestUtils.insertIntoXContent( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), BytesReference.bytes(builder), Collections.singletonList("inn\\.er1"), () -> "field2", @@ -194,7 +194,7 @@ public void testInsertRandomXContent() throws IOException { try ( XContentParser parser = createParser( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), insertRandomFields(builder.contentType(), BytesReference.bytes(builder), null, random()) ) ) { @@ -212,7 +212,7 @@ public void testInsertRandomXContent() throws IOException { Predicate pathsToExclude = path -> path.endsWith("foo1"); try ( XContentParser parser = createParser( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), insertRandomFields(builder.contentType(), BytesReference.bytes(builder), pathsToExclude, random()) ) ) { @@ -230,7 +230,7 @@ public void testInsertRandomXContent() throws IOException { pathsToExclude = path -> path.contains("foo1"); try ( XContentParser parser = createParser( - XContentType.JSON.xContent(), + MediaTypeRegistry.JSON.xContent(), insertRandomFields(builder.contentType(), BytesReference.bytes(builder), pathsToExclude, random()) ) ) {