From d79340f2d1ae7381800244578ecc4d2d58cf5412 Mon Sep 17 00:00:00 2001 From: Rabi Panda Date: Wed, 16 Nov 2022 11:30:25 -0800 Subject: [PATCH] Call 'toArray()' with an empty array instead of a pre-sized array (#5277) Calls to `Collection.toArray()` is not consistent and in many places and use a pre-sized array parameter. This change makes a consistent use of the `toArray(new T[0])`. The empty array usage is considered faster, safer and cleaner than the sized based array approach. Signed-off-by: Rabi Panda --- .../gradle/DistributionDownloadPlugin.java | 2 +- .../opensearch/client/core/CountResponse.java | 2 +- .../indices/PutIndexTemplateRequest.java | 2 +- .../client/RestHighLevelClientExtTests.java | 2 +- .../plugins/InstallPluginCommand.java | 2 +- .../plugins/RemovePluginCommand.java | 2 +- .../common/collect/IteratorsTests.java | 2 +- .../java/org/opensearch/core/ParseField.java | 4 ++-- .../org/opensearch/core/common/Strings.java | 2 +- .../core/common/bytes/BytesReference.java | 2 +- .../core/xcontent/filtering/FilterPath.java | 2 +- .../filtering/FilterPathBasedFilter.java | 2 +- .../join/query/ChildQuerySearchIT.java | 2 +- .../rankeval/TransportRankEvalAction.java | 9 ++----- .../AbstractAsyncBulkByScrollAction.java | 2 +- .../reindex/DeleteByQueryBasicTests.java | 2 +- .../index/reindex/ReindexBasicTests.java | 2 +- .../reindex/UpdateByQueryBasicTests.java | 2 +- .../highlight/AnnotatedPassageFormatter.java | 2 +- .../opensearch/action/IndicesRequestIT.java | 2 +- .../action/admin/indices/get/GetIndexIT.java | 4 ++-- .../org/opensearch/recovery/RelocationIT.java | 2 +- .../aggregations/bucket/GeoDistanceIT.java | 2 +- .../aggregations/bucket/LongTermsIT.java | 2 +- .../aggregations/pipeline/MaxBucketIT.java | 16 ++++++------- .../aggregations/pipeline/MinBucketIT.java | 14 +++++------ .../search/basic/SearchWhileRelocatingIT.java | 2 +- .../search/morelikethis/MoreLikeThisIT.java | 2 +- .../SharedClusterSnapshotRestoreIT.java | 4 ++-- .../uhighlight/CustomFieldHighlighter.java | 2 +- .../restore/RestoreRemoteStoreRequest.java | 2 +- .../create/CreateSnapshotRequest.java | 2 +- .../restore/RestoreSnapshotRequest.java | 4 ++-- .../alias/TransportIndicesAliasesAction.java | 4 ++-- .../delete/TransportDeleteIndexAction.java | 2 +- .../admin/indices/segments/IndexSegments.java | 5 +--- .../indices/segments/PitSegmentsRequest.java | 2 +- .../TransportIndicesSegmentsAction.java | 2 +- .../segments/TransportPitSegmentsAction.java | 2 +- .../admin/indices/stats/CommonStatsFlags.java | 2 +- .../admin/indices/stats/IndexStats.java | 7 ++---- .../stats/TransportIndicesStatsAction.java | 8 +------ .../template/put/PutIndexTemplateRequest.java | 2 +- .../upgrade/get/IndexUpgradeStatus.java | 2 +- .../get/TransportUpgradeStatusAction.java | 2 +- .../upgrade/get/UpgradeStatusResponse.java | 2 +- .../opensearch/action/bulk/BulkResponse.java | 2 +- .../action/bulk/TransportBulkAction.java | 2 +- .../action/get/MultiGetRequest.java | 6 ++--- .../action/search/ClearScrollRequest.java | 2 +- .../action/search/DeletePitRequest.java | 2 +- .../opensearch/action/search/PitService.java | 2 +- .../search/SearchScrollAsyncAction.java | 2 +- .../action/support/ActionFilters.java | 2 +- .../support/broadcast/BroadcastResponse.java | 2 +- .../replication/ReplicationResponse.java | 2 +- .../metadata/IndexNameExpressionResolver.java | 4 ++-- .../cluster/routing/RoutingNodes.java | 4 ++-- .../routing/allocation/AllocationService.java | 2 +- .../allocator/LocalShardsBalancer.java | 2 +- .../opensearch/common/blobstore/BlobPath.java | 2 +- .../common/geo/GeoPolygonDecomposer.java | 2 +- .../geo/builders/LineStringBuilder.java | 4 ++-- .../geo/builders/MultiLineStringBuilder.java | 2 +- .../common/geo/builders/PolygonBuilder.java | 4 ++-- .../lucene/index/FilterableTermsEnum.java | 2 +- .../common/lucene/search/XMoreLikeThis.java | 2 +- .../common/network/NetworkService.java | 4 ++-- .../common/network/NetworkUtils.java | 6 ++--- .../opensearch/common/settings/Settings.java | 2 +- .../common/settings/SettingsFilter.java | 2 +- ...ioritizedOpenSearchThreadPoolExecutor.java | 2 +- .../org/opensearch/env/NodeEnvironment.java | 2 +- .../gateway/LocalAllocateDangledIndices.java | 5 +--- .../index/analysis/AnalyzerComponents.java | 4 ++-- .../analysis/CustomNormalizerProvider.java | 4 ++-- .../org/opensearch/index/engine/Engine.java | 2 +- .../opensearch/index/mapper/ParseContext.java | 2 +- .../index/query/IdsQueryBuilder.java | 2 +- .../index/query/MoreLikeThisQueryBuilder.java | 18 +++++++------- .../query/VectorGeoShapeQueryProcessor.java | 6 +---- .../FunctionScoreQueryBuilder.java | 2 +- .../index/reindex/ReindexRequest.java | 2 +- .../index/shard/LocalShardSnapshot.java | 2 +- .../org/opensearch/monitor/fs/FsProbe.java | 2 +- .../monitor/jvm/DeadlockAnalyzer.java | 2 +- .../org/opensearch/monitor/jvm/JvmInfo.java | 2 +- .../document/RestTermVectorsAction.java | 2 +- .../action/search/RestGetAllPitsAction.java | 2 +- .../aggregations/MultiBucketCollector.java | 2 +- .../SignificantTextAggregationBuilder.java | 2 +- .../pipeline/BucketMetricsParser.java | 2 +- .../DerivativePipelineAggregationBuilder.java | 2 +- .../pipeline/MaxBucketPipelineAggregator.java | 2 +- .../MovAvgPipelineAggregationBuilder.java | 2 +- .../SerialDiffPipelineAggregationBuilder.java | 2 +- .../fetch/subphase/FetchSourceContext.java | 6 ++--- .../subphase/highlight/HighlightField.java | 2 +- .../search/sort/GeoDistanceSortBuilder.java | 6 ++--- .../opensearch/search/sort/SortBuilder.java | 5 +--- .../phrase/DirectCandidateGenerator.java | 2 +- .../phrase/NoisyChannelSpellChecker.java | 2 +- .../suggest/phrase/PhraseSuggester.java | 2 +- .../opensearch/snapshots/SnapshotInfo.java | 6 +---- .../node/tasks/TransportTasksActionTests.java | 2 +- .../ClusterSearchShardsResponseTests.java | 2 +- .../TransportRolloverActionTests.java | 2 +- .../stats/IndicesStatsResponseTests.java | 8 +------ .../action/bulk/BulkRequestModifierTests.java | 2 +- .../nodes/TransportNodesActionTests.java | 2 +- .../AbstractTermVectorsTestCase.java | 2 +- .../cluster/node/DiscoveryNodesTests.java | 4 ++-- .../allocation/FailedNodeRoutingTests.java | 2 +- .../cluster/serialization/DiffableTests.java | 5 +--- .../common/geo/GeoJsonShapeParserTests.java | 24 +++++++++---------- .../common/geo/GeoWKTShapeParserTests.java | 10 ++++---- .../support/XContentMapValuesTests.java | 4 ++-- .../opensearch/env/NodeEnvironmentTests.java | 2 +- .../query/MoreLikeThisQueryBuilderTests.java | 5 +--- .../index/query/RegexpQueryBuilderTests.java | 2 +- .../query/SimpleQueryStringBuilderTests.java | 2 +- .../index/query/TermsQueryBuilderTests.java | 2 +- .../seqno/LocalCheckpointTrackerTests.java | 2 +- .../index/translog/SnapshotMatchers.java | 2 +- ...ClusterStateServiceRandomUpdatesTests.java | 8 +++---- .../indices/store/IndicesStoreTests.java | 2 +- .../search/CreatePitSingleNodeTests.java | 2 +- .../support/AggregationPathTests.java | 2 +- .../highlight/HighlightBuilderTests.java | 2 +- .../search/sort/FieldSortBuilderTests.java | 2 +- .../sort/GeoDistanceSortBuilderTests.java | 2 +- .../search/sort/SortBuilderTests.java | 2 +- .../hamcrest/OpenSearchGeoAssertions.java | 2 +- .../UpdateThreadPoolSettingsTests.java | 2 +- .../ClusterStateCreationUtils.java | 2 +- ...earchBlobStoreRepositoryIntegTestCase.java | 4 ++-- .../opensearch/test/InternalTestCluster.java | 2 +- .../test/OpenSearchIntegTestCase.java | 2 +- .../opensearch/test/XContentTestUtils.java | 2 +- .../test/hamcrest/OpenSearchAssertions.java | 5 +--- .../test/rest/OpenSearchRestTestCase.java | 4 ++-- .../test/transport/MockTransportService.java | 2 +- 142 files changed, 206 insertions(+), 254 deletions(-) diff --git a/buildSrc/src/main/java/org/opensearch/gradle/DistributionDownloadPlugin.java b/buildSrc/src/main/java/org/opensearch/gradle/DistributionDownloadPlugin.java index 7b6aa6774b401..0732845f329e0 100644 --- a/buildSrc/src/main/java/org/opensearch/gradle/DistributionDownloadPlugin.java +++ b/buildSrc/src/main/java/org/opensearch/gradle/DistributionDownloadPlugin.java @@ -176,7 +176,7 @@ private static void addIvyRepo(Project project, String name, String url, String project.getRepositories().exclusiveContent(exclusiveContentRepository -> { exclusiveContentRepository.filter(config -> config.includeGroup(group)); - exclusiveContentRepository.forRepositories(repos.toArray(new IvyArtifactRepository[repos.size()])); + exclusiveContentRepository.forRepositories(repos.toArray(new IvyArtifactRepository[0])); }); } diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/CountResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/CountResponse.java index eeb99cbca2b5f..5540c3c284271 100644 --- a/client/rest-high-level/src/main/java/org/opensearch/client/core/CountResponse.java +++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/CountResponse.java @@ -233,7 +233,7 @@ static ShardStats fromXContent(XContentParser parser) throws IOException { parser.skipChildren(); } } - return new ShardStats(successfulShards, totalShards, skippedShards, failures.toArray(new ShardSearchFailure[failures.size()])); + return new ShardStats(successfulShards, totalShards, skippedShards, failures.toArray(new ShardSearchFailure[0])); } @Override 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 d090a469d2735..1c286577ae8c9 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 @@ -478,7 +478,7 @@ public PutIndexTemplateRequest alias(Alias alias) { @Override public String[] indices() { - return indexPatterns.toArray(new String[indexPatterns.size()]); + return indexPatterns.toArray(new String[0]); } @Override diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java index 7658aa3c2c765..6c4cdfa8dca92 100644 --- a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java +++ b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java @@ -153,7 +153,7 @@ static CustomResponseSection2 fromXContent(XContentParser parser) throws IOExcep values.add(parser.text()); } assertEquals(XContentParser.Token.END_ARRAY, parser.currentToken()); - CustomResponseSection2 responseSection2 = new CustomResponseSection2(values.toArray(new String[values.size()])); + CustomResponseSection2 responseSection2 = new CustomResponseSection2(values.toArray(new String[0])); assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); return responseSection2; } diff --git a/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/InstallPluginCommand.java b/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/InstallPluginCommand.java index 60141968be48e..24bbd35431451 100644 --- a/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/InstallPluginCommand.java +++ b/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/InstallPluginCommand.java @@ -1027,7 +1027,7 @@ private static void setFileAttributes(final Path path, final Set set = new HashSet<>(); Collections.addAll(set, deprecatedNames); - this.deprecatedNames = set.toArray(new String[set.size()]); + this.deprecatedNames = set.toArray(new String[0]); } Set allNames = new HashSet<>(); allNames.add(name); Collections.addAll(allNames, this.deprecatedNames); - this.allNames = allNames.toArray(new String[allNames.size()]); + this.allNames = allNames.toArray(new String[0]); } /** diff --git a/libs/core/src/main/java/org/opensearch/core/common/Strings.java b/libs/core/src/main/java/org/opensearch/core/common/Strings.java index 15c49d3a56c76..805be7648c810 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/Strings.java +++ b/libs/core/src/main/java/org/opensearch/core/common/Strings.java @@ -343,7 +343,7 @@ public static String[] toStringArray(final Collection collection) { if (collection == null) { return null; } - return collection.toArray(new String[collection.size()]); + return collection.toArray(new String[0]); } /** diff --git a/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesReference.java b/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesReference.java index 9bcdfffc65426..6b60e7448cd03 100644 --- a/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesReference.java +++ b/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesReference.java @@ -98,7 +98,7 @@ static ByteBuffer[] toByteBuffers(BytesReference reference) { while ((r = byteRefIterator.next()) != null) { buffers.add(ByteBuffer.wrap(r.bytes, r.offset, r.length)); } - return buffers.toArray(new ByteBuffer[buffers.size()]); + return buffers.toArray(new ByteBuffer[0]); } catch (IOException e) { // this is really an error since we don't do IO in our bytesreferences diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/filtering/FilterPath.java b/libs/core/src/main/java/org/opensearch/core/xcontent/filtering/FilterPath.java index 5ca5e4de04145..b8da9787165f8 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/filtering/FilterPath.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/filtering/FilterPath.java @@ -105,7 +105,7 @@ public static FilterPath[] compile(Set filters) { } } } - return paths.toArray(new FilterPath[paths.size()]); + return paths.toArray(new FilterPath[0]); } private static FilterPath parse(final String filter) { diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/filtering/FilterPathBasedFilter.java b/libs/core/src/main/java/org/opensearch/core/xcontent/filtering/FilterPathBasedFilter.java index fedfa154f33cb..3e6fbc29c53a5 100644 --- a/libs/core/src/main/java/org/opensearch/core/xcontent/filtering/FilterPathBasedFilter.java +++ b/libs/core/src/main/java/org/opensearch/core/xcontent/filtering/FilterPathBasedFilter.java @@ -100,7 +100,7 @@ private TokenFilter evaluate(String name, FilterPath[] filters) { } if ((nextFilters != null) && (nextFilters.isEmpty() == false)) { - return new FilterPathBasedFilter(nextFilters.toArray(new FilterPath[nextFilters.size()]), inclusive); + return new FilterPathBasedFilter(nextFilters.toArray(new FilterPath[0]), inclusive); } } return NO_MATCHING; diff --git a/modules/parent-join/src/internalClusterTest/java/org/opensearch/join/query/ChildQuerySearchIT.java b/modules/parent-join/src/internalClusterTest/java/org/opensearch/join/query/ChildQuerySearchIT.java index dee30fc7ab20a..99527c3273c4b 100644 --- a/modules/parent-join/src/internalClusterTest/java/org/opensearch/join/query/ChildQuerySearchIT.java +++ b/modules/parent-join/src/internalClusterTest/java/org/opensearch/join/query/ChildQuerySearchIT.java @@ -327,7 +327,7 @@ public void testHasParentFilter() throws Exception { } assertThat(parentToChildren.get(previousParentId).add(childId), is(true)); } - indexRandom(true, builders.toArray(new IndexRequestBuilder[builders.size()])); + indexRandom(true, builders.toArray(new IndexRequestBuilder[0])); assertThat(parentToChildren.isEmpty(), equalTo(false)); for (Map.Entry> parentToChildrenEntry : parentToChildren.entrySet()) { 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 76197561fdb5e..8e72c6ef06849 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 @@ -148,7 +148,7 @@ protected void doExecute(Task task, RankEvalRequest request, ActionListener indexingFailures, List search return; } RefreshRequest refresh = new RefreshRequest(); - refresh.indices(destinationIndices.toArray(new String[destinationIndices.size()])); + refresh.indices(destinationIndices.toArray(new String[0])); logger.debug("[{}]: refreshing", task.getId()); client.admin().indices().refresh(refresh, new ActionListener() { @Override diff --git a/modules/reindex/src/test/java/org/opensearch/index/reindex/DeleteByQueryBasicTests.java b/modules/reindex/src/test/java/org/opensearch/index/reindex/DeleteByQueryBasicTests.java index baf3c83bd0050..6874f96628761 100644 --- a/modules/reindex/src/test/java/org/opensearch/index/reindex/DeleteByQueryBasicTests.java +++ b/modules/reindex/src/test/java/org/opensearch/index/reindex/DeleteByQueryBasicTests.java @@ -362,7 +362,7 @@ public void testMultipleSources() throws Exception { int slices = randomSlices(1, 10); int expectedSlices = expectedSliceStatuses(slices, docs.keySet()); - String[] sourceIndexNames = docs.keySet().toArray(new String[docs.size()]); + String[] sourceIndexNames = docs.keySet().toArray(new String[0]); assertThat( deleteByQuery().source(sourceIndexNames).filter(QueryBuilders.matchAllQuery()).refresh(true).setSlices(slices).get(), diff --git a/modules/reindex/src/test/java/org/opensearch/index/reindex/ReindexBasicTests.java b/modules/reindex/src/test/java/org/opensearch/index/reindex/ReindexBasicTests.java index 0c660e5df9682..24adba16d0bad 100644 --- a/modules/reindex/src/test/java/org/opensearch/index/reindex/ReindexBasicTests.java +++ b/modules/reindex/src/test/java/org/opensearch/index/reindex/ReindexBasicTests.java @@ -161,7 +161,7 @@ public void testMultipleSources() throws Exception { int slices = randomSlices(1, 10); int expectedSlices = expectedSliceStatuses(slices, docs.keySet()); - String[] sourceIndexNames = docs.keySet().toArray(new String[docs.size()]); + String[] sourceIndexNames = docs.keySet().toArray(new String[0]); ReindexRequestBuilder request = reindex().source(sourceIndexNames).destination("dest").refresh(true).setSlices(slices); BulkByScrollResponse response = request.get(); diff --git a/modules/reindex/src/test/java/org/opensearch/index/reindex/UpdateByQueryBasicTests.java b/modules/reindex/src/test/java/org/opensearch/index/reindex/UpdateByQueryBasicTests.java index 4f48b99dccdd4..987fab954a8d0 100644 --- a/modules/reindex/src/test/java/org/opensearch/index/reindex/UpdateByQueryBasicTests.java +++ b/modules/reindex/src/test/java/org/opensearch/index/reindex/UpdateByQueryBasicTests.java @@ -151,7 +151,7 @@ public void testMultipleSources() throws Exception { int slices = randomSlices(1, 10); int expectedSlices = expectedSliceStatuses(slices, docs.keySet()); - String[] sourceIndexNames = docs.keySet().toArray(new String[docs.size()]); + String[] sourceIndexNames = docs.keySet().toArray(new String[0]); BulkByScrollResponse response = updateByQuery().source(sourceIndexNames).refresh(true).setSlices(slices).get(); assertThat(response, matcher().updated(allDocs.size()).slices(hasSize(expectedSlices))); diff --git a/plugins/mapper-annotated-text/src/main/java/org/opensearch/search/fetch/subphase/highlight/AnnotatedPassageFormatter.java b/plugins/mapper-annotated-text/src/main/java/org/opensearch/search/fetch/subphase/highlight/AnnotatedPassageFormatter.java index 8a94fea0ebbd4..48a41dd4afaf3 100644 --- a/plugins/mapper-annotated-text/src/main/java/org/opensearch/search/fetch/subphase/highlight/AnnotatedPassageFormatter.java +++ b/plugins/mapper-annotated-text/src/main/java/org/opensearch/search/fetch/subphase/highlight/AnnotatedPassageFormatter.java @@ -237,7 +237,7 @@ public AnnotationToken[] getIntersectingAnnotations(int start, int end) { // add 1 for the fieldvalue separator character fieldValueOffset += fieldValueAnnotations.textMinusMarkup.length() + 1; } - return intersectingAnnotations.toArray(new AnnotationToken[intersectingAnnotations.size()]); + return intersectingAnnotations.toArray(new AnnotationToken[0]); } private void append(StringBuilder dest, String content, int start, int end) { diff --git a/server/src/internalClusterTest/java/org/opensearch/action/IndicesRequestIT.java b/server/src/internalClusterTest/java/org/opensearch/action/IndicesRequestIT.java index 89249dd76caac..927a79d4884ef 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/IndicesRequestIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/IndicesRequestIT.java @@ -739,7 +739,7 @@ private String[] randomUniqueIndices() { while (uniqueIndices.size() < count) { uniqueIndices.add(randomFrom(this.indices)); } - return uniqueIndices.toArray(new String[uniqueIndices.size()]); + return uniqueIndices.toArray(new String[0]); } private static void assertAllRequestsHaveBeenConsumed() { diff --git a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/get/GetIndexIT.java b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/get/GetIndexIT.java index e5db895e7dfa9..ac92c389e9a71 100644 --- a/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/get/GetIndexIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/action/admin/indices/get/GetIndexIT.java @@ -162,7 +162,7 @@ public void testSimpleMixedFeatures() { } GetIndexResponse response = runWithRandomFeatureMethod( client().admin().indices().prepareGetIndex().addIndices("idx"), - features.toArray(new Feature[features.size()]) + features.toArray(new Feature[0]) ); String[] indices = response.indices(); assertThat(indices, notNullValue()); @@ -193,7 +193,7 @@ public void testEmptyMixedFeatures() { } GetIndexResponse response = runWithRandomFeatureMethod( client().admin().indices().prepareGetIndex().addIndices("empty_idx"), - features.toArray(new Feature[features.size()]) + features.toArray(new Feature[0]) ); String[] indices = response.indices(); assertThat(indices, notNullValue()); diff --git a/server/src/internalClusterTest/java/org/opensearch/recovery/RelocationIT.java b/server/src/internalClusterTest/java/org/opensearch/recovery/RelocationIT.java index 601774f49e3ef..9f398d84a8439 100644 --- a/server/src/internalClusterTest/java/org/opensearch/recovery/RelocationIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/recovery/RelocationIT.java @@ -601,7 +601,7 @@ public void testIndexSearchAndRelocateConcurrently() throws Exception { logger.info(" --> checking iteration {}", i); SearchResponse afterRelocation = client().prepareSearch().setSize(ids.size()).get(); assertNoFailures(afterRelocation); - assertSearchHits(afterRelocation, ids.toArray(new String[ids.size()])); + assertSearchHits(afterRelocation, ids.toArray(new String[0])); } stopped.set(true); for (Thread searchThread : searchThreads) { diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/GeoDistanceIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/GeoDistanceIT.java index db689a57d6d44..ed0bd3aad5bab 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/GeoDistanceIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/GeoDistanceIT.java @@ -164,7 +164,7 @@ public void setupSuiteScopeCluster() throws Exception { .setSource(jsonBuilder().startObject().field("value", i * 2).field("location", "52.0945, 5.116").endObject()) ); } - indexRandom(true, builders.toArray(new IndexRequestBuilder[builders.size()])); + indexRandom(true, builders.toArray(new IndexRequestBuilder[0])); ensureSearchable(); } diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/LongTermsIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/LongTermsIT.java index cac0b05c01be2..49031bfd3fc1d 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/LongTermsIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/bucket/LongTermsIT.java @@ -180,7 +180,7 @@ public void setupSuiteScopeCluster() throws Exception { getMultiSortDocs(builders); - indexRandom(true, builders.toArray(new IndexRequestBuilder[builders.size()])); + indexRandom(true, builders.toArray(new IndexRequestBuilder[0])); ensureSearchable(); } 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 7805e0bac4c0b..a8bd9bc4eadcd 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 @@ -188,7 +188,7 @@ public void testDocCountTopLevel() throws Exception { assertThat(maxBucketValue, notNullValue()); assertThat(maxBucketValue.getName(), equalTo("max_bucket")); assertThat(maxBucketValue.value(), equalTo(maxValue)); - assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()]))); + assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0]))); } public void testDocCountAsSubAgg() throws Exception { @@ -240,7 +240,7 @@ public void testDocCountAsSubAgg() throws Exception { assertThat(maxBucketValue, notNullValue()); assertThat(maxBucketValue.getName(), equalTo("max_bucket")); assertThat(maxBucketValue.value(), equalTo(maxValue)); - assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()]))); + assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0]))); } } @@ -280,7 +280,7 @@ public void testMetricTopLevel() throws Exception { assertThat(maxBucketValue, notNullValue()); assertThat(maxBucketValue.getName(), equalTo("max_bucket")); assertThat(maxBucketValue.value(), equalTo(maxValue)); - assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()]))); + assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0]))); } public void testMetricAsSubAgg() throws Exception { @@ -339,7 +339,7 @@ public void testMetricAsSubAgg() throws Exception { assertThat(maxBucketValue, notNullValue()); assertThat(maxBucketValue.getName(), equalTo("max_bucket")); assertThat(maxBucketValue.value(), equalTo(maxValue)); - assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()]))); + assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0]))); } } @@ -388,7 +388,7 @@ public void testMetricAsSubAggOfSingleBucketAgg() throws Exception { assertThat(maxBucketValue, notNullValue()); assertThat(maxBucketValue.getName(), equalTo("max_bucket")); assertThat(maxBucketValue.value(), equalTo(maxValue)); - assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()]))); + assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0]))); } public void testMetricAsSubAggWithInsertZeros() throws Exception { @@ -445,7 +445,7 @@ public void testMetricAsSubAggWithInsertZeros() throws Exception { assertThat(maxBucketValue, notNullValue()); assertThat(maxBucketValue.getName(), equalTo("max_bucket")); assertThat(maxBucketValue.value(), equalTo(maxValue)); - assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[maxKeys.size()]))); + assertThat(maxBucketValue.keys(), equalTo(maxKeys.toArray(new String[0]))); } } @@ -526,7 +526,7 @@ public void testNested() throws Exception { assertThat(maxBucketValue, notNullValue()); assertThat(maxBucketValue.getName(), equalTo("max_histo_bucket")); assertThat(maxBucketValue.value(), equalTo(maxHistoValue)); - assertThat(maxBucketValue.keys(), equalTo(maxHistoKeys.toArray(new String[maxHistoKeys.size()]))); + assertThat(maxBucketValue.keys(), equalTo(maxHistoKeys.toArray(new String[0]))); if (maxHistoValue > maxTermsValue) { maxTermsValue = maxHistoValue; maxTermsKeys = new ArrayList<>(); @@ -540,7 +540,7 @@ public void testNested() throws Exception { assertThat(maxBucketValue, notNullValue()); assertThat(maxBucketValue.getName(), equalTo("max_terms_bucket")); assertThat(maxBucketValue.value(), equalTo(maxTermsValue)); - assertThat(maxBucketValue.keys(), equalTo(maxTermsKeys.toArray(new String[maxTermsKeys.size()]))); + assertThat(maxBucketValue.keys(), equalTo(maxTermsKeys.toArray(new String[0]))); } /** diff --git a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/MinBucketIT.java b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/MinBucketIT.java index e1e8d8b035ae1..290583ce49a5e 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/MinBucketIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/aggregations/pipeline/MinBucketIT.java @@ -174,7 +174,7 @@ public void testDocCountTopLevel() throws Exception { assertThat(minBucketValue, notNullValue()); assertThat(minBucketValue.getName(), equalTo("min_bucket")); assertThat(minBucketValue.value(), equalTo(minValue)); - assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()]))); + assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0]))); } public void testDocCountAsSubAgg() throws Exception { @@ -226,7 +226,7 @@ public void testDocCountAsSubAgg() throws Exception { assertThat(minBucketValue, notNullValue()); assertThat(minBucketValue.getName(), equalTo("min_bucket")); assertThat(minBucketValue.value(), equalTo(minValue)); - assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()]))); + assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0]))); } } @@ -266,7 +266,7 @@ public void testMetricTopLevel() throws Exception { assertThat(minBucketValue, notNullValue()); assertThat(minBucketValue.getName(), equalTo("min_bucket")); assertThat(minBucketValue.value(), equalTo(minValue)); - assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()]))); + assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0]))); } public void testMetricAsSubAgg() throws Exception { @@ -325,7 +325,7 @@ public void testMetricAsSubAgg() throws Exception { assertThat(minBucketValue, notNullValue()); assertThat(minBucketValue.getName(), equalTo("min_bucket")); assertThat(minBucketValue.value(), equalTo(minValue)); - assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()]))); + assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0]))); } } @@ -383,7 +383,7 @@ public void testMetricAsSubAggWithInsertZeros() throws Exception { assertThat(minBucketValue, notNullValue()); assertThat(minBucketValue.getName(), equalTo("min_bucket")); assertThat(minBucketValue.value(), equalTo(minValue)); - assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[minKeys.size()]))); + assertThat(minBucketValue.keys(), equalTo(minKeys.toArray(new String[0]))); } } @@ -464,7 +464,7 @@ public void testNested() throws Exception { assertThat(minBucketValue, notNullValue()); assertThat(minBucketValue.getName(), equalTo("min_histo_bucket")); assertThat(minBucketValue.value(), equalTo(minHistoValue)); - assertThat(minBucketValue.keys(), equalTo(minHistoKeys.toArray(new String[minHistoKeys.size()]))); + assertThat(minBucketValue.keys(), equalTo(minHistoKeys.toArray(new String[0]))); if (minHistoValue < minTermsValue) { minTermsValue = minHistoValue; minTermsKeys = new ArrayList<>(); @@ -478,6 +478,6 @@ public void testNested() throws Exception { assertThat(minBucketValue, notNullValue()); assertThat(minBucketValue.getName(), equalTo("min_terms_bucket")); assertThat(minBucketValue.value(), equalTo(minTermsValue)); - assertThat(minBucketValue.keys(), equalTo(minTermsKeys.toArray(new String[minTermsKeys.size()]))); + assertThat(minBucketValue.keys(), equalTo(minTermsKeys.toArray(new String[0]))); } } diff --git a/server/src/internalClusterTest/java/org/opensearch/search/basic/SearchWhileRelocatingIT.java b/server/src/internalClusterTest/java/org/opensearch/search/basic/SearchWhileRelocatingIT.java index 54f853c9f512c..f7b8b0df7dca7 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/basic/SearchWhileRelocatingIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/basic/SearchWhileRelocatingIT.java @@ -103,7 +103,7 @@ private void testSearchAndRelocateConcurrently(final int numberOfReplicas) throw ) ); } - indexRandom(true, indexBuilders.toArray(new IndexRequestBuilder[indexBuilders.size()])); + indexRandom(true, indexBuilders.toArray(new IndexRequestBuilder[0])); assertHitCount(client().prepareSearch().get(), (numDocs)); final int numIters = scaledRandomIntBetween(5, 20); for (int i = 0; i < numIters; i++) { diff --git a/server/src/internalClusterTest/java/org/opensearch/search/morelikethis/MoreLikeThisIT.java b/server/src/internalClusterTest/java/org/opensearch/search/morelikethis/MoreLikeThisIT.java index 91611913d1939..36fc5de0a5cf7 100644 --- a/server/src/internalClusterTest/java/org/opensearch/search/morelikethis/MoreLikeThisIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/search/morelikethis/MoreLikeThisIT.java @@ -793,7 +793,7 @@ public void testMoreLikeThisUnlike() throws ExecutionException, InterruptedExcep List docs = new ArrayList<>(numFields); for (int i = 0; i < numFields; i++) { docs.add(new Item("test", i + "")); - mltQuery = moreLikeThisQuery(null, new Item[] { new Item("test", doc) }).unlike(docs.toArray(new Item[docs.size()])) + mltQuery = moreLikeThisQuery(null, new Item[] { new Item("test", doc) }).unlike(docs.toArray(new Item[0])) .minTermFreq(0) .minDocFreq(0) .maxQueryTerms(100) diff --git a/server/src/internalClusterTest/java/org/opensearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/internalClusterTest/java/org/opensearch/snapshots/SharedClusterSnapshotRestoreIT.java index 2d48882e43739..d2003f5dca0e2 100644 --- a/server/src/internalClusterTest/java/org/opensearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/server/src/internalClusterTest/java/org/opensearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -149,7 +149,7 @@ public void testBasicWorkFlow() throws Exception { } } if (!indicesToFlush.isEmpty()) { - String[] indices = indicesToFlush.toArray(new String[indicesToFlush.size()]); + String[] indices = indicesToFlush.toArray(new String[0]); logger.info("--> starting asynchronous flush for indices {}", Arrays.toString(indices)); flushResponseFuture = client().admin().indices().prepareFlush(indices).execute(); } @@ -1785,7 +1785,7 @@ public void testRestoreSnapshotWithCorruptedIndexMetadata() throws Exception { assertThat(snapshotInfos.get(0).state(), equalTo(SnapshotState.SUCCESS)); assertThat(snapshotInfos.get(0).snapshotId().getName(), equalTo("test-snap")); - assertAcked(client().admin().indices().prepareDelete(nbDocsPerIndex.keySet().toArray(new String[nbDocsPerIndex.size()]))); + assertAcked(client().admin().indices().prepareDelete(nbDocsPerIndex.keySet().toArray(new String[0]))); Predicate isRestorableIndex = index -> corruptedIndex.getName().equals(index) == false; diff --git a/server/src/main/java/org/apache/lucene/search/uhighlight/CustomFieldHighlighter.java b/server/src/main/java/org/apache/lucene/search/uhighlight/CustomFieldHighlighter.java index dd28d5c28b1ca..22d5146f5bd4f 100644 --- a/server/src/main/java/org/apache/lucene/search/uhighlight/CustomFieldHighlighter.java +++ b/server/src/main/java/org/apache/lucene/search/uhighlight/CustomFieldHighlighter.java @@ -174,7 +174,7 @@ protected Passage[] highlightOffsetsEnums(OffsetsEnum off) throws IOException { } while (off.nextPosition()); maybeAddPassage(passageQueue, passageScorer, passage, contentLength); - Passage[] passages = passageQueue.toArray(new Passage[passageQueue.size()]); + Passage[] passages = passageQueue.toArray(new Passage[0]); // sort in ascending order Arrays.sort(passages, Comparator.comparingInt(Passage::getStartOffset)); return passages; 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 a0327af1dbd84..afa2058d1deba 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 @@ -92,7 +92,7 @@ public RestoreRemoteStoreRequest indices(String... indices) { * @return this request */ public RestoreRemoteStoreRequest indices(List indices) { - this.indices = indices.toArray(new String[indices.size()]); + this.indices = indices.toArray(new String[0]); return 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 2323c3f91d102..80360b95886fc 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 @@ -261,7 +261,7 @@ public CreateSnapshotRequest indices(String... indices) { * @return this request */ public CreateSnapshotRequest indices(List indices) { - this.indices = indices.toArray(new String[indices.size()]); + this.indices = indices.toArray(new String[0]); return 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 4e0e71a80b139..4d678893a8851 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 @@ -312,7 +312,7 @@ public RestoreSnapshotRequest indices(String... indices) { * @return this request */ public RestoreSnapshotRequest indices(List indices) { - this.indices = indices.toArray(new String[indices.size()]); + this.indices = indices.toArray(new String[0]); return this; } @@ -487,7 +487,7 @@ public RestoreSnapshotRequest ignoreIndexSettings(String... ignoreIndexSettings) * Sets the list of index settings and index settings groups that shouldn't be restored from snapshot */ public RestoreSnapshotRequest ignoreIndexSettings(List ignoreIndexSettings) { - this.ignoreIndexSettings = ignoreIndexSettings.toArray(new String[ignoreIndexSettings.size()]); + this.ignoreIndexSettings = ignoreIndexSettings.toArray(new String[0]); return this; } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/alias/TransportIndicesAliasesAction.java b/server/src/main/java/org/opensearch/action/admin/indices/alias/TransportIndicesAliasesAction.java index b15c420335792..81cb3102cfcb9 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/alias/TransportIndicesAliasesAction.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/alias/TransportIndicesAliasesAction.java @@ -123,7 +123,7 @@ protected ClusterBlockException checkBlock(IndicesAliasesRequest request, Cluste for (IndicesAliasesRequest.AliasActions aliasAction : request.aliasActions()) { Collections.addAll(indices, aliasAction.indices()); } - return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_WRITE, indices.toArray(new String[indices.size()])); + return state.blocks().indicesBlockedException(ClusterBlockLevel.METADATA_WRITE, indices.toArray(new String[0])); } @Override @@ -196,7 +196,7 @@ protected void clusterManagerOperation( } } if (finalActions.isEmpty() && false == actions.isEmpty()) { - throw new AliasesNotFoundException(aliases.toArray(new String[aliases.size()])); + throw new AliasesNotFoundException(aliases.toArray(new String[0])); } request.aliasActions().clear(); IndicesAliasesClusterStateUpdateRequest updateRequest = new IndicesAliasesClusterStateUpdateRequest(unmodifiableList(finalActions)) diff --git a/server/src/main/java/org/opensearch/action/admin/indices/delete/TransportDeleteIndexAction.java b/server/src/main/java/org/opensearch/action/admin/indices/delete/TransportDeleteIndexAction.java index 51c90a982e71b..410a58afc95f1 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/delete/TransportDeleteIndexAction.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/delete/TransportDeleteIndexAction.java @@ -128,7 +128,7 @@ protected void clusterManagerOperation( DeleteIndexClusterStateUpdateRequest deleteRequest = new DeleteIndexClusterStateUpdateRequest().ackTimeout(request.timeout()) .masterNodeTimeout(request.clusterManagerNodeTimeout()) - .indices(concreteIndices.toArray(new Index[concreteIndices.size()])); + .indices(concreteIndices.toArray(new Index[0])); deleteIndexService.deleteIndices(deleteRequest, new ActionListener() { diff --git a/server/src/main/java/org/opensearch/action/admin/indices/segments/IndexSegments.java b/server/src/main/java/org/opensearch/action/admin/indices/segments/IndexSegments.java index 810a33270921f..4b37da2c99850 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/segments/IndexSegments.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/segments/IndexSegments.java @@ -68,10 +68,7 @@ public class IndexSegments implements Iterable { for (Map.Entry> entry : tmpIndexShards.entrySet()) { indexShards.put( entry.getKey(), - new IndexShardSegments( - entry.getValue().get(0).getShardRouting().shardId(), - entry.getValue().toArray(new ShardSegments[entry.getValue().size()]) - ) + new IndexShardSegments(entry.getValue().get(0).getShardRouting().shardId(), entry.getValue().toArray(new ShardSegments[0])) ); } } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/segments/PitSegmentsRequest.java b/server/src/main/java/org/opensearch/action/admin/indices/segments/PitSegmentsRequest.java index ead28f848985e..84edec384b68a 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/segments/PitSegmentsRequest.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/segments/PitSegmentsRequest.java @@ -68,7 +68,7 @@ public void setVerbose(boolean v) { @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); - out.writeStringArrayNullable((pitIds == null) ? null : pitIds.toArray(new String[pitIds.size()])); + out.writeStringArrayNullable((pitIds == null) ? null : pitIds.toArray(new String[0])); out.writeBoolean(verbose); } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/segments/TransportIndicesSegmentsAction.java b/server/src/main/java/org/opensearch/action/admin/indices/segments/TransportIndicesSegmentsAction.java index 9ec305b30e2b0..6dad4b8e3554f 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/segments/TransportIndicesSegmentsAction.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/segments/TransportIndicesSegmentsAction.java @@ -119,7 +119,7 @@ protected IndicesSegmentResponse newResponse( ClusterState clusterState ) { return new IndicesSegmentResponse( - results.toArray(new ShardSegments[results.size()]), + results.toArray(new ShardSegments[0]), totalShards, successfulShards, failedShards, diff --git a/server/src/main/java/org/opensearch/action/admin/indices/segments/TransportPitSegmentsAction.java b/server/src/main/java/org/opensearch/action/admin/indices/segments/TransportPitSegmentsAction.java index 805073f79645a..393c07ba58c5e 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/segments/TransportPitSegmentsAction.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/segments/TransportPitSegmentsAction.java @@ -170,7 +170,7 @@ protected IndicesSegmentResponse newResponse( ClusterState clusterState ) { return new IndicesSegmentResponse( - results.toArray(new ShardSegments[results.size()]), + results.toArray(new ShardSegments[0]), totalShards, successfulShards, failedShards, diff --git a/server/src/main/java/org/opensearch/action/admin/indices/stats/CommonStatsFlags.java b/server/src/main/java/org/opensearch/action/admin/indices/stats/CommonStatsFlags.java index 223c3a0733c0f..d553e07c4c7ed 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/stats/CommonStatsFlags.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/stats/CommonStatsFlags.java @@ -183,7 +183,7 @@ public boolean anySet() { } public Flag[] getFlags() { - return flags.toArray(new Flag[flags.size()]); + return flags.toArray(new Flag[0]); } public Set getIncludeCaches() { diff --git a/server/src/main/java/org/opensearch/action/admin/indices/stats/IndexStats.java b/server/src/main/java/org/opensearch/action/admin/indices/stats/IndexStats.java index f46696e406d83..09614ea801193 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/stats/IndexStats.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/stats/IndexStats.java @@ -91,10 +91,7 @@ public Map getIndexShards() { for (Map.Entry> entry : tmpIndexShards.entrySet()) { indexShards.put( entry.getKey(), - new IndexShardStats( - entry.getValue().get(0).getShardRouting().shardId(), - entry.getValue().toArray(new ShardStats[entry.getValue().size()]) - ) + new IndexShardStats(entry.getValue().get(0).getShardRouting().shardId(), entry.getValue().toArray(new ShardStats[0])) ); } return indexShards; @@ -156,7 +153,7 @@ public IndexStatsBuilder add(ShardStats shardStats) { } public IndexStats build() { - return new IndexStats(indexName, uuid, shards.toArray(new ShardStats[shards.size()])); + return new IndexStats(indexName, uuid, shards.toArray(new ShardStats[0])); } } } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/stats/TransportIndicesStatsAction.java b/server/src/main/java/org/opensearch/action/admin/indices/stats/TransportIndicesStatsAction.java index 747213a23f577..2b85b6d5d6b5b 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/stats/TransportIndicesStatsAction.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/stats/TransportIndicesStatsAction.java @@ -120,13 +120,7 @@ protected IndicesStatsResponse newResponse( List shardFailures, ClusterState clusterState ) { - return new IndicesStatsResponse( - responses.toArray(new ShardStats[responses.size()]), - totalShards, - successfulShards, - failedShards, - shardFailures - ); + return new IndicesStatsResponse(responses.toArray(new ShardStats[0]), totalShards, successfulShards, failedShards, shardFailures); } @Override 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 9e11973b5bdf3..d4e9200508bfa 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 @@ -478,7 +478,7 @@ public PutIndexTemplateRequest alias(Alias alias) { @Override public String[] indices() { - return indexPatterns.toArray(new String[indexPatterns.size()]); + return indexPatterns.toArray(new String[0]); } @Override diff --git a/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/IndexUpgradeStatus.java b/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/IndexUpgradeStatus.java index 1768eba250705..fd8ddc1293aaf 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/IndexUpgradeStatus.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/IndexUpgradeStatus.java @@ -70,7 +70,7 @@ public class IndexUpgradeStatus implements Iterable { entry.getKey(), new IndexShardUpgradeStatus( entry.getValue().get(0).getShardRouting().shardId(), - entry.getValue().toArray(new ShardUpgradeStatus[entry.getValue().size()]) + entry.getValue().toArray(new ShardUpgradeStatus[0]) ) ); } diff --git a/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/TransportUpgradeStatusAction.java b/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/TransportUpgradeStatusAction.java index e3afa342a933a..a171355fb2049 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/TransportUpgradeStatusAction.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/TransportUpgradeStatusAction.java @@ -121,7 +121,7 @@ protected UpgradeStatusResponse newResponse( ClusterState clusterState ) { return new UpgradeStatusResponse( - responses.toArray(new ShardUpgradeStatus[responses.size()]), + responses.toArray(new ShardUpgradeStatus[0]), totalShards, successfulShards, failedShards, diff --git a/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/UpgradeStatusResponse.java b/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/UpgradeStatusResponse.java index b94a4c8ae27c4..ba2915ee4ddf1 100644 --- a/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/UpgradeStatusResponse.java +++ b/server/src/main/java/org/opensearch/action/admin/indices/upgrade/get/UpgradeStatusResponse.java @@ -96,7 +96,7 @@ public Map getIndices() { shards.add(shard); } } - indicesUpgradeStats.put(indexName, new IndexUpgradeStatus(indexName, shards.toArray(new ShardUpgradeStatus[shards.size()]))); + indicesUpgradeStats.put(indexName, new IndexUpgradeStatus(indexName, shards.toArray(new ShardUpgradeStatus[0]))); } this.indicesUpgradeStatus = indicesUpgradeStats; return indicesUpgradeStats; diff --git a/server/src/main/java/org/opensearch/action/bulk/BulkResponse.java b/server/src/main/java/org/opensearch/action/bulk/BulkResponse.java index 1d50986eff334..6b70e2acd41d2 100644 --- a/server/src/main/java/org/opensearch/action/bulk/BulkResponse.java +++ b/server/src/main/java/org/opensearch/action/bulk/BulkResponse.java @@ -216,6 +216,6 @@ public static BulkResponse fromXContent(XContentParser parser) throws IOExceptio throwUnknownToken(token, parser.getTokenLocation()); } } - return new BulkResponse(items.toArray(new BulkItemResponse[items.size()]), took, ingestTook); + return new BulkResponse(items.toArray(new BulkItemResponse[0]), took, ingestTook); } } diff --git a/server/src/main/java/org/opensearch/action/bulk/TransportBulkAction.java b/server/src/main/java/org/opensearch/action/bulk/TransportBulkAction.java index 6a8ede6cc2d58..9ff8e14ac49d5 100644 --- a/server/src/main/java/org/opensearch/action/bulk/TransportBulkAction.java +++ b/server/src/main/java/org/opensearch/action/bulk/TransportBulkAction.java @@ -642,7 +642,7 @@ protected void doRun() { BulkShardRequest bulkShardRequest = new BulkShardRequest( shardId, bulkRequest.getRefreshPolicy(), - requests.toArray(new BulkItemRequest[requests.size()]) + requests.toArray(new BulkItemRequest[0]) ); bulkShardRequest.waitForActiveShards(bulkRequest.waitForActiveShards()); bulkShardRequest.timeout(bulkRequest.timeout()); 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 8221c43ad8748..b14774494b975 100644 --- a/server/src/main/java/org/opensearch/action/get/MultiGetRequest.java +++ b/server/src/main/java/org/opensearch/action/get/MultiGetRequest.java @@ -521,15 +521,15 @@ private static void parseDocuments( fetchSourceContext = new FetchSourceContext( fetchSourceContext.fetchSource(), - includes == null ? Strings.EMPTY_ARRAY : includes.toArray(new String[includes.size()]), - excludes == null ? Strings.EMPTY_ARRAY : excludes.toArray(new String[excludes.size()]) + includes == null ? Strings.EMPTY_ARRAY : includes.toArray(new String[0]), + excludes == null ? Strings.EMPTY_ARRAY : excludes.toArray(new String[0]) ); } } } String[] aFields; if (storedFields != null) { - aFields = storedFields.toArray(new String[storedFields.size()]); + aFields = storedFields.toArray(new String[0]); } else { aFields = defaultFields; } diff --git a/server/src/main/java/org/opensearch/action/search/ClearScrollRequest.java b/server/src/main/java/org/opensearch/action/search/ClearScrollRequest.java index 99eee5f3e99da..16bf0fc46c4eb 100644 --- a/server/src/main/java/org/opensearch/action/search/ClearScrollRequest.java +++ b/server/src/main/java/org/opensearch/action/search/ClearScrollRequest.java @@ -103,7 +103,7 @@ public void writeTo(StreamOutput out) throws IOException { if (scrollIds == null) { out.writeVInt(0); } else { - out.writeStringArray(scrollIds.toArray(new String[scrollIds.size()])); + out.writeStringArray(scrollIds.toArray(new String[0])); } } diff --git a/server/src/main/java/org/opensearch/action/search/DeletePitRequest.java b/server/src/main/java/org/opensearch/action/search/DeletePitRequest.java index 1178c4f7d9852..e21a63eef9433 100644 --- a/server/src/main/java/org/opensearch/action/search/DeletePitRequest.java +++ b/server/src/main/java/org/opensearch/action/search/DeletePitRequest.java @@ -78,7 +78,7 @@ public void writeTo(StreamOutput out) throws IOException { if (pitIds == null) { out.writeVInt(0); } else { - out.writeStringArray(pitIds.toArray(new String[pitIds.size()])); + out.writeStringArray(pitIds.toArray(new String[0])); } } diff --git a/server/src/main/java/org/opensearch/action/search/PitService.java b/server/src/main/java/org/opensearch/action/search/PitService.java index ea44e3895cd2a..b6480ce63f827 100644 --- a/server/src/main/java/org/opensearch/action/search/PitService.java +++ b/server/src/main/java/org/opensearch/action/search/PitService.java @@ -175,7 +175,7 @@ public void getAllPits(ActionListener getAllPitsListener for (final DiscoveryNode node : clusterService.state().nodes().getDataNodes().values()) { nodes.add(node); } - DiscoveryNode[] disNodesArr = nodes.toArray(new DiscoveryNode[nodes.size()]); + DiscoveryNode[] disNodesArr = nodes.toArray(new DiscoveryNode[0]); GetAllPitNodesRequest getAllPitNodesRequest = new GetAllPitNodesRequest(disNodesArr); transportService.sendRequest( transportService.getLocalNode(), diff --git a/server/src/main/java/org/opensearch/action/search/SearchScrollAsyncAction.java b/server/src/main/java/org/opensearch/action/search/SearchScrollAsyncAction.java index 51d9a34937f79..7329a03f7e281 100644 --- a/server/src/main/java/org/opensearch/action/search/SearchScrollAsyncAction.java +++ b/server/src/main/java/org/opensearch/action/search/SearchScrollAsyncAction.java @@ -243,7 +243,7 @@ synchronized ShardSearchFailure[] buildShardFailures() { // pkg private for test if (shardFailures.isEmpty()) { return ShardSearchFailure.EMPTY_ARRAY; } - return shardFailures.toArray(new ShardSearchFailure[shardFailures.size()]); + return shardFailures.toArray(new ShardSearchFailure[0]); } // we do our best to return the shard failures, but its ok if its not fully concurrently safe diff --git a/server/src/main/java/org/opensearch/action/support/ActionFilters.java b/server/src/main/java/org/opensearch/action/support/ActionFilters.java index 95cafbea4d7c1..cad828e08a25e 100644 --- a/server/src/main/java/org/opensearch/action/support/ActionFilters.java +++ b/server/src/main/java/org/opensearch/action/support/ActionFilters.java @@ -46,7 +46,7 @@ public class ActionFilters { private final ActionFilter[] filters; public ActionFilters(Set actionFilters) { - this.filters = actionFilters.toArray(new ActionFilter[actionFilters.size()]); + this.filters = actionFilters.toArray(new ActionFilter[0]); Arrays.sort(filters, new Comparator() { @Override public int compare(ActionFilter o1, ActionFilter o2) { diff --git a/server/src/main/java/org/opensearch/action/support/broadcast/BroadcastResponse.java b/server/src/main/java/org/opensearch/action/support/broadcast/BroadcastResponse.java index fc0210d3e69b8..071e4d9f36923 100644 --- a/server/src/main/java/org/opensearch/action/support/broadcast/BroadcastResponse.java +++ b/server/src/main/java/org/opensearch/action/support/broadcast/BroadcastResponse.java @@ -114,7 +114,7 @@ public BroadcastResponse( if (shardFailures == null) { this.shardFailures = EMPTY; } else { - this.shardFailures = shardFailures.toArray(new DefaultShardOperationFailedException[shardFailures.size()]); + this.shardFailures = shardFailures.toArray(new DefaultShardOperationFailedException[0]); } } diff --git a/server/src/main/java/org/opensearch/action/support/replication/ReplicationResponse.java b/server/src/main/java/org/opensearch/action/support/replication/ReplicationResponse.java index bc517ae5fc3a8..67480976c500f 100644 --- a/server/src/main/java/org/opensearch/action/support/replication/ReplicationResponse.java +++ b/server/src/main/java/org/opensearch/action/support/replication/ReplicationResponse.java @@ -225,7 +225,7 @@ public static ShardInfo fromXContent(XContentParser parser) throws IOException { } Failure[] failures = EMPTY; if (failuresList != null) { - failures = failuresList.toArray(new Failure[failuresList.size()]); + failures = failuresList.toArray(new Failure[0]); } return new ShardInfo(total, successful, failures); } diff --git a/server/src/main/java/org/opensearch/cluster/metadata/IndexNameExpressionResolver.java b/server/src/main/java/org/opensearch/cluster/metadata/IndexNameExpressionResolver.java index f7663e5509112..7efe4efd9afd7 100644 --- a/server/src/main/java/org/opensearch/cluster/metadata/IndexNameExpressionResolver.java +++ b/server/src/main/java/org/opensearch/cluster/metadata/IndexNameExpressionResolver.java @@ -356,7 +356,7 @@ Index[] concreteIndices(Context context, String... indexExpressions) { throw infe; } checkSystemIndexAccess(context, metadata, concreteIndices, indexExpressions); - return concreteIndices.toArray(new Index[concreteIndices.size()]); + return concreteIndices.toArray(new Index[0]); } private void checkSystemIndexAccess(Context context, Metadata metadata, Set concreteIndices, String[] originalPatterns) { @@ -604,7 +604,7 @@ public String[] indexAliases( if (aliases == null) { return null; } - return aliases.toArray(new String[aliases.size()]); + return aliases.toArray(new String[0]); } /** diff --git a/server/src/main/java/org/opensearch/cluster/routing/RoutingNodes.java b/server/src/main/java/org/opensearch/cluster/routing/RoutingNodes.java index 884387b45e015..76111f623e0a5 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/RoutingNodes.java +++ b/server/src/main/java/org/opensearch/cluster/routing/RoutingNodes.java @@ -1179,7 +1179,7 @@ public void shuffle() { */ public ShardRouting[] drain() { nodes.ensureMutable(); - ShardRouting[] mutableShardRoutings = unassigned.toArray(new ShardRouting[unassigned.size()]); + ShardRouting[] mutableShardRoutings = unassigned.toArray(new ShardRouting[0]); unassigned.clear(); primaries = 0; return mutableShardRoutings; @@ -1191,7 +1191,7 @@ public ShardRouting[] drain() { */ public ShardRouting[] drainIgnored() { nodes.ensureMutable(); - ShardRouting[] mutableShardRoutings = ignored.toArray(new ShardRouting[ignored.size()]); + ShardRouting[] mutableShardRoutings = ignored.toArray(new ShardRouting[0]); ignored.clear(); ignoredPrimaries = 0; return mutableShardRoutings; diff --git a/server/src/main/java/org/opensearch/cluster/routing/allocation/AllocationService.java b/server/src/main/java/org/opensearch/cluster/routing/allocation/AllocationService.java index a1c3e6a03ce52..78f17c9ff212b 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/allocation/AllocationService.java +++ b/server/src/main/java/org/opensearch/cluster/routing/allocation/AllocationService.java @@ -380,7 +380,7 @@ public ClusterState adaptAutoExpandReplicas(ClusterState clusterState) { final Metadata.Builder metadataBuilder = Metadata.builder(clusterState.metadata()); for (Map.Entry> entry : autoExpandReplicaChanges.entrySet()) { final int numberOfReplicas = entry.getKey(); - final String[] indices = entry.getValue().toArray(new String[entry.getValue().size()]); + final String[] indices = entry.getValue().toArray(new String[0]); // we do *not* update the in sync allocation ids as they will be removed upon the first index // operation which make these copies stale routingTableBuilder.updateNumberOfReplicas(numberOfReplicas, indices); diff --git a/server/src/main/java/org/opensearch/cluster/routing/allocation/allocator/LocalShardsBalancer.java b/server/src/main/java/org/opensearch/cluster/routing/allocation/allocator/LocalShardsBalancer.java index 4d0b654f9d52f..7f6a7790d1db0 100644 --- a/server/src/main/java/org/opensearch/cluster/routing/allocation/allocator/LocalShardsBalancer.java +++ b/server/src/main/java/org/opensearch/cluster/routing/allocation/allocator/LocalShardsBalancer.java @@ -111,7 +111,7 @@ public LocalShardsBalancer( * Returns an array view on the nodes in the balancer. Nodes should not be removed from this list. */ private BalancedShardsAllocator.ModelNode[] nodesArray() { - return nodes.values().toArray(new BalancedShardsAllocator.ModelNode[nodes.size()]); + return nodes.values().toArray(new BalancedShardsAllocator.ModelNode[0]); } /** diff --git a/server/src/main/java/org/opensearch/common/blobstore/BlobPath.java b/server/src/main/java/org/opensearch/common/blobstore/BlobPath.java index 076c49ffa6d45..68af77714a319 100644 --- a/server/src/main/java/org/opensearch/common/blobstore/BlobPath.java +++ b/server/src/main/java/org/opensearch/common/blobstore/BlobPath.java @@ -71,7 +71,7 @@ public Iterator iterator() { } public String[] toArray() { - return paths.toArray(new String[paths.size()]); + return paths.toArray(new String[0]); } public BlobPath add(String path) { diff --git a/server/src/main/java/org/opensearch/common/geo/GeoPolygonDecomposer.java b/server/src/main/java/org/opensearch/common/geo/GeoPolygonDecomposer.java index 2260f1ffdfeed..1dd35707f0879 100644 --- a/server/src/main/java/org/opensearch/common/geo/GeoPolygonDecomposer.java +++ b/server/src/main/java/org/opensearch/common/geo/GeoPolygonDecomposer.java @@ -464,7 +464,7 @@ private static Edge[] edges(Edge[] edges, int numHoles, List> comp } } - return mainEdges.toArray(new Edge[mainEdges.size()]); + return mainEdges.toArray(new Edge[0]); } private static void compose(Edge[] edges, Edge[] holes, int numHoles, List collector) { diff --git a/server/src/main/java/org/opensearch/common/geo/builders/LineStringBuilder.java b/server/src/main/java/org/opensearch/common/geo/builders/LineStringBuilder.java index dacf8056cfe2e..94124e7f71ad1 100644 --- a/server/src/main/java/org/opensearch/common/geo/builders/LineStringBuilder.java +++ b/server/src/main/java/org/opensearch/common/geo/builders/LineStringBuilder.java @@ -122,7 +122,7 @@ public int numDimensions() { @Override public JtsGeometry buildS4J() { - Coordinate[] coordinates = this.coordinates.toArray(new Coordinate[this.coordinates.size()]); + Coordinate[] coordinates = this.coordinates.toArray(new Coordinate[0]); Geometry geometry; if (wrapdateline) { ArrayList strings = decomposeS4J(FACTORY, coordinates, new ArrayList()); @@ -130,7 +130,7 @@ public JtsGeometry buildS4J() { if (strings.size() == 1) { geometry = strings.get(0); } else { - LineString[] linestrings = strings.toArray(new LineString[strings.size()]); + LineString[] linestrings = strings.toArray(new LineString[0]); geometry = FACTORY.createMultiLineString(linestrings); } diff --git a/server/src/main/java/org/opensearch/common/geo/builders/MultiLineStringBuilder.java b/server/src/main/java/org/opensearch/common/geo/builders/MultiLineStringBuilder.java index db5bd758b715c..e945341a32111 100644 --- a/server/src/main/java/org/opensearch/common/geo/builders/MultiLineStringBuilder.java +++ b/server/src/main/java/org/opensearch/common/geo/builders/MultiLineStringBuilder.java @@ -154,7 +154,7 @@ public JtsGeometry buildS4J() { if (parts.size() == 1) { geometry = parts.get(0); } else { - LineString[] lineStrings = parts.toArray(new LineString[parts.size()]); + LineString[] lineStrings = parts.toArray(new LineString[0]); geometry = FACTORY.createMultiLineString(lineStrings); } } else { diff --git a/server/src/main/java/org/opensearch/common/geo/builders/PolygonBuilder.java b/server/src/main/java/org/opensearch/common/geo/builders/PolygonBuilder.java index 5fa70a191e7d7..9e118ab2de3a5 100644 --- a/server/src/main/java/org/opensearch/common/geo/builders/PolygonBuilder.java +++ b/server/src/main/java/org/opensearch/common/geo/builders/PolygonBuilder.java @@ -309,7 +309,7 @@ protected static org.opensearch.geometry.LinearRing linearRing(List } protected static LinearRing linearRingS4J(GeometryFactory factory, List coordinates) { - return factory.createLinearRing(coordinates.toArray(new Coordinate[coordinates.size()])); + return factory.createLinearRing(coordinates.toArray(new Coordinate[0])); } @Override @@ -507,7 +507,7 @@ private static Edge[] edges(Edge[] edges, int numHoles, List> } } - return mainEdges.toArray(new Edge[mainEdges.size()]); + return mainEdges.toArray(new Edge[0]); } private static Coordinate[][][] compose(Edge[] edges, Edge[] holes, int numHoles) { diff --git a/server/src/main/java/org/opensearch/common/lucene/index/FilterableTermsEnum.java b/server/src/main/java/org/opensearch/common/lucene/index/FilterableTermsEnum.java index 61c9e9f54cb51..224c5b600c930 100644 --- a/server/src/main/java/org/opensearch/common/lucene/index/FilterableTermsEnum.java +++ b/server/src/main/java/org/opensearch/common/lucene/index/FilterableTermsEnum.java @@ -140,7 +140,7 @@ protected boolean match(int doc) { } enums.add(new Holder(termsEnum, bits)); } - this.enums = enums.toArray(new Holder[enums.size()]); + this.enums = enums.toArray(new Holder[0]); } @Override diff --git a/server/src/main/java/org/opensearch/common/lucene/search/XMoreLikeThis.java b/server/src/main/java/org/opensearch/common/lucene/search/XMoreLikeThis.java index 7149eeab8f3ed..49148890abd55 100644 --- a/server/src/main/java/org/opensearch/common/lucene/search/XMoreLikeThis.java +++ b/server/src/main/java/org/opensearch/common/lucene/search/XMoreLikeThis.java @@ -621,7 +621,7 @@ public Query like(int docNum) throws IOException { if (fieldNames == null) { // gather list of valid fields from lucene Collection fields = FieldInfos.getIndexedFields(ir); - fieldNames = fields.toArray(new String[fields.size()]); + fieldNames = fields.toArray(new String[0]); } return createQuery(retrieveTerms(docNum)); diff --git a/server/src/main/java/org/opensearch/common/network/NetworkService.java b/server/src/main/java/org/opensearch/common/network/NetworkService.java index 4721221879430..deec184f702bf 100644 --- a/server/src/main/java/org/opensearch/common/network/NetworkService.java +++ b/server/src/main/java/org/opensearch/common/network/NetworkService.java @@ -205,7 +205,7 @@ public InetAddress resolvePublishHostAddresses(String publishHosts[]) throws IOE // 1. single wildcard address, probably set by network.host: expand to all interface addresses. if (addresses.length == 1 && addresses[0].isAnyLocalAddress()) { HashSet all = new HashSet<>(Arrays.asList(NetworkUtils.getAllAddresses())); - addresses = all.toArray(new InetAddress[all.size()]); + addresses = all.toArray(new InetAddress[0]); } // 2. try to deal with some (mis)configuration @@ -248,7 +248,7 @@ private InetAddress[] resolveInetAddresses(String hosts[]) throws IOException { for (String host : hosts) { set.addAll(Arrays.asList(resolveInternal(host))); } - return set.toArray(new InetAddress[set.size()]); + return set.toArray(new InetAddress[0]); } /** resolves a single host specification */ diff --git a/server/src/main/java/org/opensearch/common/network/NetworkUtils.java b/server/src/main/java/org/opensearch/common/network/NetworkUtils.java index 8660b876fa187..8816260c5d26f 100644 --- a/server/src/main/java/org/opensearch/common/network/NetworkUtils.java +++ b/server/src/main/java/org/opensearch/common/network/NetworkUtils.java @@ -239,7 +239,7 @@ static InetAddress[] getAddressesForInterface(String name) throws SocketExceptio if (list.isEmpty()) { throw new IllegalArgumentException("Interface '" + name + "' has no internet addresses"); } - return list.toArray(new InetAddress[list.size()]); + return list.toArray(new InetAddress[0]); } /** Returns only the IPV4 addresses in {@code addresses} */ @@ -253,7 +253,7 @@ static InetAddress[] filterIPV4(InetAddress addresses[]) { if (list.isEmpty()) { throw new IllegalArgumentException("No ipv4 addresses found in " + Arrays.toString(addresses)); } - return list.toArray(new InetAddress[list.size()]); + return list.toArray(new InetAddress[0]); } /** Returns only the IPV6 addresses in {@code addresses} */ @@ -267,6 +267,6 @@ static InetAddress[] filterIPV6(InetAddress addresses[]) { if (list.isEmpty()) { throw new IllegalArgumentException("No ipv6 addresses found in " + Arrays.toString(addresses)); } - return list.toArray(new InetAddress[list.size()]); + return list.toArray(new InetAddress[0]); } } 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 c5ef4972d087d..0557884f0f8ad 100644 --- a/server/src/main/java/org/opensearch/common/settings/Settings.java +++ b/server/src/main/java/org/opensearch/common/settings/Settings.java @@ -1046,7 +1046,7 @@ public Builder put(Settings settings, boolean copySecureSettings) { } private void processLegacyLists(Map map) { - String[] array = map.keySet().toArray(new String[map.size()]); + String[] array = map.keySet().toArray(new String[0]); for (String key : array) { if (key.endsWith(".0")) { // let's only look at the head of the list and convert in order starting there. int counter = 0; diff --git a/server/src/main/java/org/opensearch/common/settings/SettingsFilter.java b/server/src/main/java/org/opensearch/common/settings/SettingsFilter.java index 1079a02f51c55..47e5454728fbf 100644 --- a/server/src/main/java/org/opensearch/common/settings/SettingsFilter.java +++ b/server/src/main/java/org/opensearch/common/settings/SettingsFilter.java @@ -117,7 +117,7 @@ private static Settings filterSettings(Iterable patterns, Settings setti } } if (!simpleMatchPatternList.isEmpty()) { - String[] simpleMatchPatterns = simpleMatchPatternList.toArray(new String[simpleMatchPatternList.size()]); + String[] simpleMatchPatterns = simpleMatchPatternList.toArray(new String[0]); builder.keys().removeIf(key -> Regex.simpleMatch(simpleMatchPatterns, key)); } return builder.build(); diff --git a/server/src/main/java/org/opensearch/common/util/concurrent/PrioritizedOpenSearchThreadPoolExecutor.java b/server/src/main/java/org/opensearch/common/util/concurrent/PrioritizedOpenSearchThreadPoolExecutor.java index 0cf8dc61c9254..95df4486b9d7b 100644 --- a/server/src/main/java/org/opensearch/common/util/concurrent/PrioritizedOpenSearchThreadPoolExecutor.java +++ b/server/src/main/java/org/opensearch/common/util/concurrent/PrioritizedOpenSearchThreadPoolExecutor.java @@ -81,7 +81,7 @@ public Pending[] getPending() { List pending = new ArrayList<>(); addPending(new ArrayList<>(current), pending, true); addPending(new ArrayList<>(getQueue()), pending, false); - return pending.toArray(new Pending[pending.size()]); + return pending.toArray(new Pending[0]); } public int getNumberOfPendingTasks() { diff --git a/server/src/main/java/org/opensearch/env/NodeEnvironment.java b/server/src/main/java/org/opensearch/env/NodeEnvironment.java index 0899fb1123bc4..80ab7448d8d09 100644 --- a/server/src/main/java/org/opensearch/env/NodeEnvironment.java +++ b/server/src/main/java/org/opensearch/env/NodeEnvironment.java @@ -1062,7 +1062,7 @@ public Path[] resolveIndexFolder(String indexFolderName) { paths.add(indexFolder); } } - return paths.toArray(new Path[paths.size()]); + return paths.toArray(new Path[0]); } /** diff --git a/server/src/main/java/org/opensearch/gateway/LocalAllocateDangledIndices.java b/server/src/main/java/org/opensearch/gateway/LocalAllocateDangledIndices.java index 3c5fb881a8a83..84290634359e3 100644 --- a/server/src/main/java/org/opensearch/gateway/LocalAllocateDangledIndices.java +++ b/server/src/main/java/org/opensearch/gateway/LocalAllocateDangledIndices.java @@ -113,10 +113,7 @@ public void allocateDangled(Collection indices, ActionListener stopWords) { if (stopWords == null) { throw new IllegalArgumentException("requires stopwords to be non-null"); } - this.stopWords = stopWords.toArray(new String[stopWords.size()]); + this.stopWords = stopWords.toArray(new String[0]); return this; } @@ -899,11 +899,11 @@ public static MoreLikeThisQueryBuilder fromXContent(XContentParser parser) throw throw new ParsingException(parser.getTokenLocation(), "more_like_this requires 'fields' to be non-empty"); } - String[] fieldsArray = fields == null ? null : fields.toArray(new String[fields.size()]); - String[] likeTextsArray = likeTexts.isEmpty() ? null : likeTexts.toArray(new String[likeTexts.size()]); - String[] unlikeTextsArray = unlikeTexts.isEmpty() ? null : unlikeTexts.toArray(new String[unlikeTexts.size()]); - Item[] likeItemsArray = likeItems.isEmpty() ? null : likeItems.toArray(new Item[likeItems.size()]); - Item[] unlikeItemsArray = unlikeItems.isEmpty() ? null : unlikeItems.toArray(new Item[unlikeItems.size()]); + String[] fieldsArray = fields == null ? null : fields.toArray(new String[0]); + String[] likeTextsArray = likeTexts.isEmpty() ? null : likeTexts.toArray(new String[0]); + String[] unlikeTextsArray = unlikeTexts.isEmpty() ? null : unlikeTexts.toArray(new String[0]); + Item[] likeItemsArray = likeItems.isEmpty() ? null : likeItems.toArray(new Item[0]); + Item[] unlikeItemsArray = unlikeItems.isEmpty() ? null : unlikeItems.toArray(new Item[0]); MoreLikeThisQueryBuilder moreLikeThisQueryBuilder = new MoreLikeThisQueryBuilder(fieldsArray, likeTextsArray, likeItemsArray) .unlike(unlikeTextsArray) @@ -1027,7 +1027,7 @@ protected Query doToQuery(QueryShardContext context) throws IOException { if (moreLikeFields.isEmpty()) { return null; } - mltQuery.setMoreLikeFields(moreLikeFields.toArray(new String[moreLikeFields.size()])); + mltQuery.setMoreLikeFields(moreLikeFields.toArray(new String[0])); // handle like texts if (likeTexts.length > 0) { @@ -1100,7 +1100,7 @@ private static void setDefaultIndexTypeFields( if (useDefaultField) { item.fields("*"); } else { - item.fields(moreLikeFields.toArray(new String[moreLikeFields.size()])); + item.fields(moreLikeFields.toArray(new String[0])); } } } diff --git a/server/src/main/java/org/opensearch/index/query/VectorGeoShapeQueryProcessor.java b/server/src/main/java/org/opensearch/index/query/VectorGeoShapeQueryProcessor.java index e11b22e9296cf..9703b7da35c7f 100644 --- a/server/src/main/java/org/opensearch/index/query/VectorGeoShapeQueryProcessor.java +++ b/server/src/main/java/org/opensearch/index/query/VectorGeoShapeQueryProcessor.java @@ -81,11 +81,7 @@ private Query getVectorQueryFromShape(Geometry queryShape, String fieldName, Sha if (geometries.size() == 0) { return new MatchNoDocsQuery(); } - return LatLonShape.newGeometryQuery( - fieldName, - relation.getLuceneRelation(), - geometries.toArray(new LatLonGeometry[geometries.size()]) - ); + return LatLonShape.newGeometryQuery(fieldName, relation.getLuceneRelation(), geometries.toArray(new LatLonGeometry[0])); } /** diff --git a/server/src/main/java/org/opensearch/index/query/functionscore/FunctionScoreQueryBuilder.java b/server/src/main/java/org/opensearch/index/query/functionscore/FunctionScoreQueryBuilder.java index 139d28cb6a7df..b3c797f11de6d 100644 --- a/server/src/main/java/org/opensearch/index/query/functionscore/FunctionScoreQueryBuilder.java +++ b/server/src/main/java/org/opensearch/index/query/functionscore/FunctionScoreQueryBuilder.java @@ -602,7 +602,7 @@ public static FunctionScoreQueryBuilder fromXContent(XContentParser parser) thro FunctionScoreQueryBuilder functionScoreQueryBuilder = new FunctionScoreQueryBuilder( query, - filterFunctionBuilders.toArray(new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()]) + filterFunctionBuilders.toArray(new FilterFunctionBuilder[0]) ); if (combineFunction != null) { functionScoreQueryBuilder.boostMode(combineFunction); diff --git a/server/src/main/java/org/opensearch/index/reindex/ReindexRequest.java b/server/src/main/java/org/opensearch/index/reindex/ReindexRequest.java index 03608c1b1e9af..393e01823024e 100644 --- a/server/src/main/java/org/opensearch/index/reindex/ReindexRequest.java +++ b/server/src/main/java/org/opensearch/index/reindex/ReindexRequest.java @@ -400,7 +400,7 @@ private static String[] extractStringArray(Map source, String na if (value instanceof List) { @SuppressWarnings("unchecked") List list = (List) value; - return list.toArray(new String[list.size()]); + return list.toArray(new String[0]); } else if (value instanceof String) { return Strings.splitStringByCommaToArray((String) value); } else { diff --git a/server/src/main/java/org/opensearch/index/shard/LocalShardSnapshot.java b/server/src/main/java/org/opensearch/index/shard/LocalShardSnapshot.java index ee96b31a3a727..a98fc2a3b4145 100644 --- a/server/src/main/java/org/opensearch/index/shard/LocalShardSnapshot.java +++ b/server/src/main/java/org/opensearch/index/shard/LocalShardSnapshot.java @@ -96,7 +96,7 @@ Directory getSnapshotDirectory() { @Override public String[] listAll() throws IOException { Collection fileNames = wrappedIndexCommit.get().getFileNames(); - final String[] fileNameArray = fileNames.toArray(new String[fileNames.size()]); + final String[] fileNameArray = fileNames.toArray(new String[0]); return fileNameArray; } diff --git a/server/src/main/java/org/opensearch/monitor/fs/FsProbe.java b/server/src/main/java/org/opensearch/monitor/fs/FsProbe.java index 4d85087aca6a8..db77ec7628e76 100644 --- a/server/src/main/java/org/opensearch/monitor/fs/FsProbe.java +++ b/server/src/main/java/org/opensearch/monitor/fs/FsProbe.java @@ -174,7 +174,7 @@ final FsInfo.IoStats ioStats(final Set> devicesNumbers, } } - return new FsInfo.IoStats(devicesStats.toArray(new FsInfo.DeviceStats[devicesStats.size()])); + return new FsInfo.IoStats(devicesStats.toArray(new FsInfo.DeviceStats[0])); } catch (Exception e) { // do not fail Elasticsearch if something unexpected // happens here diff --git a/server/src/main/java/org/opensearch/monitor/jvm/DeadlockAnalyzer.java b/server/src/main/java/org/opensearch/monitor/jvm/DeadlockAnalyzer.java index 12d749a2b9102..e48e036c1540b 100644 --- a/server/src/main/java/org/opensearch/monitor/jvm/DeadlockAnalyzer.java +++ b/server/src/main/java/org/opensearch/monitor/jvm/DeadlockAnalyzer.java @@ -81,7 +81,7 @@ private Deadlock[] createDeadlockDescriptions(Set> cyc Deadlock result[] = new Deadlock[cycles.size()]; int count = 0; for (LinkedHashSet cycle : cycles) { - ThreadInfo asArray[] = cycle.toArray(new ThreadInfo[cycle.size()]); + ThreadInfo asArray[] = cycle.toArray(new ThreadInfo[0]); Deadlock d = new Deadlock(asArray); result[count++] = d; } diff --git a/server/src/main/java/org/opensearch/monitor/jvm/JvmInfo.java b/server/src/main/java/org/opensearch/monitor/jvm/JvmInfo.java index 178e9aa7f4551..a62cffd656e37 100644 --- a/server/src/main/java/org/opensearch/monitor/jvm/JvmInfo.java +++ b/server/src/main/java/org/opensearch/monitor/jvm/JvmInfo.java @@ -81,7 +81,7 @@ public class JvmInfo implements ReportingService.Info { } catch (Exception t) { // ignore } - String[] inputArguments = runtimeMXBean.getInputArguments().toArray(new String[runtimeMXBean.getInputArguments().size()]); + String[] inputArguments = runtimeMXBean.getInputArguments().toArray(new String[0]); Mem mem = new Mem(heapInit, heapMax, nonHeapInit, nonHeapMax, directMemoryMax); String bootClassPath; diff --git a/server/src/main/java/org/opensearch/rest/action/document/RestTermVectorsAction.java b/server/src/main/java/org/opensearch/rest/action/document/RestTermVectorsAction.java index b7b75104adaad..ac1e0035b3ca3 100644 --- a/server/src/main/java/org/opensearch/rest/action/document/RestTermVectorsAction.java +++ b/server/src/main/java/org/opensearch/rest/action/document/RestTermVectorsAction.java @@ -123,7 +123,7 @@ public static void addFieldStringsFromParameter(TermVectorsRequest termVectorsRe } } if (selectedFields != null) { - termVectorsRequest.selectedFields(selectedFields.toArray(new String[selectedFields.size()])); + termVectorsRequest.selectedFields(selectedFields.toArray(new String[0])); } } diff --git a/server/src/main/java/org/opensearch/rest/action/search/RestGetAllPitsAction.java b/server/src/main/java/org/opensearch/rest/action/search/RestGetAllPitsAction.java index 809d65519c4f5..7e1e4da206ab8 100644 --- a/server/src/main/java/org/opensearch/rest/action/search/RestGetAllPitsAction.java +++ b/server/src/main/java/org/opensearch/rest/action/search/RestGetAllPitsAction.java @@ -54,7 +54,7 @@ protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient cli for (DiscoveryNode node : nodesInCluster.get()) { nodes.add(node); } - DiscoveryNode[] disNodesArr = nodes.toArray(new DiscoveryNode[nodes.size()]); + DiscoveryNode[] disNodesArr = nodes.toArray(new DiscoveryNode[0]); GetAllPitNodesRequest getAllPitNodesRequest = new GetAllPitNodesRequest(disNodesArr); return channel -> client.getAllPits(getAllPitNodesRequest, new RestBuilderListener(channel) { @Override diff --git a/server/src/main/java/org/opensearch/search/aggregations/MultiBucketCollector.java b/server/src/main/java/org/opensearch/search/aggregations/MultiBucketCollector.java index 8aad9db0248f1..9915848ee2e1d 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/MultiBucketCollector.java +++ b/server/src/main/java/org/opensearch/search/aggregations/MultiBucketCollector.java @@ -192,7 +192,7 @@ private static class MultiLeafBucketCollector extends LeafBucketCollector { private int numCollectors; private MultiLeafBucketCollector(List collectors, boolean cacheScores) { - this.collectors = collectors.toArray(new LeafBucketCollector[collectors.size()]); + this.collectors = collectors.toArray(new LeafBucketCollector[0]); this.cacheScores = cacheScores; this.numCollectors = this.collectors.length; } diff --git a/server/src/main/java/org/opensearch/search/aggregations/bucket/terms/SignificantTextAggregationBuilder.java b/server/src/main/java/org/opensearch/search/aggregations/bucket/terms/SignificantTextAggregationBuilder.java index b34c54ab54618..7e2c20c14dafb 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/bucket/terms/SignificantTextAggregationBuilder.java +++ b/server/src/main/java/org/opensearch/search/aggregations/bucket/terms/SignificantTextAggregationBuilder.java @@ -216,7 +216,7 @@ public SignificantTextAggregationBuilder fieldName(String fieldName) { * to also be the name of the JSON field holding the value */ public SignificantTextAggregationBuilder sourceFieldNames(List names) { - this.sourceFieldNames = names.toArray(new String[names.size()]); + this.sourceFieldNames = names.toArray(new String[0]); return this; } diff --git a/server/src/main/java/org/opensearch/search/aggregations/pipeline/BucketMetricsParser.java b/server/src/main/java/org/opensearch/search/aggregations/pipeline/BucketMetricsParser.java index 2e7bbd703b9d8..ba6fb92875057 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/pipeline/BucketMetricsParser.java +++ b/server/src/main/java/org/opensearch/search/aggregations/pipeline/BucketMetricsParser.java @@ -85,7 +85,7 @@ public final BucketMetricsPipelineAggregationBuilder parse(String pipelineAgg String path = parser.text(); paths.add(path); } - bucketsPaths = paths.toArray(new String[paths.size()]); + bucketsPaths = paths.toArray(new String[0]); } else { parseToken(pipelineAggregatorName, parser, currentFieldName, token, params); } diff --git a/server/src/main/java/org/opensearch/search/aggregations/pipeline/DerivativePipelineAggregationBuilder.java b/server/src/main/java/org/opensearch/search/aggregations/pipeline/DerivativePipelineAggregationBuilder.java index 8a4fed691ee98..e3996cd46b778 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/pipeline/DerivativePipelineAggregationBuilder.java +++ b/server/src/main/java/org/opensearch/search/aggregations/pipeline/DerivativePipelineAggregationBuilder.java @@ -223,7 +223,7 @@ public static DerivativePipelineAggregationBuilder parse(String pipelineAggregat String path = parser.text(); paths.add(path); } - bucketsPaths = paths.toArray(new String[paths.size()]); + bucketsPaths = paths.toArray(new String[0]); } else { throw new ParsingException( parser.getTokenLocation(), diff --git a/server/src/main/java/org/opensearch/search/aggregations/pipeline/MaxBucketPipelineAggregator.java b/server/src/main/java/org/opensearch/search/aggregations/pipeline/MaxBucketPipelineAggregator.java index ba8d3878eda48..c674076dd2c1d 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/pipeline/MaxBucketPipelineAggregator.java +++ b/server/src/main/java/org/opensearch/search/aggregations/pipeline/MaxBucketPipelineAggregator.java @@ -92,7 +92,7 @@ protected void collectBucketValue(String bucketKey, Double bucketValue) { @Override protected InternalAggregation buildAggregation(Map metadata) { - String[] keys = maxBucketKeys.toArray(new String[maxBucketKeys.size()]); + String[] keys = maxBucketKeys.toArray(new String[0]); return new InternalBucketMetricValue(name(), keys, maxValue, format, metadata()); } diff --git a/server/src/main/java/org/opensearch/search/aggregations/pipeline/MovAvgPipelineAggregationBuilder.java b/server/src/main/java/org/opensearch/search/aggregations/pipeline/MovAvgPipelineAggregationBuilder.java index e53ac003712ea..296a51f1ec248 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/pipeline/MovAvgPipelineAggregationBuilder.java +++ b/server/src/main/java/org/opensearch/search/aggregations/pipeline/MovAvgPipelineAggregationBuilder.java @@ -386,7 +386,7 @@ public static MovAvgPipelineAggregationBuilder parse( String path = parser.text(); paths.add(path); } - bucketsPaths = paths.toArray(new String[paths.size()]); + bucketsPaths = paths.toArray(new String[0]); } else { throw new ParsingException( parser.getTokenLocation(), diff --git a/server/src/main/java/org/opensearch/search/aggregations/pipeline/SerialDiffPipelineAggregationBuilder.java b/server/src/main/java/org/opensearch/search/aggregations/pipeline/SerialDiffPipelineAggregationBuilder.java index 628ac1bbfb16d..a3b1441fb058b 100644 --- a/server/src/main/java/org/opensearch/search/aggregations/pipeline/SerialDiffPipelineAggregationBuilder.java +++ b/server/src/main/java/org/opensearch/search/aggregations/pipeline/SerialDiffPipelineAggregationBuilder.java @@ -220,7 +220,7 @@ public static SerialDiffPipelineAggregationBuilder parse(String reducerName, XCo String path = parser.text(); paths.add(path); } - bucketsPaths = paths.toArray(new String[paths.size()]); + bucketsPaths = paths.toArray(new String[0]); } else { throw new ParsingException( parser.getTokenLocation(), diff --git a/server/src/main/java/org/opensearch/search/fetch/subphase/FetchSourceContext.java b/server/src/main/java/org/opensearch/search/fetch/subphase/FetchSourceContext.java index af7f5992cf398..337576890e663 100644 --- a/server/src/main/java/org/opensearch/search/fetch/subphase/FetchSourceContext.java +++ b/server/src/main/java/org/opensearch/search/fetch/subphase/FetchSourceContext.java @@ -152,7 +152,7 @@ public static FetchSourceContext fromXContent(XContentParser parser) throws IOEx while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { list.add(parser.text()); } - includes = list.toArray(new String[list.size()]); + includes = list.toArray(new String[0]); } else if (token == XContentParser.Token.START_OBJECT) { String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { @@ -172,7 +172,7 @@ public static FetchSourceContext fromXContent(XContentParser parser) throws IOEx ); } } - includes = includesList.toArray(new String[includesList.size()]); + includes = includesList.toArray(new String[0]); } else if (EXCLUDES_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { List excludesList = new ArrayList<>(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { @@ -186,7 +186,7 @@ public static FetchSourceContext fromXContent(XContentParser parser) throws IOEx ); } } - excludes = excludesList.toArray(new String[excludesList.size()]); + excludes = excludesList.toArray(new String[0]); } else { throw new ParsingException( parser.getTokenLocation(), diff --git a/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/HighlightField.java b/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/HighlightField.java index 61462228e812f..30effe2826d76 100644 --- a/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/HighlightField.java +++ b/server/src/main/java/org/opensearch/search/fetch/subphase/highlight/HighlightField.java @@ -139,7 +139,7 @@ public static HighlightField fromXContent(XContentParser parser) throws IOExcept while (parser.nextToken() != XContentParser.Token.END_ARRAY) { values.add(new Text(parser.text())); } - fragments = values.toArray(new Text[values.size()]); + fragments = values.toArray(new Text[0]); } else if (token == XContentParser.Token.VALUE_NULL) { fragments = null; } else { diff --git a/server/src/main/java/org/opensearch/search/sort/GeoDistanceSortBuilder.java b/server/src/main/java/org/opensearch/search/sort/GeoDistanceSortBuilder.java index e9fa013847aa4..0499bba3245c6 100644 --- a/server/src/main/java/org/opensearch/search/sort/GeoDistanceSortBuilder.java +++ b/server/src/main/java/org/opensearch/search/sort/GeoDistanceSortBuilder.java @@ -241,7 +241,7 @@ public GeoDistanceSortBuilder points(GeoPoint... points) { * Returns the points to create the range distance facets from. */ public GeoPoint[] points() { - return this.points.toArray(new GeoPoint[this.points.size()]); + return this.points.toArray(new GeoPoint[0]); } /** @@ -576,7 +576,7 @@ public static GeoDistanceSortBuilder fromXContent(XContentParser parser, String } } - GeoDistanceSortBuilder result = new GeoDistanceSortBuilder(fieldName, geoPoints.toArray(new GeoPoint[geoPoints.size()])); + GeoDistanceSortBuilder result = new GeoDistanceSortBuilder(fieldName, geoPoints.toArray(new GeoPoint[0])); result.geoDistance(geoDistance); result.unit(unit); result.order(order); @@ -644,7 +644,7 @@ public BucketedSort buildBucketedSort(QueryShardContext context, int bucketSize, private GeoPoint[] localPoints() { // validation was not available prior to 2.x, so to support bwc percolation queries we only ignore_malformed // on 2.x created indexes - GeoPoint[] localPoints = points.toArray(new GeoPoint[points.size()]); + GeoPoint[] localPoints = points.toArray(new GeoPoint[0]); if (GeoValidationMethod.isIgnoreMalformed(validation) == false) { for (GeoPoint point : localPoints) { if (GeoUtils.isValidLatitude(point.lat()) == false) { 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 501ea811a073c..a8c21e7311061 100644 --- a/server/src/main/java/org/opensearch/search/sort/SortBuilder.java +++ b/server/src/main/java/org/opensearch/search/sort/SortBuilder.java @@ -185,10 +185,7 @@ public static Optional buildSort(List> sortBuilde } if (sort) { return Optional.of( - new SortAndFormats( - new Sort(sortFields.toArray(new SortField[sortFields.size()])), - sortFormats.toArray(new DocValueFormat[sortFormats.size()]) - ) + new SortAndFormats(new Sort(sortFields.toArray(new SortField[0])), sortFormats.toArray(new DocValueFormat[0])) ); } } diff --git a/server/src/main/java/org/opensearch/search/suggest/phrase/DirectCandidateGenerator.java b/server/src/main/java/org/opensearch/search/suggest/phrase/DirectCandidateGenerator.java index 225d212d6e77c..1a00cb9465771 100644 --- a/server/src/main/java/org/opensearch/search/suggest/phrase/DirectCandidateGenerator.java +++ b/server/src/main/java/org/opensearch/search/suggest/phrase/DirectCandidateGenerator.java @@ -324,7 +324,7 @@ public void addCandidates(List candidates) { final Set set = new HashSet<>(candidates); Collections.addAll(set, this.candidates); - this.candidates = set.toArray(new Candidate[set.size()]); + this.candidates = set.toArray(new Candidate[0]); // Sort strongest to weakest: Arrays.sort(this.candidates, Collections.reverseOrder()); } diff --git a/server/src/main/java/org/opensearch/search/suggest/phrase/NoisyChannelSpellChecker.java b/server/src/main/java/org/opensearch/search/suggest/phrase/NoisyChannelSpellChecker.java index 49790c996371a..e8ba90f353f02 100644 --- a/server/src/main/java/org/opensearch/search/suggest/phrase/NoisyChannelSpellChecker.java +++ b/server/src/main/java/org/opensearch/search/suggest/phrase/NoisyChannelSpellChecker.java @@ -129,7 +129,7 @@ public void end() { } double cutoffScore = Double.MIN_VALUE; CandidateScorer scorer = new CandidateScorer(wordScorer, numCorrections, gramSize); - CandidateSet[] candidateSets = candidateSetsList.toArray(new CandidateSet[candidateSetsList.size()]); + CandidateSet[] candidateSets = candidateSetsList.toArray(new CandidateSet[0]); if (confidence > 0.0) { Candidate[] candidates = new Candidate[candidateSets.length]; for (int i = 0; i < candidates.length; i++) { diff --git a/server/src/main/java/org/opensearch/search/suggest/phrase/PhraseSuggester.java b/server/src/main/java/org/opensearch/search/suggest/phrase/PhraseSuggester.java index dd3e17ae5b42b..09862e42b5819 100644 --- a/server/src/main/java/org/opensearch/search/suggest/phrase/PhraseSuggester.java +++ b/server/src/main/java/org/opensearch/search/suggest/phrase/PhraseSuggester.java @@ -133,7 +133,7 @@ public Suggestion> innerExecute( try (TokenStream stream = tokenStream(suggestion.getAnalyzer(), suggestion.getText(), spare, suggestion.getField())) { checkerResult = checker.getCorrections( stream, - new MultiCandidateGeneratorWrapper(suggestion.getShardSize(), gens.toArray(new CandidateGenerator[gens.size()])), + new MultiCandidateGeneratorWrapper(suggestion.getShardSize(), gens.toArray(new CandidateGenerator[0])), suggestion.maxErrors(), suggestion.getShardSize(), wordScorer, diff --git a/server/src/main/java/org/opensearch/snapshots/SnapshotInfo.java b/server/src/main/java/org/opensearch/snapshots/SnapshotInfo.java index 15c75db67551d..fd47b778e653a 100644 --- a/server/src/main/java/org/opensearch/snapshots/SnapshotInfo.java +++ b/server/src/main/java/org/opensearch/snapshots/SnapshotInfo.java @@ -688,11 +688,7 @@ public RestStatus status() { if (shardFailures.size() == 0) { return RestStatus.OK; } - return RestStatus.status( - successfulShards, - totalShards, - shardFailures.toArray(new ShardOperationFailedException[shardFailures.size()]) - ); + return RestStatus.status(successfulShards, totalShards, shardFailures.toArray(new ShardOperationFailedException[0])); } @Override 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 e99207891beee..64aa7dc173937 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 @@ -684,7 +684,7 @@ protected String[] filterNodeIds(DiscoveryNodes nodes, String[] nodesIds) { filteredNodes.add(node); } } - return filteredNodes.toArray(new String[filteredNodes.size()]); + return filteredNodes.toArray(new String[0]); } @Override diff --git a/server/src/test/java/org/opensearch/action/admin/cluster/shards/ClusterSearchShardsResponseTests.java b/server/src/test/java/org/opensearch/action/admin/cluster/shards/ClusterSearchShardsResponseTests.java index d1e6d7d2353a5..2f911f30065bc 100644 --- a/server/src/test/java/org/opensearch/action/admin/cluster/shards/ClusterSearchShardsResponseTests.java +++ b/server/src/test/java/org/opensearch/action/admin/cluster/shards/ClusterSearchShardsResponseTests.java @@ -88,7 +88,7 @@ public void testSerialization() throws Exception { } ClusterSearchShardsResponse clusterSearchShardsResponse = new ClusterSearchShardsResponse( clusterSearchShardsGroups, - nodes.toArray(new DiscoveryNode[nodes.size()]), + nodes.toArray(new DiscoveryNode[0]), indicesAndFilters ); diff --git a/server/src/test/java/org/opensearch/action/admin/indices/rollover/TransportRolloverActionTests.java b/server/src/test/java/org/opensearch/action/admin/indices/rollover/TransportRolloverActionTests.java index d3167a6a426ff..fb4e955e95ab9 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/rollover/TransportRolloverActionTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/rollover/TransportRolloverActionTests.java @@ -426,7 +426,7 @@ public static IndicesStatsResponse randomIndicesStatsResponse(final IndexMetadat } } return IndicesStatsTests.newIndicesStatsResponse( - shardStats.toArray(new ShardStats[shardStats.size()]), + shardStats.toArray(new ShardStats[0]), shardStats.size(), shardStats.size(), 0, diff --git a/server/src/test/java/org/opensearch/action/admin/indices/stats/IndicesStatsResponseTests.java b/server/src/test/java/org/opensearch/action/admin/indices/stats/IndicesStatsResponseTests.java index 91968e84c13dc..2b79e523fc620 100644 --- a/server/src/test/java/org/opensearch/action/admin/indices/stats/IndicesStatsResponseTests.java +++ b/server/src/test/java/org/opensearch/action/admin/indices/stats/IndicesStatsResponseTests.java @@ -100,13 +100,7 @@ public void testGetIndices() { shardsCounter.incrementAndGet(); } } - final IndicesStatsResponse indicesStatsResponse = new IndicesStatsResponse( - shards.toArray(new ShardStats[shards.size()]), - 0, - 0, - 0, - null - ); + final IndicesStatsResponse indicesStatsResponse = new IndicesStatsResponse(shards.toArray(new ShardStats[0]), 0, 0, 0, null); Map indexStats = indicesStatsResponse.getIndices(); assertThat(indexStats.size(), is(noOfIndexes)); 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 1c75b3348b194..fe6dfb7a58eae 100644 --- a/server/src/test/java/org/opensearch/action/bulk/BulkRequestModifierTests.java +++ b/server/src/test/java/org/opensearch/action/bulk/BulkRequestModifierTests.java @@ -130,7 +130,7 @@ public void onFailure(Exception e) {} IndexResponse indexResponse = new IndexResponse(new ShardId("index", "_na_", 0), indexRequest.id(), 1, 17, 1, true); originalResponses.add(new BulkItemResponse(Integer.parseInt(indexRequest.id()), indexRequest.opType(), indexResponse)); } - bulkResponseListener.onResponse(new BulkResponse(originalResponses.toArray(new BulkItemResponse[originalResponses.size()]), 0)); + bulkResponseListener.onResponse(new BulkResponse(originalResponses.toArray(new BulkItemResponse[0]), 0)); assertThat(responses.size(), Matchers.equalTo(32)); for (int i = 0; i < 32; i++) { diff --git a/server/src/test/java/org/opensearch/action/support/nodes/TransportNodesActionTests.java b/server/src/test/java/org/opensearch/action/support/nodes/TransportNodesActionTests.java index f355b59a31265..d1ea8c11299fc 100644 --- a/server/src/test/java/org/opensearch/action/support/nodes/TransportNodesActionTests.java +++ b/server/src/test/java/org/opensearch/action/support/nodes/TransportNodesActionTests.java @@ -110,7 +110,7 @@ public void testNodesSelectors() { String nodeId = randomFrom(nodeIds); nodeSelectors.add(nodeId); } - String[] finalNodesIds = nodeSelectors.toArray(new String[nodeSelectors.size()]); + String[] finalNodesIds = nodeSelectors.toArray(new String[0]); TestNodesRequest request = new TestNodesRequest(finalNodesIds); action.new AsyncAction(null, request, new PlainActionFuture<>()).start(); Map> capturedRequests = transport.getCapturedRequestsByTargetNodeAndClear(); diff --git a/server/src/test/java/org/opensearch/action/termvectors/AbstractTermVectorsTestCase.java b/server/src/test/java/org/opensearch/action/termvectors/AbstractTermVectorsTestCase.java index 0d461a01d2f4a..e84b5213be39e 100644 --- a/server/src/test/java/org/opensearch/action/termvectors/AbstractTermVectorsTestCase.java +++ b/server/src/test/java/org/opensearch/action/termvectors/AbstractTermVectorsTestCase.java @@ -325,7 +325,7 @@ protected TestConfig[] generateTestConfigs(int numberOfTests, TestDoc[] testDocs refresh(); - return configs.toArray(new TestConfig[configs.size()]); + return configs.toArray(new TestConfig[0]); } protected TestFieldSetting[] getFieldSettings() { diff --git a/server/src/test/java/org/opensearch/cluster/node/DiscoveryNodesTests.java b/server/src/test/java/org/opensearch/cluster/node/DiscoveryNodesTests.java index 19c5464b6d3b7..9baf2e8c8180e 100644 --- a/server/src/test/java/org/opensearch/cluster/node/DiscoveryNodesTests.java +++ b/server/src/test/java/org/opensearch/cluster/node/DiscoveryNodesTests.java @@ -170,9 +170,9 @@ public void testResolveNodesIds() { expectedNodeIdsSet.add(discoveryNode.getId()); } - String[] resolvedNodesIds = discoveryNodes.resolveNodes(nodeSelectors.toArray(new String[nodeSelectors.size()])); + String[] resolvedNodesIds = discoveryNodes.resolveNodes(nodeSelectors.toArray(new String[0])); Arrays.sort(resolvedNodesIds); - String[] expectedNodesIds = expectedNodeIdsSet.toArray(new String[expectedNodeIdsSet.size()]); + String[] expectedNodesIds = expectedNodeIdsSet.toArray(new String[0]); Arrays.sort(expectedNodesIds); assertThat(resolvedNodesIds, equalTo(expectedNodesIds)); } diff --git a/server/src/test/java/org/opensearch/cluster/routing/allocation/FailedNodeRoutingTests.java b/server/src/test/java/org/opensearch/cluster/routing/allocation/FailedNodeRoutingTests.java index 02188ba116c46..c245e608edbec 100644 --- a/server/src/test/java/org/opensearch/cluster/routing/allocation/FailedNodeRoutingTests.java +++ b/server/src/test/java/org/opensearch/cluster/routing/allocation/FailedNodeRoutingTests.java @@ -261,7 +261,7 @@ public ClusterState randomInitialClusterState() { for (int i = 0; i < randomIntBetween(2, 5); i++) { allNodes.add(createNode()); } - ClusterState state = ClusterStateCreationUtils.state(localNode, localNode, allNodes.toArray(new DiscoveryNode[allNodes.size()])); + ClusterState state = ClusterStateCreationUtils.state(localNode, localNode, allNodes.toArray(new DiscoveryNode[0])); return state; } diff --git a/server/src/test/java/org/opensearch/cluster/serialization/DiffableTests.java b/server/src/test/java/org/opensearch/cluster/serialization/DiffableTests.java index 395dbcbc1055e..968d6beedd802 100644 --- a/server/src/test/java/org/opensearch/cluster/serialization/DiffableTests.java +++ b/server/src/test/java/org/opensearch/cluster/serialization/DiffableTests.java @@ -114,10 +114,7 @@ public abstract class MapDriver { protected final Set keysToRemove = new HashSet<>(randomSubsetOf(randomInt(keys.size()), keys.toArray(new Integer[0]))); protected final Set keysThatAreNotRemoved = Sets.difference(keys, keysToRemove); protected final Set keysToOverride = new HashSet<>( - randomSubsetOf( - randomInt(keysThatAreNotRemoved.size()), - keysThatAreNotRemoved.toArray(new Integer[keysThatAreNotRemoved.size()]) - ) + randomSubsetOf(randomInt(keysThatAreNotRemoved.size()), keysThatAreNotRemoved.toArray(new Integer[0])) ); // make sure keysToAdd does not contain elements in keys protected final Set keysToAdd = Sets.difference(randomPositiveIntSet(), keys); diff --git a/server/src/test/java/org/opensearch/common/geo/GeoJsonShapeParserTests.java b/server/src/test/java/org/opensearch/common/geo/GeoJsonShapeParserTests.java index 73e48d42b0270..e16dd859ec14c 100644 --- a/server/src/test/java/org/opensearch/common/geo/GeoJsonShapeParserTests.java +++ b/server/src/test/java/org/opensearch/common/geo/GeoJsonShapeParserTests.java @@ -352,7 +352,7 @@ public void testParsePolygon() throws IOException, ParseException { shellCoordinates.add(new Coordinate(101, 1)); shellCoordinates.add(new Coordinate(100, 1)); shellCoordinates.add(new Coordinate(100, 0)); - Coordinate[] coordinates = shellCoordinates.toArray(new Coordinate[shellCoordinates.size()]); + Coordinate[] coordinates = shellCoordinates.toArray(new Coordinate[0]); LinearRing shell = GEOMETRY_FACTORY.createLinearRing(coordinates); Polygon expected = GEOMETRY_FACTORY.createPolygon(shell, null); assertGeometryEquals(jtsGeom(expected), polygonGeoJson, true); @@ -404,7 +404,7 @@ public void testParse3DPolygon() throws IOException, ParseException { shellCoordinates.add(new Coordinate(101, 1, 10)); shellCoordinates.add(new Coordinate(100, 1, 10)); shellCoordinates.add(new Coordinate(100, 0, 10)); - Coordinate[] coordinates = shellCoordinates.toArray(new Coordinate[shellCoordinates.size()]); + Coordinate[] coordinates = shellCoordinates.toArray(new Coordinate[0]); Version randomVersion = VersionUtils.randomIndexCompatibleVersion(random()); Settings indexSettings = Settings.builder() @@ -414,7 +414,7 @@ public void testParse3DPolygon() throws IOException, ParseException { .put(IndexMetadata.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()) .build(); - LinearRing shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[shellCoordinates.size()])); + LinearRing shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[0])); Polygon expected = GEOMETRY_FACTORY.createPolygon(shell, null); Mapper.BuilderContext mockBuilderContext = new Mapper.BuilderContext(indexSettings, new ContentPath()); final LegacyGeoShapeFieldMapper mapperBuilder = (LegacyGeoShapeFieldMapper) (new LegacyGeoShapeFieldMapper.Builder("test") @@ -1377,9 +1377,9 @@ public void testParsePolygonWithHole() throws IOException, ParseException { holeCoordinates.add(new Coordinate(100.2, 0.8)); holeCoordinates.add(new Coordinate(100.2, 0.2)); - LinearRing shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[shellCoordinates.size()])); + LinearRing shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[0])); LinearRing[] holes = new LinearRing[1]; - holes[0] = GEOMETRY_FACTORY.createLinearRing(holeCoordinates.toArray(new Coordinate[holeCoordinates.size()])); + holes[0] = GEOMETRY_FACTORY.createLinearRing(holeCoordinates.toArray(new Coordinate[0])); Polygon expected = GEOMETRY_FACTORY.createPolygon(shell, holes); assertGeometryEquals(jtsGeom(expected), polygonGeoJson, true); @@ -1561,9 +1561,9 @@ public void testParseMultiPolygon() throws IOException, ParseException { holeCoordinates.add(new Coordinate(100.2, 0.8)); holeCoordinates.add(new Coordinate(100.2, 0.2)); - LinearRing shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[shellCoordinates.size()])); + LinearRing shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[0])); LinearRing[] holes = new LinearRing[1]; - holes[0] = GEOMETRY_FACTORY.createLinearRing(holeCoordinates.toArray(new Coordinate[holeCoordinates.size()])); + holes[0] = GEOMETRY_FACTORY.createLinearRing(holeCoordinates.toArray(new Coordinate[0])); Polygon withHoles = GEOMETRY_FACTORY.createPolygon(shell, holes); shellCoordinates = new ArrayList<>(); @@ -1573,7 +1573,7 @@ public void testParseMultiPolygon() throws IOException, ParseException { shellCoordinates.add(new Coordinate(102, 2)); shellCoordinates.add(new Coordinate(102, 3)); - shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[shellCoordinates.size()])); + shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[0])); Polygon withoutHoles = GEOMETRY_FACTORY.createPolygon(shell, null); Shape expected = shapeCollection(withoutHoles, withHoles); @@ -1675,9 +1675,9 @@ public void testParseMultiPolygon() throws IOException, ParseException { holeCoordinates.add(new Coordinate(100.8, 0.8)); holeCoordinates.add(new Coordinate(100.2, 0.8)); - shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[shellCoordinates.size()])); + shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[0])); holes = new LinearRing[1]; - holes[0] = GEOMETRY_FACTORY.createLinearRing(holeCoordinates.toArray(new Coordinate[holeCoordinates.size()])); + holes[0] = GEOMETRY_FACTORY.createLinearRing(holeCoordinates.toArray(new Coordinate[0])); withHoles = GEOMETRY_FACTORY.createPolygon(shell, holes); assertGeometryEquals(jtsGeom(withHoles), multiPolygonGeoJson, true); @@ -1776,8 +1776,8 @@ public void testParseGeometryCollection() throws IOException, ParseException { expected[0] = jtsGeom(expectedLineString); Point expectedPoint = GEOMETRY_FACTORY.createPoint(new Coordinate(102.0, 2.0)); expected[1] = new JtsPoint(expectedPoint, SPATIAL_CONTEXT); - LinearRing shell1 = GEOMETRY_FACTORY.createLinearRing(shellCoordinates1.toArray(new Coordinate[shellCoordinates1.size()])); - LinearRing shell2 = GEOMETRY_FACTORY.createLinearRing(shellCoordinates2.toArray(new Coordinate[shellCoordinates2.size()])); + LinearRing shell1 = GEOMETRY_FACTORY.createLinearRing(shellCoordinates1.toArray(new Coordinate[0])); + LinearRing shell2 = GEOMETRY_FACTORY.createLinearRing(shellCoordinates2.toArray(new Coordinate[0])); MultiPolygon expectedMultiPoly = GEOMETRY_FACTORY.createMultiPolygon( new Polygon[] { GEOMETRY_FACTORY.createPolygon(shell1), GEOMETRY_FACTORY.createPolygon(shell2) } ); diff --git a/server/src/test/java/org/opensearch/common/geo/GeoWKTShapeParserTests.java b/server/src/test/java/org/opensearch/common/geo/GeoWKTShapeParserTests.java index 3da6d633bb125..5b5f053572b8b 100644 --- a/server/src/test/java/org/opensearch/common/geo/GeoWKTShapeParserTests.java +++ b/server/src/test/java/org/opensearch/common/geo/GeoWKTShapeParserTests.java @@ -181,7 +181,7 @@ private List randomLineStringCoords() { @Override public void testParseLineString() throws IOException, ParseException { List coordinates = randomLineStringCoords(); - LineString expected = GEOMETRY_FACTORY.createLineString(coordinates.toArray(new Coordinate[coordinates.size()])); + LineString expected = GEOMETRY_FACTORY.createLineString(coordinates.toArray(new Coordinate[0])); assertExpected(jtsGeom(expected), new LineStringBuilder(coordinates), true); double[] lats = new double[coordinates.size()]; @@ -200,7 +200,7 @@ public void testParseMultiLineString() throws IOException, ParseException { MultiLineStringBuilder builder = new MultiLineStringBuilder(); for (int j = 0; j < numLineStrings; ++j) { List lsc = randomLineStringCoords(); - Coordinate[] coords = lsc.toArray(new Coordinate[lsc.size()]); + Coordinate[] coords = lsc.toArray(new Coordinate[0]); lineStrings.add(GEOMETRY_FACTORY.createLineString(coords)); builder.linestring(new LineStringBuilder(lsc)); } @@ -221,7 +221,7 @@ public void testParseMultiLineString() throws IOException, ParseException { assertExpected(expectedGeom, builder, false); assertMalformed(builder); - MultiLineString expected = GEOMETRY_FACTORY.createMultiLineString(lineStrings.toArray(new LineString[lineStrings.size()])); + MultiLineString expected = GEOMETRY_FACTORY.createMultiLineString(lineStrings.toArray(new LineString[0])); assumeTrue("JTS test path cannot handle empty multilinestrings", numLineStrings > 1); assertExpected(jtsGeom(expected), builder, true); } @@ -279,9 +279,9 @@ public void testParsePolygonWithHole() throws IOException, ParseException { PolygonBuilder polygonWithHole = new PolygonBuilder(new CoordinatesBuilder().coordinates(shellCoordinates)); polygonWithHole.hole(new LineStringBuilder(holeCoordinates)); - LinearRing shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[shellCoordinates.size()])); + LinearRing shell = GEOMETRY_FACTORY.createLinearRing(shellCoordinates.toArray(new Coordinate[0])); LinearRing[] holes = new LinearRing[1]; - holes[0] = GEOMETRY_FACTORY.createLinearRing(holeCoordinates.toArray(new Coordinate[holeCoordinates.size()])); + holes[0] = GEOMETRY_FACTORY.createLinearRing(holeCoordinates.toArray(new Coordinate[0])); Polygon expected = GEOMETRY_FACTORY.createPolygon(shell, holes); assertExpected(jtsGeom(expected), polygonWithHole, true); 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 c94d667bfe9f4..be194c070135a 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 @@ -74,13 +74,13 @@ protected void testFilter(Builder expected, Builder actual, Set includes if (includes == null) { sourceIncludes = randomBoolean() ? Strings.EMPTY_ARRAY : null; } else { - sourceIncludes = includes.toArray(new String[includes.size()]); + sourceIncludes = includes.toArray(new String[0]); } String[] sourceExcludes; if (excludes == null) { sourceExcludes = randomBoolean() ? Strings.EMPTY_ARRAY : null; } else { - sourceExcludes = excludes.toArray(new String[excludes.size()]); + sourceExcludes = excludes.toArray(new String[0]); } assertEquals( diff --git a/server/src/test/java/org/opensearch/env/NodeEnvironmentTests.java b/server/src/test/java/org/opensearch/env/NodeEnvironmentTests.java index dcb0623603d60..962eb743dca6e 100644 --- a/server/src/test/java/org/opensearch/env/NodeEnvironmentTests.java +++ b/server/src/test/java/org/opensearch/env/NodeEnvironmentTests.java @@ -266,7 +266,7 @@ public void testResolveIndexFolders() throws Exception { } for (Map.Entry> actualIndexDataPathEntry : actualIndexDataPaths.entrySet()) { List actual = actualIndexDataPathEntry.getValue(); - Path[] actualPaths = actual.toArray(new Path[actual.size()]); + Path[] actualPaths = actual.toArray(new Path[0]); assertThat(actualPaths, equalTo(env.resolveIndexFolder(actualIndexDataPathEntry.getKey()))); } assertTrue("LockedShards: " + env.lockedShards(), env.lockedShards().isEmpty()); diff --git a/server/src/test/java/org/opensearch/index/query/MoreLikeThisQueryBuilderTests.java b/server/src/test/java/org/opensearch/index/query/MoreLikeThisQueryBuilderTests.java index 02c6ad46653d6..b6449ef0332e1 100644 --- a/server/src/test/java/org/opensearch/index/query/MoreLikeThisQueryBuilderTests.java +++ b/server/src/test/java/org/opensearch/index/query/MoreLikeThisQueryBuilderTests.java @@ -245,10 +245,7 @@ protected MultiTermVectorsResponse executeMultiTermVectors(MultiTermVectorsReque if (request.doc() != null) { generatedFields = generateFields(randomFields, request.doc().utf8ToString()); } else { - generatedFields = generateFields( - request.selectedFields().toArray(new String[request.selectedFields().size()]), - request.id() - ); + generatedFields = generateFields(request.selectedFields().toArray(new String[0]), request.id()); } EnumSet flags = EnumSet.of(TermVectorsRequest.Flag.Positions, TermVectorsRequest.Flag.Offsets); response.setFields(generatedFields, request.selectedFields(), flags, generatedFields); diff --git a/server/src/test/java/org/opensearch/index/query/RegexpQueryBuilderTests.java b/server/src/test/java/org/opensearch/index/query/RegexpQueryBuilderTests.java index 47bdf3ccaf77c..30c8c07fa2c27 100644 --- a/server/src/test/java/org/opensearch/index/query/RegexpQueryBuilderTests.java +++ b/server/src/test/java/org/opensearch/index/query/RegexpQueryBuilderTests.java @@ -57,7 +57,7 @@ protected RegexpQueryBuilder doCreateTestQueryBuilder() { for (int i = 0; i < iter; i++) { flags.add(randomFrom(RegexpFlag.values())); } - query.flags(flags.toArray(new RegexpFlag[flags.size()])); + query.flags(flags.toArray(new RegexpFlag[0])); } if (randomBoolean()) { query.caseInsensitive(true); diff --git a/server/src/test/java/org/opensearch/index/query/SimpleQueryStringBuilderTests.java b/server/src/test/java/org/opensearch/index/query/SimpleQueryStringBuilderTests.java index 859a970b02a02..7688772173b08 100644 --- a/server/src/test/java/org/opensearch/index/query/SimpleQueryStringBuilderTests.java +++ b/server/src/test/java/org/opensearch/index/query/SimpleQueryStringBuilderTests.java @@ -109,7 +109,7 @@ protected SimpleQueryStringBuilder doCreateTestQueryBuilder() { flagSet.add(randomFrom(SimpleQueryStringFlag.values())); } if (flagSet.size() > 0) { - result.flags(flagSet.toArray(new SimpleQueryStringFlag[flagSet.size()])); + result.flags(flagSet.toArray(new SimpleQueryStringFlag[0])); } } diff --git a/server/src/test/java/org/opensearch/index/query/TermsQueryBuilderTests.java b/server/src/test/java/org/opensearch/index/query/TermsQueryBuilderTests.java index ce3eeb0e3bf69..cfe9fed3bc97c 100644 --- a/server/src/test/java/org/opensearch/index/query/TermsQueryBuilderTests.java +++ b/server/src/test/java/org/opensearch/index/query/TermsQueryBuilderTests.java @@ -244,7 +244,7 @@ public GetResponse executeGet(GetRequest getRequest) { try { XContentBuilder builder = XContentFactory.jsonBuilder().prettyPrint(); builder.startObject(); - builder.array(termsPath, randomTerms.toArray(new Object[randomTerms.size()])); + builder.array(termsPath, randomTerms.toArray(new Object[0])); builder.endObject(); json = builder.toString(); } catch (IOException ex) { diff --git a/server/src/test/java/org/opensearch/index/seqno/LocalCheckpointTrackerTests.java b/server/src/test/java/org/opensearch/index/seqno/LocalCheckpointTrackerTests.java index 88c5e2b49b900..c8f67a99f74be 100644 --- a/server/src/test/java/org/opensearch/index/seqno/LocalCheckpointTrackerTests.java +++ b/server/src/test/java/org/opensearch/index/seqno/LocalCheckpointTrackerTests.java @@ -235,7 +235,7 @@ public void testConcurrentReplica() throws InterruptedException { seqNoPerThread[t] = randomSubsetOf(size, seqNos).toArray(new Integer[size]); seqNos.removeAll(Arrays.asList(seqNoPerThread[t])); } - seqNoPerThread[threads.length - 1] = seqNos.toArray(new Integer[seqNos.size()]); + seqNoPerThread[threads.length - 1] = seqNos.toArray(new Integer[0]); logger.info("--> will run [{}] threads, maxOps [{}], unfinished seq no [{}]", threads.length, maxOps, unFinishedSeq); final CyclicBarrier barrier = new CyclicBarrier(threads.length); for (int t = 0; t < threads.length; t++) { diff --git a/server/src/test/java/org/opensearch/index/translog/SnapshotMatchers.java b/server/src/test/java/org/opensearch/index/translog/SnapshotMatchers.java index c9de270cf7568..dbca53640d9fd 100644 --- a/server/src/test/java/org/opensearch/index/translog/SnapshotMatchers.java +++ b/server/src/test/java/org/opensearch/index/translog/SnapshotMatchers.java @@ -68,7 +68,7 @@ public static Matcher equalsTo(Translog.Operation... ops) { * Consumes a snapshot and make sure it's content is as expected */ public static Matcher equalsTo(List ops) { - return new EqualMatcher(ops.toArray(new Translog.Operation[ops.size()])); + return new EqualMatcher(ops.toArray(new Translog.Operation[0])); } public static Matcher containsOperationsInAnyOrder(Collection expectedOperations) { diff --git a/server/src/test/java/org/opensearch/indices/cluster/IndicesClusterStateServiceRandomUpdatesTests.java b/server/src/test/java/org/opensearch/indices/cluster/IndicesClusterStateServiceRandomUpdatesTests.java index 6ba49e74196ee..22bf337b05598 100644 --- a/server/src/test/java/org/opensearch/indices/cluster/IndicesClusterStateServiceRandomUpdatesTests.java +++ b/server/src/test/java/org/opensearch/indices/cluster/IndicesClusterStateServiceRandomUpdatesTests.java @@ -339,7 +339,7 @@ public ClusterState randomInitialClusterState( for (int i = 0; i < randomIntBetween(2, 5); i++) { allNodes.add(createNode()); } - ClusterState state = ClusterStateCreationUtils.state(localNode, localNode, allNodes.toArray(new DiscoveryNode[allNodes.size()])); + ClusterState state = ClusterStateCreationUtils.state(localNode, localNode, allNodes.toArray(new DiscoveryNode[0])); // add nodes to clusterStateServiceMap updateNodes(state, clusterStateServiceMap, indicesServiceSupplier); return state; @@ -421,7 +421,7 @@ public ClusterState randomlyUpdateClusterState( indicesToDelete.add(state.metadata().index(index).getIndex().getName()); } if (indicesToDelete.isEmpty() == false) { - DeleteIndexRequest deleteRequest = new DeleteIndexRequest(indicesToDelete.toArray(new String[indicesToDelete.size()])); + DeleteIndexRequest deleteRequest = new DeleteIndexRequest(indicesToDelete.toArray(new String[0])); state = cluster.deleteIndices(state, deleteRequest); for (String index : indicesToDelete) { assertFalse(state.metadata().hasIndex(index)); @@ -453,9 +453,7 @@ public ClusterState randomlyUpdateClusterState( } } if (indicesToUpdate.isEmpty() == false) { - UpdateSettingsRequest updateSettingsRequest = new UpdateSettingsRequest( - indicesToUpdate.toArray(new String[indicesToUpdate.size()]) - ); + UpdateSettingsRequest updateSettingsRequest = new UpdateSettingsRequest(indicesToUpdate.toArray(new String[0])); Settings.Builder settings = Settings.builder(); if (containsClosedIndex == false) { settings.put(SETTING_NUMBER_OF_REPLICAS, randomInt(2)); diff --git a/server/src/test/java/org/opensearch/indices/store/IndicesStoreTests.java b/server/src/test/java/org/opensearch/indices/store/IndicesStoreTests.java index 40c5a631ce5d9..79434e1b23e9d 100644 --- a/server/src/test/java/org/opensearch/indices/store/IndicesStoreTests.java +++ b/server/src/test/java/org/opensearch/indices/store/IndicesStoreTests.java @@ -56,7 +56,7 @@ public class IndicesStoreTests extends OpenSearchTestCase { Set set = new HashSet<>(); set.addAll(Arrays.asList(ShardRoutingState.values())); set.remove(ShardRoutingState.STARTED); - NOT_STARTED_STATES = set.toArray(new ShardRoutingState[set.size()]); + NOT_STARTED_STATES = set.toArray(new ShardRoutingState[0]); } private DiscoveryNode localNode; diff --git a/server/src/test/java/org/opensearch/search/CreatePitSingleNodeTests.java b/server/src/test/java/org/opensearch/search/CreatePitSingleNodeTests.java index d8fdd9a9cd6eb..f54c5cfbacd46 100644 --- a/server/src/test/java/org/opensearch/search/CreatePitSingleNodeTests.java +++ b/server/src/test/java/org/opensearch/search/CreatePitSingleNodeTests.java @@ -319,7 +319,7 @@ public void testCreatePitMoreThanMaxOpenPitContexts() throws Exception { final int maxPitContexts = SearchService.MAX_OPEN_PIT_CONTEXT.get(Settings.EMPTY); validatePitStats("index", maxPitContexts, 0, 0); // deleteall - DeletePitRequest deletePITRequest = new DeletePitRequest(pitIds.toArray(new String[pitIds.size()])); + DeletePitRequest deletePITRequest = new DeletePitRequest(pitIds.toArray(new String[0])); /* When we invoke delete again, returns success after clearing the remaining readers. Asserting reader context diff --git a/server/src/test/java/org/opensearch/search/aggregations/support/AggregationPathTests.java b/server/src/test/java/org/opensearch/search/aggregations/support/AggregationPathTests.java index a45f890216bce..4f88e5ca55b4c 100644 --- a/server/src/test/java/org/opensearch/search/aggregations/support/AggregationPathTests.java +++ b/server/src/test/java/org/opensearch/search/aggregations/support/AggregationPathTests.java @@ -99,7 +99,7 @@ Tokens add(String name, String key) { } AggregationPath.PathElement[] toArray() { - return tokens.toArray(new AggregationPath.PathElement[tokens.size()]); + return tokens.toArray(new AggregationPath.PathElement[0]); } } } diff --git a/server/src/test/java/org/opensearch/search/fetch/subphase/highlight/HighlightBuilderTests.java b/server/src/test/java/org/opensearch/search/fetch/subphase/highlight/HighlightBuilderTests.java index d07144c70da7d..2bc30b4fba380 100644 --- a/server/src/test/java/org/opensearch/search/fetch/subphase/highlight/HighlightBuilderTests.java +++ b/server/src/test/java/org/opensearch/search/fetch/subphase/highlight/HighlightBuilderTests.java @@ -760,7 +760,7 @@ private static String[] randomStringArray(int minSize, int maxSize) { for (int f = 0; f < size; f++) { randomStrings.add(randomAlphaOfLengthBetween(3, 10)); } - return randomStrings.toArray(new String[randomStrings.size()]); + return randomStrings.toArray(new String[0]); } /** diff --git a/server/src/test/java/org/opensearch/search/sort/FieldSortBuilderTests.java b/server/src/test/java/org/opensearch/search/sort/FieldSortBuilderTests.java index 3ebe2e1194c13..ced952db555aa 100644 --- a/server/src/test/java/org/opensearch/search/sort/FieldSortBuilderTests.java +++ b/server/src/test/java/org/opensearch/search/sort/FieldSortBuilderTests.java @@ -717,7 +717,7 @@ protected void assertWarnings(FieldSortBuilder testItem) { expectedWarnings.add(nestedPathDeprecationWarning); } if (expectedWarnings.isEmpty() == false) { - assertWarnings(expectedWarnings.toArray(new String[expectedWarnings.size()])); + assertWarnings(expectedWarnings.toArray(new String[0])); assertedWarnings.addAll(expectedWarnings); } } diff --git a/server/src/test/java/org/opensearch/search/sort/GeoDistanceSortBuilderTests.java b/server/src/test/java/org/opensearch/search/sort/GeoDistanceSortBuilderTests.java index dcbe6f8949179..385ced3655116 100644 --- a/server/src/test/java/org/opensearch/search/sort/GeoDistanceSortBuilderTests.java +++ b/server/src/test/java/org/opensearch/search/sort/GeoDistanceSortBuilderTests.java @@ -419,7 +419,7 @@ protected void assertWarnings(GeoDistanceSortBuilder testItem) { expectedWarnings.add(nestedPathDeprecationWarning); } if (expectedWarnings.isEmpty() == false) { - assertWarnings(expectedWarnings.toArray(new String[expectedWarnings.size()])); + assertWarnings(expectedWarnings.toArray(new String[0])); assertedWarnings.addAll(expectedWarnings); } } diff --git a/server/src/test/java/org/opensearch/search/sort/SortBuilderTests.java b/server/src/test/java/org/opensearch/search/sort/SortBuilderTests.java index 2f7463346a325..63db202be0c31 100644 --- a/server/src/test/java/org/opensearch/search/sort/SortBuilderTests.java +++ b/server/src/test/java/org/opensearch/search/sort/SortBuilderTests.java @@ -201,7 +201,7 @@ public void testRandomSortBuilders() throws IOException { assertEquals(iterator.next(), parsedBuilder); } if (expectedWarningHeaders.size() > 0) { - assertWarnings(expectedWarningHeaders.toArray(new String[expectedWarningHeaders.size()])); + assertWarnings(expectedWarningHeaders.toArray(new String[0])); assertedWarnings.addAll(expectedWarningHeaders); } } diff --git a/server/src/test/java/org/opensearch/test/hamcrest/OpenSearchGeoAssertions.java b/server/src/test/java/org/opensearch/test/hamcrest/OpenSearchGeoAssertions.java index 74332edc010c7..1470ecec67688 100644 --- a/server/src/test/java/org/opensearch/test/hamcrest/OpenSearchGeoAssertions.java +++ b/server/src/test/java/org/opensearch/test/hamcrest/OpenSearchGeoAssertions.java @@ -100,7 +100,7 @@ private static int next(int top, Coordinate... points) { } private static Coordinate[] fixedOrderedRing(List coordinates, boolean direction) { - return fixedOrderedRing(coordinates.toArray(new Coordinate[coordinates.size()]), direction); + return fixedOrderedRing(coordinates.toArray(new Coordinate[0]), direction); } private static Coordinate[] fixedOrderedRing(Coordinate[] points, boolean direction) { diff --git a/server/src/test/java/org/opensearch/threadpool/UpdateThreadPoolSettingsTests.java b/server/src/test/java/org/opensearch/threadpool/UpdateThreadPoolSettingsTests.java index 419b100558f65..44c5937894828 100644 --- a/server/src/test/java/org/opensearch/threadpool/UpdateThreadPoolSettingsTests.java +++ b/server/src/test/java/org/opensearch/threadpool/UpdateThreadPoolSettingsTests.java @@ -248,7 +248,7 @@ public void testCustomThreadPool() throws Exception { private String randomThreadPoolName() { Set threadPoolNames = ThreadPool.THREAD_POOL_TYPES.keySet(); - return randomFrom(threadPoolNames.toArray(new String[threadPoolNames.size()])); + return randomFrom(threadPoolNames.toArray(new String[0])); } } diff --git a/test/framework/src/main/java/org/opensearch/action/support/replication/ClusterStateCreationUtils.java b/test/framework/src/main/java/org/opensearch/action/support/replication/ClusterStateCreationUtils.java index 15c377374455f..0c4e871b1330c 100644 --- a/test/framework/src/main/java/org/opensearch/action/support/replication/ClusterStateCreationUtils.java +++ b/test/framework/src/main/java/org/opensearch/action/support/replication/ClusterStateCreationUtils.java @@ -525,7 +525,7 @@ private static DiscoveryNode newNode(int nodeId) { } private static String selectAndRemove(Set strings) { - String selection = randomFrom(strings.toArray(new String[strings.size()])); + String selection = randomFrom(strings.toArray(new String[0])); strings.remove(selection); return selection; } diff --git a/test/framework/src/main/java/org/opensearch/repositories/blobstore/OpenSearchBlobStoreRepositoryIntegTestCase.java b/test/framework/src/main/java/org/opensearch/repositories/blobstore/OpenSearchBlobStoreRepositoryIntegTestCase.java index e812589d64aa4..4e0c9270cd627 100644 --- a/test/framework/src/main/java/org/opensearch/repositories/blobstore/OpenSearchBlobStoreRepositoryIntegTestCase.java +++ b/test/framework/src/main/java/org/opensearch/repositories/blobstore/OpenSearchBlobStoreRepositoryIntegTestCase.java @@ -335,7 +335,7 @@ public void testSnapshotAndRestore() throws Exception { List deleteIndices = randomSubsetOf(randomIntBetween(0, indexCount), indexNames); if (deleteIndices.size() > 0) { logger.info("--> delete indices {}", deleteIndices); - assertAcked(client().admin().indices().prepareDelete(deleteIndices.toArray(new String[deleteIndices.size()]))); + assertAcked(client().admin().indices().prepareDelete(deleteIndices.toArray(new String[0]))); } Set closeIndices = new HashSet<>(Arrays.asList(indexNames)); @@ -361,7 +361,7 @@ public void testSnapshotAndRestore() throws Exception { // Wait for green so the close does not fail in the edge case of coinciding with a shard recovery that hasn't fully synced yet ensureGreen(); logger.info("--> close indices {}", closeIndices); - assertAcked(client().admin().indices().prepareClose(closeIndices.toArray(new String[closeIndices.size()]))); + assertAcked(client().admin().indices().prepareClose(closeIndices.toArray(new String[0]))); } logger.info("--> restore all indices from the snapshot"); diff --git a/test/framework/src/main/java/org/opensearch/test/InternalTestCluster.java b/test/framework/src/main/java/org/opensearch/test/InternalTestCluster.java index f45ed2e951818..644ea33e8b89f 100644 --- a/test/framework/src/main/java/org/opensearch/test/InternalTestCluster.java +++ b/test/framework/src/main/java/org/opensearch/test/InternalTestCluster.java @@ -1749,7 +1749,7 @@ public InetSocketAddress[] httpAddresses() { for (HttpServerTransport httpServerTransport : getInstances(HttpServerTransport.class)) { addresses.add(httpServerTransport.boundAddress().publishAddress().address()); } - return addresses.toArray(new InetSocketAddress[addresses.size()]); + return addresses.toArray(new InetSocketAddress[0]); } /** 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 256c95f982835..ffc5fdac210a4 100644 --- a/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java +++ b/test/framework/src/main/java/org/opensearch/test/OpenSearchIntegTestCase.java @@ -757,7 +757,7 @@ public final void createIndex(String... names) { success = true; } finally { if (!success && !created.isEmpty()) { - cluster().wipeIndices(created.toArray(new String[created.size()])); + cluster().wipeIndices(created.toArray(new String[0])); } } } diff --git a/test/framework/src/main/java/org/opensearch/test/XContentTestUtils.java b/test/framework/src/main/java/org/opensearch/test/XContentTestUtils.java index 343ad39407785..2c535211ca456 100644 --- a/test/framework/src/main/java/org/opensearch/test/XContentTestUtils.java +++ b/test/framework/src/main/java/org/opensearch/test/XContentTestUtils.java @@ -295,7 +295,7 @@ static List getInsertPaths(XContentParser parser, Stack currentP currentPath.push(parser.currentName().replaceAll("\\.", "\\\\.")); } if (parser.currentToken() == XContentParser.Token.START_OBJECT) { - validPaths.add(String.join(".", currentPath.toArray(new String[currentPath.size()]))); + validPaths.add(String.join(".", currentPath.toArray(new String[0]))); while (parser.nextToken() != XContentParser.Token.END_OBJECT) { if (parser.currentToken() == XContentParser.Token.START_OBJECT || parser.currentToken() == XContentParser.Token.START_ARRAY) { 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 15a8e0959983f..650558aaa97a6 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 @@ -272,10 +272,7 @@ public static void assertSearchHits(SearchResponse searchResponse, String... ids ); } assertThat( - "Some expected ids were not found in search results: " - + Arrays.toString(idsSet.toArray(new String[idsSet.size()])) - + "." - + shardStatus, + "Some expected ids were not found in search results: " + Arrays.toString(idsSet.toArray(new String[0])) + "." + shardStatus, idsSet.size(), equalTo(0) ); 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 675d8bec17d17..5f2f1ea915047 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 @@ -202,8 +202,8 @@ public void initClient() throws IOException { } clusterHosts = unmodifiableList(hosts); logger.info("initializing REST clients against {}", clusterHosts); - client = buildClient(restClientSettings(), clusterHosts.toArray(new HttpHost[clusterHosts.size()])); - adminClient = buildClient(restAdminSettings(), clusterHosts.toArray(new HttpHost[clusterHosts.size()])); + client = buildClient(restClientSettings(), clusterHosts.toArray(new HttpHost[0])); + adminClient = buildClient(restAdminSettings(), clusterHosts.toArray(new HttpHost[0])); nodeVersions = new TreeSet<>(); Map response = entityAsMap(adminClient.performRequest(new Request("GET", "_nodes/plugins"))); diff --git a/test/framework/src/main/java/org/opensearch/test/transport/MockTransportService.java b/test/framework/src/main/java/org/opensearch/test/transport/MockTransportService.java index 760bcbde8fb34..6bf5381b62cc9 100644 --- a/test/framework/src/main/java/org/opensearch/test/transport/MockTransportService.java +++ b/test/framework/src/main/java/org/opensearch/test/transport/MockTransportService.java @@ -269,7 +269,7 @@ private static TransportAddress[] extractTransportAddresses(TransportService tra BoundTransportAddress boundTransportAddress = transportService.boundAddress(); transportAddresses.addAll(Arrays.asList(boundTransportAddress.boundAddresses())); transportAddresses.add(boundTransportAddress.publishAddress()); - return transportAddresses.toArray(new TransportAddress[transportAddresses.size()]); + return transportAddresses.toArray(new TransportAddress[0]); } @Override