distros = DistributionDownloadPlugin.getContainer(project);
return distros.create(name, distro -> {
@@ -289,7 +318,7 @@ private OpenSearchDistribution checkDistro(
String version,
Type type,
Platform platform,
- Boolean bundledJdk
+ JavaPackageType bundledJdk
) {
OpenSearchDistribution distribution = createDistro(project, name, version, type, platform, bundledJdk);
distribution.finalizeValues();
@@ -315,7 +344,7 @@ private void checkBwc(
Project archiveProject = ProjectBuilder.builder().withParent(bwcProject).withName(projectName).build();
archiveProject.getConfigurations().create(config);
archiveProject.getArtifacts().add(config, new File("doesnotmatter"));
- final OpenSearchDistribution distro = createDistro(project, "distro", version.toString(), type, platform, true);
+ final OpenSearchDistribution distro = createDistro(project, "distro", version.toString(), type, platform, JavaPackageType.JDK);
distro.setArchitecture(Architecture.current());
checkPlugin(project);
}
@@ -335,7 +364,7 @@ private Project createProject(BwcVersions bwcVersions, boolean isInternal) {
return project;
}
- private static String projectName(String base, boolean bundledJdk) {
- return bundledJdk ? base : ("no-jdk-" + base);
+ private static String projectName(String base, JavaPackageType bundledJdk) {
+ return (bundledJdk == JavaPackageType.JDK) ? base : ((bundledJdk == JavaPackageType.NONE) ? ("no-jdk-" + base) : "jre-" + base);
}
}
diff --git a/buildSrc/src/test/java/org/opensearch/gradle/EmptyDirTaskTests.java b/buildSrc/src/test/java/org/opensearch/gradle/EmptyDirTaskTests.java
index a6dc268b90557..ad5b8385abaf8 100644
--- a/buildSrc/src/test/java/org/opensearch/gradle/EmptyDirTaskTests.java
+++ b/buildSrc/src/test/java/org/opensearch/gradle/EmptyDirTaskTests.java
@@ -31,18 +31,19 @@
package org.opensearch.gradle;
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.InvalidPathException;
-import java.nio.file.Path;
-
import com.carrotsearch.randomizedtesting.RandomizedTest;
+
import org.apache.tools.ant.taskdefs.condition.Os;
import org.opensearch.gradle.test.GradleUnitTestCase;
import org.gradle.api.Project;
import org.gradle.testfixtures.ProjectBuilder;
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.InvalidPathException;
+import java.nio.file.Path;
+
public class EmptyDirTaskTests extends GradleUnitTestCase {
public void testCreateEmptyDir() throws Exception {
diff --git a/buildSrc/src/test/java/org/opensearch/gradle/JdkDownloadPluginTests.java b/buildSrc/src/test/java/org/opensearch/gradle/JdkDownloadPluginTests.java
index 55a1eaec98d82..bb394cf51429f 100644
--- a/buildSrc/src/test/java/org/opensearch/gradle/JdkDownloadPluginTests.java
+++ b/buildSrc/src/test/java/org/opensearch/gradle/JdkDownloadPluginTests.java
@@ -33,14 +33,13 @@
package org.opensearch.gradle;
import org.opensearch.gradle.test.GradleUnitTestCase;
-
-import java.util.UUID;
-
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.Project;
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.BeforeClass;
+import java.util.UUID;
+
import static org.hamcrest.CoreMatchers.equalTo;
public class JdkDownloadPluginTests extends GradleUnitTestCase {
diff --git a/buildSrc/src/test/java/org/opensearch/gradle/plugin/OptionalDependenciesPluginTests.java b/buildSrc/src/test/java/org/opensearch/gradle/plugin/OptionalDependenciesPluginTests.java
index ee29f5653d18a..76b669a73610e 100644
--- a/buildSrc/src/test/java/org/opensearch/gradle/plugin/OptionalDependenciesPluginTests.java
+++ b/buildSrc/src/test/java/org/opensearch/gradle/plugin/OptionalDependenciesPluginTests.java
@@ -12,12 +12,12 @@
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
+import org.opensearch.gradle.test.GradleUnitTestCase;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.junit.After;
import org.junit.Before;
import org.junit.rules.TemporaryFolder;
-import org.opensearch.gradle.test.GradleUnitTestCase;
import java.io.File;
import java.io.FileNotFoundException;
@@ -28,8 +28,8 @@
import java.io.OutputStream;
import java.util.Optional;
-import static org.gradle.testkit.runner.TaskOutcome.SUCCESS;
import static org.hamcrest.CoreMatchers.is;
+import static org.gradle.testkit.runner.TaskOutcome.SUCCESS;
public class OptionalDependenciesPluginTests extends GradleUnitTestCase {
private TemporaryFolder projectDir;
diff --git a/buildSrc/src/test/java/org/opensearch/gradle/plugin/PluginBuildPluginTests.java b/buildSrc/src/test/java/org/opensearch/gradle/plugin/PluginBuildPluginTests.java
index 8772a9fbd65ee..fa0693a258222 100644
--- a/buildSrc/src/test/java/org/opensearch/gradle/plugin/PluginBuildPluginTests.java
+++ b/buildSrc/src/test/java/org/opensearch/gradle/plugin/PluginBuildPluginTests.java
@@ -31,19 +31,20 @@
package org.opensearch.gradle.plugin;
-import org.gradle.api.tasks.bundling.AbstractArchiveTask;
import org.opensearch.gradle.BwcVersions;
import org.opensearch.gradle.test.GradleUnitTestCase;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.internal.project.ProjectInternal;
+import org.gradle.api.tasks.bundling.AbstractArchiveTask;
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.Before;
import org.junit.Ignore;
-import org.mockito.Mockito;
import java.util.stream.Collectors;
+import org.mockito.Mockito;
+
public class PluginBuildPluginTests extends GradleUnitTestCase {
private Project project;
diff --git a/buildSrc/src/test/java/org/opensearch/gradle/pluginzip/PublishTests.java b/buildSrc/src/test/java/org/opensearch/gradle/pluginzip/PublishTests.java
index ce33b6bdd5b04..8e246ff9ecd11 100644
--- a/buildSrc/src/test/java/org/opensearch/gradle/pluginzip/PublishTests.java
+++ b/buildSrc/src/test/java/org/opensearch/gradle/pluginzip/PublishTests.java
@@ -8,12 +8,15 @@
package org.opensearch.gradle.pluginzip;
+import org.apache.maven.model.Model;
+import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
+import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
+import org.opensearch.gradle.test.GradleUnitTestCase;
import org.gradle.api.Project;
import org.gradle.testfixtures.ProjectBuilder;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import org.gradle.testkit.runner.UnexpectedBuildFailure;
-import org.opensearch.gradle.test.GradleUnitTestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -28,17 +31,12 @@
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
-
-import static org.gradle.testkit.runner.TaskOutcome.SUCCESS;
-
-import org.apache.maven.model.Model;
-import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
-import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
-
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
+import static org.gradle.testkit.runner.TaskOutcome.SUCCESS;
+
public class PublishTests extends GradleUnitTestCase {
private TemporaryFolder projectDir;
private static final String TEMPLATE_RESOURCE_FOLDER = "pluginzip";
@@ -60,7 +58,7 @@ public void tearDown() {
* This test is used to verify that adding the 'opensearch.pluginzip' to the project
* adds some other transitive plugins and tasks under the hood. This is basically
* a behavioral test of the {@link Publish#apply(Project)} method.
- *
+ *
* This is equivalent of having a build.gradle script with just the following section:
*
* plugins {
@@ -204,7 +202,7 @@ public void useDefaultValues() throws IOException, URISyntaxException, XmlPullPa
GradleRunner runner = prepareGradleRunnerFromTemplate("useDefaultValues.gradle", "build", ZIP_PUBLISH_TASK);
BuildResult result = runner.build();
- /** Check if build and {@value ZIP_PUBLISH_TASK} tasks have run well */
+ /* Check if build and ZIP_PUBLISH_TASK tasks have run well */
assertEquals(SUCCESS, result.task(":" + "build").getOutcome());
assertEquals(SUCCESS, result.task(":" + ZIP_PUBLISH_TASK).getOutcome());
@@ -279,7 +277,7 @@ public void allProjectsGroup() throws IOException, URISyntaxException, XmlPullPa
GradleRunner runner = prepareGradleRunnerFromTemplate("allProjectsGroup.gradle", "build", ZIP_PUBLISH_TASK);
BuildResult result = runner.build();
- /** Check if build and {@value ZIP_PUBLISH_TASK} tasks have run well */
+ /* Check if build and {@value ZIP_PUBLISH_TASK} tasks have run well */
assertEquals(SUCCESS, result.task(":" + "build").getOutcome());
assertEquals(SUCCESS, result.task(":" + ZIP_PUBLISH_TASK).getOutcome());
@@ -314,7 +312,7 @@ public void groupPriorityLevel() throws IOException, URISyntaxException, XmlPull
GradleRunner runner = prepareGradleRunnerFromTemplate("groupPriorityLevel.gradle", "build", ZIP_PUBLISH_TASK);
BuildResult result = runner.build();
- /** Check if build and {@value ZIP_PUBLISH_TASK} tasks have run well */
+ /* Check if build and {@value ZIP_PUBLISH_TASK} tasks have run well */
assertEquals(SUCCESS, result.task(":" + "build").getOutcome());
assertEquals(SUCCESS, result.task(":" + ZIP_PUBLISH_TASK).getOutcome());
@@ -350,7 +348,7 @@ public void missingPOMEntity() throws IOException, URISyntaxException, XmlPullPa
GradleRunner runner = prepareGradleRunnerFromTemplate("missingPOMEntity.gradle", "build", ZIP_PUBLISH_TASK);
BuildResult result = runner.build();
- /** Check if build and {@value ZIP_PUBLISH_TASK} tasks have run well */
+ /* Check if build and {@value ZIP_PUBLISH_TASK} tasks have run well */
assertEquals(SUCCESS, result.task(":" + "build").getOutcome());
assertEquals(SUCCESS, result.task(":" + ZIP_PUBLISH_TASK).getOutcome());
@@ -397,7 +395,7 @@ public void customizedGroupValue() throws IOException, URISyntaxException, XmlPu
GradleRunner runner = prepareGradleRunnerFromTemplate("customizedGroupValue.gradle", "build", ZIP_PUBLISH_TASK);
BuildResult result = runner.build();
- /** Check if build and {@value ZIP_PUBLISH_TASK} tasks have run well */
+ /* Check if build and {@value ZIP_PUBLISH_TASK} tasks have run well */
assertEquals(SUCCESS, result.task(":" + "build").getOutcome());
assertEquals(SUCCESS, result.task(":" + ZIP_PUBLISH_TASK).getOutcome());
diff --git a/buildSrc/src/test/java/org/opensearch/gradle/precommit/FilePermissionsTaskTests.java b/buildSrc/src/test/java/org/opensearch/gradle/precommit/FilePermissionsTaskTests.java
index f47964dd17a7a..0a8cff734ea97 100644
--- a/buildSrc/src/test/java/org/opensearch/gradle/precommit/FilePermissionsTaskTests.java
+++ b/buildSrc/src/test/java/org/opensearch/gradle/precommit/FilePermissionsTaskTests.java
@@ -31,12 +31,8 @@
package org.opensearch.gradle.precommit;
-import java.io.File;
-import java.nio.charset.Charset;
-import java.nio.file.Files;
-import java.util.List;
-
import com.carrotsearch.randomizedtesting.RandomizedTest;
+
import org.apache.tools.ant.taskdefs.condition.Os;
import org.opensearch.gradle.test.GradleUnitTestCase;
import org.gradle.api.GradleException;
@@ -45,6 +41,11 @@
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.Assert;
+import java.io.File;
+import java.nio.charset.Charset;
+import java.nio.file.Files;
+import java.util.List;
+
public class FilePermissionsTaskTests extends GradleUnitTestCase {
public void testCheckPermissionsWhenAnExecutableFileExists() throws Exception {
diff --git a/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/BaseTestCase.java b/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/BaseTestCase.java
index 8e06a1cad0241..f285dcbfd3bd2 100644
--- a/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/BaseTestCase.java
+++ b/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/BaseTestCase.java
@@ -35,10 +35,12 @@
import com.carrotsearch.randomizedtesting.RandomizedRunner;
import com.carrotsearch.randomizedtesting.annotations.TestMethodProviders;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;
-import junit.framework.AssertionFailedError;
+
import org.junit.Assert;
import org.junit.runner.RunWith;
+import junit.framework.AssertionFailedError;
+
@RunWith(RandomizedRunner.class)
@TestMethodProviders({ JUnit4MethodProvider.class, JUnit3MethodProvider.class })
@ThreadLeakLingering(linger = 5000) // wait for "Connection worker" to die
diff --git a/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/GradleThreadsFilter.java b/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/GradleThreadsFilter.java
index b64c719440733..def5248c1f255 100644
--- a/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/GradleThreadsFilter.java
+++ b/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/GradleThreadsFilter.java
@@ -36,7 +36,7 @@
/**
* Filter out threads controlled by gradle that may be created during unit tests.
- *
+ *
* Currently this includes pooled threads for Exec as well as file system event watcher threads.
*/
public class GradleThreadsFilter implements ThreadFilter {
diff --git a/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/GradleUnitTestCase.java b/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/GradleUnitTestCase.java
index a50a14a0ea932..f8032ba53df4c 100644
--- a/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/GradleUnitTestCase.java
+++ b/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/GradleUnitTestCase.java
@@ -35,6 +35,7 @@
import com.carrotsearch.randomizedtesting.RandomizedRunner;
import com.carrotsearch.randomizedtesting.annotations.TestMethodProviders;
import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;
+
import org.junit.runner.RunWith;
@RunWith(RandomizedRunner.class)
diff --git a/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/JUnit3MethodProvider.java b/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/JUnit3MethodProvider.java
index 163a903d31832..1a2e36aa78e9f 100644
--- a/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/JUnit3MethodProvider.java
+++ b/buildSrc/src/testFixtures/java/org/opensearch/gradle/test/JUnit3MethodProvider.java
@@ -43,7 +43,7 @@
/**
* Backwards compatible test* method provider (public, non-static).
- *
+ *
* copy of org.apache.lucene.util.LuceneJUnit3MethodProvider to avoid a dependency between build and test fw.
*/
public final class JUnit3MethodProvider implements TestMethodProvider {
diff --git a/buildSrc/src/testKit/thirdPartyAudit/sample_jars/build.gradle b/buildSrc/src/testKit/thirdPartyAudit/sample_jars/build.gradle
index cb8050d1718c4..48dfb206375ca 100644
--- a/buildSrc/src/testKit/thirdPartyAudit/sample_jars/build.gradle
+++ b/buildSrc/src/testKit/thirdPartyAudit/sample_jars/build.gradle
@@ -15,8 +15,9 @@ plugins {
repositories {
mavenCentral()
}
+
dependencies {
- implementation "org.apache.logging.log4j:log4j-core:2.20.0"
+ implementation "org.apache.logging.log4j:log4j-core:2.23.1"
}
["0.0.1", "0.0.2"].forEach { v ->
diff --git a/buildSrc/version.properties b/buildSrc/version.properties
index e4a9293c59b8f..536a95d69ed83 100644
--- a/buildSrc/version.properties
+++ b/buildSrc/version.properties
@@ -1,36 +1,38 @@
opensearch = 3.0.0
-lucene = 9.8.0-snapshot-4373c3b
+lucene = 9.11.0-snapshot-8a555eb
bundled_jdk_vendor = adoptium
-bundled_jdk = 20.0.2+9
-# See please https://github.com/adoptium/temurin-build/issues/3371
-bundled_jdk_linux_ppc64le = 20+36
+bundled_jdk = 21.0.2+13
# optional dependencies
spatial4j = 0.7
jts = 1.15.0
-jackson = 2.15.2
-jackson_databind = 2.15.2
-snakeyaml = 2.0
+jackson = 2.16.2
+jackson_databind = 2.16.2
+snakeyaml = 2.1
icu4j = 70.1
supercsv = 2.4.0
-log4j = 2.20.0
+log4j = 2.21.0
slf4j = 1.7.36
-asm = 9.5
+asm = 9.6
jettison = 1.5.4
woodstox = 6.4.0
kotlin = 1.7.10
-antlr4 = 4.11.1
+antlr4 = 4.13.1
guava = 32.1.1-jre
protobuf = 3.22.3
jakarta_annotation = 1.3.5
# when updating the JNA version, also update the version in buildSrc/build.gradle
-jna = 5.5.0
+jna = 5.13.0
-netty = 4.1.94.Final
+netty = 4.1.107.Final
joda = 2.12.2
+# project reactor
+reactor_netty = 1.1.17
+reactor = 3.5.15
+
# client dependencies
httpclient5 = 5.2.1
httpcore5 = 5.2.2
@@ -39,33 +41,34 @@ httpcore = 4.4.16
httpasyncclient = 4.1.5
commonslogging = 1.2
commonscodec = 1.15
-
+commonslang = 3.13.0
+commonscompress = 1.24.0
# plugin dependencies
-aws = 2.20.55
+aws = 2.20.86
reactivestreams = 1.0.4
# when updating this version, you need to ensure compatibility with:
# - plugins/ingest-attachment (transitive dependency, check the upstream POM)
# - distribution/tools/plugin-cli
-bouncycastle=1.75
+bouncycastle=1.77
# test dependencies
randomizedrunner = 2.7.1
junit = 4.13.2
hamcrest = 2.1
-mockito = 5.4.0
+mockito = 5.10.0
objenesis = 3.2
-bytebuddy = 1.14.3
+bytebuddy = 1.14.7
# benchmark dependencies
jmh = 1.35
# compression
-zstd = 1.5.5-3
+zstd = 1.5.5-5
jzlib = 1.1.3
resteasy = 6.2.4.Final
# opentelemetry dependencies
-opentelemetry = 1.26.0
-
+opentelemetry = 1.36.0
+opentelemetrysemconv = 1.23.1-alpha
diff --git a/client/benchmark/build.gradle b/client/benchmark/build.gradle
index 6fd5262f0ab4f..c1af5fa92e35c 100644
--- a/client/benchmark/build.gradle
+++ b/client/benchmark/build.gradle
@@ -33,7 +33,7 @@ apply plugin: 'application'
base {
group = 'org.opensearch.client'
- archivesBaseName = 'client-benchmarks'
+ archivesName = 'client-benchmarks'
}
// Not published so no need to assemble
diff --git a/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/SampleRecorder.java b/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/SampleRecorder.java
index e53e4f1ad692d..9cd12f5e78bd0 100644
--- a/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/SampleRecorder.java
+++ b/client/benchmark/src/main/java/org/opensearch/client/benchmark/metrics/SampleRecorder.java
@@ -37,7 +37,7 @@
/**
* Stores measurement samples.
- *
+ *
* This class is NOT threadsafe.
*/
public final class SampleRecorder {
diff --git a/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/bulk/BulkBenchmarkTask.java b/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/bulk/BulkBenchmarkTask.java
index 459cba1ce5f23..5d2b9cb764a6f 100644
--- a/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/bulk/BulkBenchmarkTask.java
+++ b/client/benchmark/src/main/java/org/opensearch/client/benchmark/ops/bulk/BulkBenchmarkTask.java
@@ -31,8 +31,8 @@
package org.opensearch.client.benchmark.ops.bulk;
-import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
import org.opensearch.OpenSearchException;
import org.opensearch.client.benchmark.BenchmarkTask;
import org.opensearch.client.benchmark.metrics.Sample;
diff --git a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/NoopPlugin.java b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/NoopPlugin.java
index e9d0fff2a9dc9..56bf91d1b2360 100644
--- a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/NoopPlugin.java
+++ b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/NoopPlugin.java
@@ -31,17 +31,17 @@
package org.opensearch.plugin.noop;
-import org.opensearch.plugin.noop.action.bulk.NoopBulkAction;
-import org.opensearch.plugin.noop.action.bulk.RestNoopBulkAction;
-import org.opensearch.plugin.noop.action.bulk.TransportNoopBulkAction;
import org.opensearch.action.ActionRequest;
-import org.opensearch.action.ActionResponse;
import org.opensearch.cluster.metadata.IndexNameExpressionResolver;
import org.opensearch.cluster.node.DiscoveryNodes;
import org.opensearch.common.settings.ClusterSettings;
import org.opensearch.common.settings.IndexScopedSettings;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.settings.SettingsFilter;
+import org.opensearch.core.action.ActionResponse;
+import org.opensearch.plugin.noop.action.bulk.NoopBulkAction;
+import org.opensearch.plugin.noop.action.bulk.RestNoopBulkAction;
+import org.opensearch.plugin.noop.action.bulk.TransportNoopBulkAction;
import org.opensearch.plugin.noop.action.search.NoopSearchAction;
import org.opensearch.plugin.noop.action.search.RestNoopSearchAction;
import org.opensearch.plugin.noop.action.search.TransportNoopSearchAction;
diff --git a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/RestNoopBulkAction.java b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/RestNoopBulkAction.java
index 332e089ad9e76..8bd35a0bfed6a 100644
--- a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/RestNoopBulkAction.java
+++ b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/RestNoopBulkAction.java
@@ -40,8 +40,8 @@
import org.opensearch.action.update.UpdateResponse;
import org.opensearch.client.Requests;
import org.opensearch.client.node.NodeClient;
-import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.index.shard.ShardId;
+import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.rest.BaseRestHandler;
import org.opensearch.rest.BytesRestResponse;
import org.opensearch.rest.RestChannel;
@@ -54,9 +54,9 @@
import static java.util.Arrays.asList;
import static java.util.Collections.unmodifiableList;
+import static org.opensearch.core.rest.RestStatus.OK;
import static org.opensearch.rest.RestRequest.Method.POST;
import static org.opensearch.rest.RestRequest.Method.PUT;
-import static org.opensearch.core.rest.RestStatus.OK;
public class RestNoopBulkAction extends BaseRestHandler {
diff --git a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/TransportNoopBulkAction.java b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/TransportNoopBulkAction.java
index 4df9a0465b1a6..77d4d3d095b29 100644
--- a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/TransportNoopBulkAction.java
+++ b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/bulk/TransportNoopBulkAction.java
@@ -31,7 +31,6 @@
package org.opensearch.plugin.noop.action.bulk;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.DocWriteRequest;
import org.opensearch.action.DocWriteResponse;
import org.opensearch.action.bulk.BulkItemResponse;
@@ -41,6 +40,7 @@
import org.opensearch.action.support.HandledTransportAction;
import org.opensearch.action.update.UpdateResponse;
import org.opensearch.common.inject.Inject;
+import org.opensearch.core.action.ActionListener;
import org.opensearch.core.index.shard.ShardId;
import org.opensearch.tasks.Task;
import org.opensearch.transport.TransportService;
diff --git a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/TransportNoopSearchAction.java b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/TransportNoopSearchAction.java
index 1b35787d226e7..99efd31dfcaa5 100644
--- a/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/TransportNoopSearchAction.java
+++ b/client/client-benchmark-noop-api-plugin/src/main/java/org/opensearch/plugin/noop/action/search/TransportNoopSearchAction.java
@@ -32,13 +32,13 @@
package org.opensearch.plugin.noop.action.search;
import org.apache.lucene.search.TotalHits;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.search.SearchRequest;
import org.opensearch.action.search.SearchResponse;
import org.opensearch.action.search.ShardSearchFailure;
import org.opensearch.action.support.ActionFilters;
import org.opensearch.action.support.HandledTransportAction;
import org.opensearch.common.inject.Inject;
+import org.opensearch.core.action.ActionListener;
import org.opensearch.core.common.io.stream.Writeable;
import org.opensearch.search.SearchHit;
import org.opensearch.search.SearchHits;
diff --git a/client/rest-high-level/build.gradle b/client/rest-high-level/build.gradle
index 770cb3f78ca47..fdc93d8037ce6 100644
--- a/client/rest-high-level/build.gradle
+++ b/client/rest-high-level/build.gradle
@@ -39,7 +39,7 @@ apply plugin: 'opensearch.rest-resources'
base {
group = 'org.opensearch.client'
- archivesBaseName = 'opensearch-rest-high-level-client'
+ archivesName = 'opensearch-rest-high-level-client'
}
restResources {
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/ClusterClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/ClusterClient.java
index 45511f2bc2a47..eb0a8b0e8f40a 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/ClusterClient.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/ClusterClient.java
@@ -32,7 +32,6 @@
package org.opensearch.client;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.admin.cluster.health.ClusterHealthRequest;
import org.opensearch.action.admin.cluster.health.ClusterHealthResponse;
import org.opensearch.action.admin.cluster.settings.ClusterGetSettingsRequest;
@@ -47,6 +46,7 @@
import org.opensearch.client.indices.GetComponentTemplatesRequest;
import org.opensearch.client.indices.GetComponentTemplatesResponse;
import org.opensearch.client.indices.PutComponentTemplateRequest;
+import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
import java.io.IOException;
@@ -170,8 +170,8 @@ public ClusterHealthResponse health(ClusterHealthRequest healthRequest, RequestO
/**
* Asynchronously get cluster health using the Cluster Health API.
- *
* If timeout occurred, {@link ClusterHealthResponse} will have isTimedOut() == true and status() == RestStatus.REQUEST_TIMEOUT
+ *
* @param healthRequest the request
* @param options the request options (e.g. headers), use {@link RequestOptions#DEFAULT} if nothing needs to be customized
* @param listener the listener to be notified upon request completion
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/GetAliasesResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/GetAliasesResponse.java
index ee829e2be1f11..c79be0a668896 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/GetAliasesResponse.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/GetAliasesResponse.java
@@ -35,11 +35,11 @@
import org.opensearch.OpenSearchException;
import org.opensearch.cluster.metadata.AliasMetadata;
import org.opensearch.common.xcontent.StatusToXContentObject;
+import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.core.xcontent.XContentParser.Token;
-import org.opensearch.core.rest.RestStatus;
import java.io.IOException;
import java.util.Collections;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/IndicesClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/IndicesClient.java
index f20a6f627a680..281f020533d51 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/IndicesClient.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/IndicesClient.java
@@ -32,7 +32,6 @@
package org.opensearch.client;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest;
import org.opensearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.opensearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest;
@@ -88,6 +87,7 @@
import org.opensearch.client.indices.SimulateIndexTemplateResponse;
import org.opensearch.client.indices.rollover.RolloverRequest;
import org.opensearch.client.indices.rollover.RolloverResponse;
+import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
import java.io.IOException;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/IndicesRequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/IndicesRequestConverters.java
index ed719909e3acc..6c6a8c1bed9c4 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/IndicesRequestConverters.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/IndicesRequestConverters.java
@@ -52,22 +52,22 @@
import org.opensearch.action.admin.indices.validate.query.ValidateQueryRequest;
import org.opensearch.client.indices.AnalyzeRequest;
import org.opensearch.client.indices.CloseIndexRequest;
+import org.opensearch.client.indices.ComposableIndexTemplateExistRequest;
import org.opensearch.client.indices.CreateDataStreamRequest;
import org.opensearch.client.indices.CreateIndexRequest;
import org.opensearch.client.indices.DataStreamsStatsRequest;
-import org.opensearch.client.indices.GetDataStreamRequest;
import org.opensearch.client.indices.DeleteAliasRequest;
import org.opensearch.client.indices.DeleteComposableIndexTemplateRequest;
import org.opensearch.client.indices.DeleteDataStreamRequest;
+import org.opensearch.client.indices.GetComposableIndexTemplateRequest;
+import org.opensearch.client.indices.GetDataStreamRequest;
import org.opensearch.client.indices.GetFieldMappingsRequest;
import org.opensearch.client.indices.GetIndexRequest;
-import org.opensearch.client.indices.GetComposableIndexTemplateRequest;
import org.opensearch.client.indices.GetIndexTemplatesRequest;
import org.opensearch.client.indices.GetMappingsRequest;
-import org.opensearch.client.indices.ComposableIndexTemplateExistRequest;
import org.opensearch.client.indices.IndexTemplatesExistRequest;
-import org.opensearch.client.indices.PutIndexTemplateRequest;
import org.opensearch.client.indices.PutComposableIndexTemplateRequest;
+import org.opensearch.client.indices.PutIndexTemplateRequest;
import org.opensearch.client.indices.PutMappingRequest;
import org.opensearch.client.indices.ResizeRequest;
import org.opensearch.client.indices.SimulateIndexTemplateRequest;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/IngestClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/IngestClient.java
index cd304019e771c..29e5c5369f184 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/IngestClient.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/IngestClient.java
@@ -32,7 +32,6 @@
package org.opensearch.client;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.ingest.DeletePipelineRequest;
import org.opensearch.action.ingest.GetPipelineRequest;
import org.opensearch.action.ingest.GetPipelineResponse;
@@ -40,6 +39,7 @@
import org.opensearch.action.ingest.SimulatePipelineRequest;
import org.opensearch.action.ingest.SimulatePipelineResponse;
import org.opensearch.action.support.master.AcknowledgedResponse;
+import org.opensearch.core.action.ActionListener;
import java.io.IOException;
import java.util.Collections;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java b/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java
index d23a5976fada6..35d9929a649ff 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/RequestConverters.java
@@ -73,19 +73,19 @@
import org.opensearch.common.Nullable;
import org.opensearch.common.Priority;
import org.opensearch.common.SuppressForbidden;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.lucene.uid.Versions;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.util.CollectionUtils;
import org.opensearch.common.xcontent.XContentHelper;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.common.Strings;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.common.util.CollectionUtils;
import org.opensearch.core.xcontent.DeprecationHandler;
+import org.opensearch.core.xcontent.MediaType;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContent;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.core.xcontent.MediaType;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.index.VersionType;
import org.opensearch.index.mapper.MapperService;
@@ -119,7 +119,7 @@
* @opensearch.api
*/
final class RequestConverters {
- static final XContentType REQUEST_BODY_CONTENT_TYPE = XContentType.JSON;
+ static final MediaType REQUEST_BODY_CONTENT_TYPE = MediaTypeRegistry.JSON;
private RequestConverters() {
// Contains only status utility methods
@@ -177,7 +177,7 @@ static Request bulk(BulkRequest bulkRequest) throws IOException {
}
if (bulkContentType == null) {
- bulkContentType = XContentType.JSON;
+ bulkContentType = MediaTypeRegistry.JSON;
}
final byte separator = bulkContentType.xContent().streamSeparator();
@@ -266,7 +266,12 @@ static Request bulk(BulkRequest bulkRequest) throws IOException {
}
}
} else if (opType == DocWriteRequest.OpType.UPDATE) {
- source = XContentHelper.toXContent((UpdateRequest) action, bulkContentType, ToXContent.EMPTY_PARAMS, false).toBytesRef();
+ source = org.opensearch.core.xcontent.XContentHelper.toXContent(
+ (UpdateRequest) action,
+ bulkContentType,
+ ToXContent.EMPTY_PARAMS,
+ false
+ ).toBytesRef();
}
if (source != null) {
@@ -446,9 +451,9 @@ static void addSearchRequestParams(Params params, SearchRequest searchRequest) {
params.withIndicesOptions(searchRequest.indicesOptions());
}
params.withSearchType(searchRequest.searchType().name().toLowerCase(Locale.ROOT));
- /**
- * Merging search responses as part of CCS flow to reduce roundtrips is not supported for point in time -
- * refer to org.opensearch.action.search.SearchResponseMerger
+ /*
+ Merging search responses as part of CCS flow to reduce roundtrips is not supported for point in time -
+ refer to org.opensearch.action.search.SearchResponseMerger
*/
if (searchRequest.pointInTimeBuilder() != null) {
params.putParam("ccs_minimize_roundtrips", "false");
@@ -821,7 +826,8 @@ static HttpEntity createEntity(ToXContent toXContent, MediaType mediaType) throw
}
static HttpEntity createEntity(ToXContent toXContent, MediaType mediaType, ToXContent.Params toXContentParams) throws IOException {
- BytesRef source = XContentHelper.toXContent(toXContent, mediaType, toXContentParams, false).toBytesRef();
+ BytesRef source = org.opensearch.core.xcontent.XContentHelper.toXContent(toXContent, mediaType, toXContentParams, false)
+ .toBytesRef();
return new ByteArrayEntity(source.bytes, source.offset, source.length, createContentType(mediaType));
}
@@ -868,12 +874,12 @@ static String endpoint(String[] indices, String endpoint, String type) {
}
/**
- * Returns a {@link ContentType} from a given {@link XContentType}.
+ * Returns a {@link ContentType} from a given {@link MediaType}.
*
* @param mediaType the {@link MediaType}
* @return the {@link ContentType}
*/
- @SuppressForbidden(reason = "Only allowed place to convert a XContentType to a ContentType")
+ @SuppressForbidden(reason = "Only allowed place to convert a MediaType to a ContentType")
public static ContentType createContentType(final MediaType mediaType) {
return ContentType.create(mediaType.mediaTypeWithoutParameters(), (Charset) null);
}
@@ -1179,14 +1185,14 @@ Params withActions(List actions) {
return this;
}
- Params withTaskId(org.opensearch.tasks.TaskId taskId) {
+ Params withTaskId(org.opensearch.core.tasks.TaskId taskId) {
if (taskId != null && taskId.isSet()) {
return putParam("task_id", taskId.toString());
}
return this;
}
- Params withParentTaskId(org.opensearch.tasks.TaskId parentTaskId) {
+ Params withParentTaskId(org.opensearch.core.tasks.TaskId parentTaskId) {
if (parentTaskId != null && parentTaskId.isSet()) {
return putParam("parent_task_id", parentTaskId.toString());
}
@@ -1252,7 +1258,7 @@ Params withWaitForEvents(Priority waitForEvents) {
*/
static MediaType enforceSameContentType(IndexRequest indexRequest, @Nullable MediaType mediaType) {
MediaType requestContentType = indexRequest.getContentType();
- if (requestContentType != XContentType.JSON && requestContentType != XContentType.SMILE) {
+ if (requestContentType != MediaTypeRegistry.JSON && requestContentType != MediaTypeRegistry.fromFormat("smile")) {
throw new IllegalArgumentException(
"Unsupported content-type found for request with content-type ["
+ requestContentType
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/RestHighLevelClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/RestHighLevelClient.java
index 1ff5c81c4a0e3..9d8d771f1eaed 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/RestHighLevelClient.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/RestHighLevelClient.java
@@ -35,7 +35,6 @@
import org.apache.hc.core5.http.HttpEntity;
import org.opensearch.OpenSearchException;
import org.opensearch.OpenSearchStatusException;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.ActionRequest;
import org.opensearch.action.ActionRequestValidationException;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse;
@@ -86,6 +85,8 @@
import org.opensearch.common.CheckedConsumer;
import org.opensearch.common.CheckedFunction;
import org.opensearch.core.ParseField;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ContextParser;
import org.opensearch.core.xcontent.DeprecationHandler;
import org.opensearch.core.xcontent.MediaType;
@@ -99,7 +100,6 @@
import org.opensearch.index.reindex.UpdateByQueryRequest;
import org.opensearch.plugins.spi.NamedXContentProvider;
import org.opensearch.rest.BytesRestResponse;
-import org.opensearch.core.rest.RestStatus;
import org.opensearch.script.mustache.MultiSearchTemplateRequest;
import org.opensearch.script.mustache.MultiSearchTemplateResponse;
import org.opensearch.script.mustache.SearchTemplateRequest;
@@ -139,21 +139,21 @@
import org.opensearch.search.aggregations.bucket.range.RangeAggregationBuilder;
import org.opensearch.search.aggregations.bucket.sampler.InternalSampler;
import org.opensearch.search.aggregations.bucket.sampler.ParsedSampler;
+import org.opensearch.search.aggregations.bucket.terms.DoubleTerms;
import org.opensearch.search.aggregations.bucket.terms.LongRareTerms;
+import org.opensearch.search.aggregations.bucket.terms.LongTerms;
import org.opensearch.search.aggregations.bucket.terms.MultiTermsAggregationBuilder;
+import org.opensearch.search.aggregations.bucket.terms.ParsedDoubleTerms;
import org.opensearch.search.aggregations.bucket.terms.ParsedLongRareTerms;
+import org.opensearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.opensearch.search.aggregations.bucket.terms.ParsedMultiTerms;
import org.opensearch.search.aggregations.bucket.terms.ParsedSignificantLongTerms;
import org.opensearch.search.aggregations.bucket.terms.ParsedSignificantStringTerms;
import org.opensearch.search.aggregations.bucket.terms.ParsedStringRareTerms;
-import org.opensearch.search.aggregations.bucket.terms.SignificantLongTerms;
-import org.opensearch.search.aggregations.bucket.terms.SignificantStringTerms;
-import org.opensearch.search.aggregations.bucket.terms.DoubleTerms;
-import org.opensearch.search.aggregations.bucket.terms.LongTerms;
-import org.opensearch.search.aggregations.bucket.terms.ParsedDoubleTerms;
-import org.opensearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.opensearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.opensearch.search.aggregations.bucket.terms.ParsedUnsignedLongTerms;
+import org.opensearch.search.aggregations.bucket.terms.SignificantLongTerms;
+import org.opensearch.search.aggregations.bucket.terms.SignificantStringTerms;
import org.opensearch.search.aggregations.bucket.terms.StringRareTerms;
import org.opensearch.search.aggregations.bucket.terms.StringTerms;
import org.opensearch.search.aggregations.bucket.terms.UnsignedLongTerms;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/RethrottleRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/RethrottleRequest.java
index 958e6ce4cda1c..6e453a5c7f343 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/RethrottleRequest.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/RethrottleRequest.java
@@ -32,7 +32,7 @@
package org.opensearch.client;
-import org.opensearch.tasks.TaskId;
+import org.opensearch.core.tasks.TaskId;
import java.util.Objects;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/SearchPipelineClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/SearchPipelineClient.java
index b6c28f57d6bd9..0014bdb8c8182 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/SearchPipelineClient.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/SearchPipelineClient.java
@@ -8,12 +8,12 @@
package org.opensearch.client;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.search.DeleteSearchPipelineRequest;
import org.opensearch.action.search.GetSearchPipelineRequest;
import org.opensearch.action.search.GetSearchPipelineResponse;
import org.opensearch.action.search.PutSearchPipelineRequest;
import org.opensearch.action.support.master.AcknowledgedResponse;
+import org.opensearch.core.action.ActionListener;
import java.io.IOException;
import java.util.Collections;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotClient.java
index 85a793dec24ce..87a0e45eafe49 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotClient.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/SnapshotClient.java
@@ -32,7 +32,6 @@
package org.opensearch.client;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.admin.cluster.repositories.cleanup.CleanupRepositoryRequest;
import org.opensearch.action.admin.cluster.repositories.cleanup.CleanupRepositoryResponse;
import org.opensearch.action.admin.cluster.repositories.delete.DeleteRepositoryRequest;
@@ -52,6 +51,7 @@
import org.opensearch.action.admin.cluster.snapshots.status.SnapshotsStatusRequest;
import org.opensearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse;
import org.opensearch.action.support.master.AcknowledgedResponse;
+import org.opensearch.core.action.ActionListener;
import java.io.IOException;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/TasksClient.java b/client/rest-high-level/src/main/java/org/opensearch/client/TasksClient.java
index 51764e3339394..ec862aead794a 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/TasksClient.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/TasksClient.java
@@ -32,13 +32,13 @@
package org.opensearch.client;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse;
import org.opensearch.client.tasks.CancelTasksRequest;
import org.opensearch.client.tasks.CancelTasksResponse;
import org.opensearch.client.tasks.GetTaskRequest;
import org.opensearch.client.tasks.GetTaskResponse;
+import org.opensearch.core.action.ActionListener;
import java.io.IOException;
import java.util.Optional;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/TimedRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/TimedRequest.java
index dad5b6a3679ec..d40445b2daa81 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/TimedRequest.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/TimedRequest.java
@@ -37,7 +37,7 @@
/**
* A base request for any requests that supply timeouts.
- *
+ *
* Please note, any requests that use a ackTimeout should set timeout as they
* represent the same backing field on the server.
*/
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/BroadcastResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/BroadcastResponse.java
index 42011a0da7ab2..a91d1461685f8 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/core/BroadcastResponse.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/BroadcastResponse.java
@@ -32,8 +32,8 @@
package org.opensearch.client.core;
-import org.opensearch.core.action.support.DefaultShardOperationFailedException;
import org.opensearch.core.ParseField;
+import org.opensearch.core.action.support.DefaultShardOperationFailedException;
import org.opensearch.core.xcontent.ConstructingObjectParser;
import org.opensearch.core.xcontent.XContentParser;
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 10d318afd9da0..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
@@ -34,8 +34,8 @@
import org.opensearch.action.search.ShardSearchFailure;
import org.opensearch.core.ParseField;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.XContentParser;
import java.io.IOException;
import java.util.ArrayList;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsResponse.java
index 5e671c416e4ef..ad2e3dd550880 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsResponse.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/core/TermVectorsResponse.java
@@ -36,14 +36,15 @@
import org.opensearch.core.ParseField;
import org.opensearch.core.xcontent.ConstructingObjectParser;
import org.opensearch.core.xcontent.XContentParser;
-import static org.opensearch.core.xcontent.ConstructingObjectParser.constructorArg;
-import static org.opensearch.core.xcontent.ConstructingObjectParser.optionalConstructorArg;
import java.util.Collections;
-import java.util.List;
import java.util.Comparator;
+import java.util.List;
import java.util.Objects;
+import static org.opensearch.core.xcontent.ConstructingObjectParser.constructorArg;
+import static org.opensearch.core.xcontent.ConstructingObjectParser.optionalConstructorArg;
+
public class TermVectorsResponse {
private final String index;
private final String id;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CloseIndexResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CloseIndexResponse.java
index a9a851474c424..e32c33484140d 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CloseIndexResponse.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CloseIndexResponse.java
@@ -32,10 +32,10 @@
package org.opensearch.client.indices;
import org.opensearch.OpenSearchException;
-import org.opensearch.core.action.support.DefaultShardOperationFailedException;
import org.opensearch.action.support.master.ShardsAcknowledgedResponse;
import org.opensearch.common.Nullable;
import org.opensearch.core.ParseField;
+import org.opensearch.core.action.support.DefaultShardOperationFailedException;
import org.opensearch.core.xcontent.ConstructingObjectParser;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.core.xcontent.XContentParserUtils;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexRequest.java
index 3405e7e81e122..62c5b54c0e75e 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexRequest.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/CreateIndexRequest.java
@@ -38,16 +38,15 @@
import org.opensearch.action.support.ActiveShardCount;
import org.opensearch.client.TimedRequest;
import org.opensearch.client.Validatable;
-import org.opensearch.common.Strings;
-import org.opensearch.core.common.bytes.BytesArray;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.core.ParseField;
+import org.opensearch.core.common.bytes.BytesArray;
+import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.DeprecationHandler;
import org.opensearch.core.xcontent.MediaType;
-import org.opensearch.core.xcontent.MediaTypeParserRegistry;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
@@ -135,7 +134,7 @@ public CreateIndexRequest settings(String source, MediaType mediaType) {
* Allows to set the settings using a json builder.
*/
public CreateIndexRequest settings(XContentBuilder builder) {
- settings(Strings.toString(builder), builder.contentType());
+ settings(builder.toString(), builder.contentType());
return this;
}
@@ -157,7 +156,7 @@ public MediaType mappingsMediaType() {
/**
* Adds mapping that will be added when the index gets created.
- *
+ *
* Note that the definition should *not* be nested under a type name.
*
* @param source The mapping source
@@ -169,7 +168,7 @@ public CreateIndexRequest mapping(String source, MediaType mediaType) {
/**
* Adds mapping that will be added when the index gets created.
- *
+ *
* Note that the definition should *not* be nested under a type name.
*
* @param source The mapping source
@@ -180,14 +179,14 @@ public CreateIndexRequest mapping(XContentBuilder source) {
/**
* Adds mapping that will be added when the index gets created.
- *
+ *
* Note that the definition should *not* be nested under a type name.
*
* @param source The mapping source
*/
public CreateIndexRequest mapping(Map source) {
try {
- XContentBuilder builder = XContentFactory.contentBuilder(MediaTypeParserRegistry.getDefaultMediaType());
+ XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.getDefaultMediaType());
builder.map(source);
return mapping(BytesReference.bytes(builder), builder.contentType());
} catch (IOException e) {
@@ -197,7 +196,7 @@ public CreateIndexRequest mapping(Map source) {
/**
* Adds mapping that will be added when the index gets created.
- *
+ *
* Note that the definition should *not* be nested under a type name.
*
* @param source The mapping source
@@ -283,7 +282,7 @@ public CreateIndexRequest aliases(Collection aliases) {
/**
* Sets the settings and mappings as a single source.
- *
+ *
* Note that the mapping definition should *not* be nested under a type name.
*/
public CreateIndexRequest source(String source, MediaType mediaType) {
@@ -292,7 +291,7 @@ public CreateIndexRequest source(String source, MediaType mediaType) {
/**
* Sets the settings and mappings as a single source.
- *
+ *
* Note that the mapping definition should *not* be nested under a type name.
*/
public CreateIndexRequest source(XContentBuilder source) {
@@ -301,7 +300,7 @@ public CreateIndexRequest source(XContentBuilder source) {
/**
* Sets the settings and mappings as a single source.
- *
+ *
* Note that the mapping definition should *not* be nested under a type name.
*/
public CreateIndexRequest source(BytesReference source, MediaType mediaType) {
@@ -312,7 +311,7 @@ public CreateIndexRequest source(BytesReference source, MediaType mediaType) {
/**
* Sets the settings and mappings as a single source.
- *
+ *
* Note that the mapping definition should *not* be nested under a type name.
*/
@SuppressWarnings("unchecked")
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStreamsStatsResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStreamsStatsResponse.java
index 2c90d5a734aa0..327836160cceb 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStreamsStatsResponse.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DataStreamsStatsResponse.java
@@ -34,7 +34,7 @@
import org.opensearch.client.core.BroadcastResponse;
import org.opensearch.core.ParseField;
-import org.opensearch.common.unit.ByteSizeValue;
+import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.core.xcontent.ConstructingObjectParser;
import org.opensearch.core.xcontent.ObjectParser;
import org.opensearch.core.xcontent.XContentParser;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DetailAnalyzeResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DetailAnalyzeResponse.java
index c2ac8169b0a4e..92ab2d7b744b2 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/DetailAnalyzeResponse.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/DetailAnalyzeResponse.java
@@ -32,8 +32,8 @@
package org.opensearch.client.indices;
-import org.opensearch.core.common.Strings;
import org.opensearch.core.ParseField;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.xcontent.ConstructingObjectParser;
import org.opensearch.core.xcontent.XContentParser;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java
index 1359c68fc1311..ec3101b7e7543 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/GetFieldMappingsResponse.java
@@ -32,14 +32,14 @@
package org.opensearch.client.indices;
+import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.core.ParseField;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.ConstructingObjectParser;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ObjectParser;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.index.mapper.Mapper;
import java.io.IOException;
@@ -47,8 +47,8 @@
import java.util.Map;
import java.util.Objects;
-import static org.opensearch.core.xcontent.ConstructingObjectParser.optionalConstructorArg;
import static org.opensearch.common.xcontent.XContentFactory.jsonBuilder;
+import static org.opensearch.core.xcontent.ConstructingObjectParser.optionalConstructorArg;
import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;
/** Response object for {@link GetFieldMappingsRequest} API */
@@ -150,7 +150,7 @@ public String fullName() {
* Returns the mappings as a map. Note that the returned map has a single key which is always the field's {@link Mapper#name}.
*/
public Map sourceAsMap() {
- return XContentHelper.convertToMap(source, true, XContentType.JSON).v2();
+ return XContentHelper.convertToMap(source, true, MediaTypeRegistry.JSON).v2();
}
// pkg-private for testing
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/IndexTemplateMetadata.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/IndexTemplateMetadata.java
index adc2e2d4e3621..017ad0089704e 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/IndexTemplateMetadata.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/IndexTemplateMetadata.java
@@ -35,8 +35,8 @@
import org.opensearch.cluster.metadata.IndexMetadata;
import org.opensearch.cluster.metadata.MappingMetadata;
import org.opensearch.common.Nullable;
-import org.opensearch.core.ParseField;
import org.opensearch.common.settings.Settings;
+import org.opensearch.core.ParseField;
import org.opensearch.core.xcontent.ConstructingObjectParser;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.index.mapper.MapperService;
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 fed958955af99..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
@@ -39,19 +39,20 @@
import org.opensearch.action.support.IndicesOptions;
import org.opensearch.action.support.clustermanager.ClusterManagerNodeRequest;
import org.opensearch.common.Nullable;
-import org.opensearch.core.common.bytes.BytesArray;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.common.xcontent.json.JsonXContent;
import org.opensearch.common.xcontent.support.XContentMapValues;
+import org.opensearch.core.common.bytes.BytesArray;
+import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.DeprecationHandler;
+import org.opensearch.core.xcontent.MediaType;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.core.xcontent.MediaType;
import org.opensearch.core.xcontent.XContentParser;
import java.io.IOException;
@@ -216,10 +217,10 @@ public Settings settings() {
* Adds mapping that will be added when the index gets created.
*
* @param source The mapping source
- * @param xContentType The type of content contained within the source
+ * @param mediaType The type of content contained within the source
*/
- public PutIndexTemplateRequest mapping(String source, XContentType xContentType) {
- internalMapping(XContentHelper.convertToMap(new BytesArray(source), true, xContentType).v2());
+ public PutIndexTemplateRequest mapping(String source, MediaType mediaType) {
+ internalMapping(XContentHelper.convertToMap(new BytesArray(source), true, mediaType).v2());
return this;
}
@@ -267,7 +268,7 @@ public PutIndexTemplateRequest mapping(Map source) {
private PutIndexTemplateRequest internalMapping(Map source) {
try {
- XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
+ XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder();
builder.map(source);
MediaType mediaType = builder.contentType();
Objects.requireNonNull(mediaType);
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutMappingRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutMappingRequest.java
index d17dc54713789..a63393bd2341b 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutMappingRequest.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/PutMappingRequest.java
@@ -38,9 +38,8 @@
import org.opensearch.client.TimedRequest;
import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.common.bytes.BytesReference;
-import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.core.xcontent.MediaType;
-import org.opensearch.core.xcontent.MediaTypeParserRegistry;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
@@ -106,12 +105,12 @@ public MediaType mediaType() {
/**
* The mapping source definition.
- *
+ *
* Note that the definition should *not* be nested under a type name.
*/
public PutMappingRequest source(Map mappingSource) {
try {
- XContentBuilder builder = XContentFactory.contentBuilder(MediaTypeParserRegistry.getDefaultMediaType());
+ XContentBuilder builder = MediaTypeRegistry.contentBuilder(MediaTypeRegistry.getDefaultMediaType());
builder.map(mappingSource);
return source(builder);
} catch (IOException e) {
@@ -121,7 +120,7 @@ public PutMappingRequest source(Map mappingSource) {
/**
* The mapping source definition.
- *
+ *
* Note that the definition should *not* be nested under a type name.
*/
public PutMappingRequest source(String mappingSource, MediaType mediaType) {
@@ -132,7 +131,7 @@ public PutMappingRequest source(String mappingSource, MediaType mediaType) {
/**
* The mapping source definition.
- *
+ *
* Note that the definition should *not* be nested under a type name.
*/
public PutMappingRequest source(XContentBuilder builder) {
@@ -143,7 +142,7 @@ public PutMappingRequest source(XContentBuilder builder) {
/**
* The mapping source definition.
- *
+ *
* Note that the definition should *not* be nested under a type name.
*/
public PutMappingRequest source(BytesReference source, MediaType mediaType) {
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/ResizeRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/ResizeRequest.java
index 61799a83e5df5..e53bdd99b3cee 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/ResizeRequest.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/ResizeRequest.java
@@ -37,9 +37,9 @@
import org.opensearch.client.Validatable;
import org.opensearch.client.ValidationException;
import org.opensearch.common.settings.Settings;
+import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.common.unit.ByteSizeValue;
import java.io.IOException;
import java.util.Collections;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverRequest.java b/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverRequest.java
index 443cef45e646b..45211864a3df3 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverRequest.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/indices/rollover/RolloverRequest.java
@@ -37,8 +37,8 @@
import org.opensearch.action.admin.indices.rollover.MaxSizeCondition;
import org.opensearch.client.TimedRequest;
import org.opensearch.client.indices.CreateIndexRequest;
-import org.opensearch.common.unit.ByteSizeValue;
import org.opensearch.common.unit.TimeValue;
+import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java
index 3566d6aef1ac3..fd101c575b97a 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicy.java
@@ -33,10 +33,10 @@
package org.opensearch.client.slm;
import org.opensearch.common.Nullable;
-import org.opensearch.common.Strings;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.ParseField;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.xcontent.ConstructingObjectParser;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
@@ -169,6 +169,6 @@ public boolean equals(Object obj) {
@Override
public String toString() {
- return Strings.toString(XContentType.JSON, this);
+ return Strings.toString(MediaTypeRegistry.JSON, this);
}
}
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java
index c0b542557159f..dd44d16f0d65e 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecyclePolicyMetadata.java
@@ -33,10 +33,10 @@
package org.opensearch.client.slm;
import org.opensearch.common.Nullable;
-import org.opensearch.common.Strings;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.ParseField;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.xcontent.ConstructingObjectParser;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
@@ -289,7 +289,7 @@ public boolean equals(Object obj) {
@Override
public String toString() {
- return Strings.toString(XContentType.JSON, this);
+ return Strings.toString(MediaTypeRegistry.JSON, this);
}
}
}
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java
index 2126ced76b5ae..476533d9c91ca 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotLifecycleStats.java
@@ -32,11 +32,11 @@
package org.opensearch.client.slm;
-import org.opensearch.common.Strings;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.ParseField;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.xcontent.ConstructingObjectParser;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
@@ -188,7 +188,7 @@ public boolean equals(Object obj) {
@Override
public String toString() {
- return Strings.toString(XContentType.JSON, this);
+ return Strings.toString(MediaTypeRegistry.JSON, this);
}
public static class SnapshotPolicyStats implements ToXContentFragment {
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java
index 2a7ab6bb04095..3165b6bede19d 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/slm/SnapshotRetentionConfiguration.java
@@ -33,11 +33,11 @@
package org.opensearch.client.slm;
import org.opensearch.common.Nullable;
-import org.opensearch.common.Strings;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.ParseField;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.xcontent.ConstructingObjectParser;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
@@ -151,6 +151,6 @@ public boolean equals(Object obj) {
@Override
public String toString() {
- return Strings.toString(XContentType.JSON, this);
+ return Strings.toString(MediaTypeRegistry.JSON, this);
}
}
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/NodeData.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/NodeData.java
index 9d752da1ef9f8..4ecdff354c37d 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/NodeData.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/NodeData.java
@@ -31,14 +31,15 @@
package org.opensearch.client.tasks;
+import org.opensearch.core.ParseField;
+import org.opensearch.core.xcontent.ObjectParser;
+import org.opensearch.core.xcontent.XContentParser;
+
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
-import org.opensearch.core.ParseField;
-import org.opensearch.core.xcontent.ObjectParser;
-import org.opensearch.core.xcontent.XContentParser;
class NodeData {
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/OpenSearchException.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/OpenSearchException.java
index 8ce6e71cfeeba..2f341e5102a08 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/OpenSearchException.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/OpenSearchException.java
@@ -33,6 +33,7 @@
import org.opensearch.core.ParseField;
import org.opensearch.core.xcontent.XContentParser;
+
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskGroup.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskGroup.java
index c419884700587..9129de717459f 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskGroup.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskGroup.java
@@ -38,7 +38,6 @@
/**
* Client side counterpart of server side version.
- *
* {@link org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup}
*/
public class TaskGroup {
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskId.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskId.java
index cd036a732957b..c2cf2c826b8bd 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskId.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskId.java
@@ -34,7 +34,7 @@
import java.util.Objects;
/**
- * client side version of a {@link org.opensearch.tasks.TaskId}
+ * client side version of a {@link org.opensearch.core.tasks.TaskId}
*/
public class TaskId {
diff --git a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskInfo.java b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskInfo.java
index 51ac62830446f..75badc4e3dbf2 100644
--- a/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskInfo.java
+++ b/client/rest-high-level/src/main/java/org/opensearch/client/tasks/TaskInfo.java
@@ -54,6 +54,7 @@ public class TaskInfo {
private long runningTimeNanos;
private boolean cancellable;
private boolean cancelled;
+ private Long cancellationStartTime;
private TaskId parentTaskId;
private final Map status = new HashMap<>();
private final Map headers = new HashMap<>();
@@ -127,6 +128,14 @@ void setCancelled(boolean cancelled) {
this.cancelled = cancelled;
}
+ public Long getCancellationStartTime() {
+ return this.cancellationStartTime;
+ }
+
+ public void setCancellationStartTime(Long cancellationStartTime) {
+ this.cancellationStartTime = cancellationStartTime;
+ }
+
public TaskId getParentTaskId() {
return parentTaskId;
}
@@ -180,6 +189,7 @@ private void noOpParse(Object s) {}
parser.declareString(TaskInfo::setParentTaskId, new ParseField("parent_task_id"));
parser.declareObject(TaskInfo::setHeaders, (p, c) -> p.mapStrings(), new ParseField("headers"));
parser.declareObject(TaskInfo::setResourceStats, (p, c) -> p.map(), new ParseField("resource_stats"));
+ parser.declareLong(TaskInfo::setCancellationStartTime, new ParseField("cancellation_time_millis"));
PARSER = (XContentParser p, Void v, String name) -> parser.parse(p, new TaskInfo(new TaskId(name)), null);
}
@@ -199,7 +209,8 @@ && isCancelled() == taskInfo.isCancelled()
&& Objects.equals(getParentTaskId(), taskInfo.getParentTaskId())
&& Objects.equals(status, taskInfo.status)
&& Objects.equals(getHeaders(), taskInfo.getHeaders())
- && Objects.equals(getResourceStats(), taskInfo.getResourceStats());
+ && Objects.equals(getResourceStats(), taskInfo.getResourceStats())
+ && Objects.equals(getCancellationStartTime(), taskInfo.cancellationStartTime);
}
@Override
@@ -216,7 +227,8 @@ public int hashCode() {
getParentTaskId(),
status,
getHeaders(),
- getResourceStats()
+ getResourceStats(),
+ getCancellationStartTime()
);
}
@@ -250,6 +262,8 @@ public String toString() {
+ headers
+ ", resource_stats="
+ resourceStats
+ + ", cancellationStartTime="
+ + cancellationStartTime
+ '}';
}
}
diff --git a/client/rest-high-level/src/main/resources/forbidden/rest-high-level-signatures.txt b/client/rest-high-level/src/main/resources/forbidden/rest-high-level-signatures.txt
index e9e793aa9a783..42dde784147c7 100644
--- a/client/rest-high-level/src/main/resources/forbidden/rest-high-level-signatures.txt
+++ b/client/rest-high-level/src/main/resources/forbidden/rest-high-level-signatures.txt
@@ -14,7 +14,7 @@
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
-@defaultMessage Use Request#createContentType(XContentType) to be sure to pass the right MIME type
+@defaultMessage Use Request#createContentType(MediaType) to be sure to pass the right MIME type
org.apache.hc.core5.http.ContentType#create(java.lang.String)
org.apache.hc.core5.http.ContentType#create(java.lang.String,java.lang.String)
org.apache.hc.core5.http.ContentType#create(java.lang.String,java.nio.charset.Charset)
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/AbstractRequestTestCase.java b/client/rest-high-level/src/test/java/org/opensearch/client/AbstractRequestTestCase.java
index 707f4246009aa..c464ee9ece74a 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/AbstractRequestTestCase.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/AbstractRequestTestCase.java
@@ -31,21 +31,20 @@
package org.opensearch.client;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.xcontent.LoggingDeprecationHandler;
+import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContent;
-import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.test.OpenSearchTestCase;
import java.io.IOException;
/**
* Base class for HLRC request parsing tests.
- *
+ *
* This case class facilitates generating client side request test instances and
* verifies that they are correctly parsed into server side request instances.
*
@@ -60,7 +59,7 @@ public final void testFromXContent() throws IOException {
final XContentType xContentType = randomFrom(XContentType.values());
final BytesReference bytes = toShuffledXContent(clientTestInstance, xContentType, ToXContent.EMPTY_PARAMS, randomBoolean());
- final XContent xContent = XContentFactory.xContent(xContentType);
+ final XContent xContent = xContentType.xContent();
final XContentParser parser = xContent.createParser(xContentRegistry(), LoggingDeprecationHandler.INSTANCE, bytes.streamInput());
final S serverInstance = doParseToServerInstance(parser);
assertInstances(serverInstance, clientTestInstance);
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/AbstractResponseTestCase.java b/client/rest-high-level/src/test/java/org/opensearch/client/AbstractResponseTestCase.java
index 5f7df0cd5860c..7d2d6b87b85c6 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/AbstractResponseTestCase.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/AbstractResponseTestCase.java
@@ -31,21 +31,20 @@
package org.opensearch.client;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.xcontent.LoggingDeprecationHandler;
+import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContent;
-import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.test.OpenSearchTestCase;
import java.io.IOException;
/**
* Base class for HLRC response parsing tests.
- *
+ *
* This case class facilitates generating server side response test instances and
* verifies that they are correctly parsed into HLRC response instances.
*
@@ -59,7 +58,7 @@ public final void testFromXContent() throws IOException {
final S serverTestInstance = createServerTestInstance(xContentType);
final BytesReference bytes = toShuffledXContent(serverTestInstance, xContentType, getParams(), randomBoolean());
- final XContent xContent = XContentFactory.xContent(xContentType);
+ final XContent xContent = xContentType.xContent();
final XContentParser parser = xContent.createParser(
NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE,
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java
index 49acbe8cd2bc1..1d70778398e2e 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorIT.java
@@ -33,6 +33,7 @@
package org.opensearch.client;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
+
import org.opensearch.action.bulk.BulkItemResponse;
import org.opensearch.action.bulk.BulkProcessor;
import org.opensearch.action.bulk.BulkRequest;
@@ -42,13 +43,12 @@
import org.opensearch.action.get.MultiGetResponse;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.search.SearchRequest;
-import org.opensearch.common.Strings;
-import org.opensearch.core.common.bytes.BytesArray;
-import org.opensearch.common.unit.ByteSizeUnit;
-import org.opensearch.common.unit.ByteSizeValue;
import org.opensearch.common.unit.TimeValue;
+import org.opensearch.core.common.bytes.BytesArray;
+import org.opensearch.core.common.unit.ByteSizeUnit;
+import org.opensearch.core.common.unit.ByteSizeValue;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.search.SearchHit;
import org.hamcrest.Matcher;
@@ -278,12 +278,12 @@ public void testBulkProcessorConcurrentRequestsReadOnlyIndex() throws Exception
// let's make sure we get at least 1 item in the MultiGetRequest regardless of the randomising roulette
if (randomBoolean() || multiGetRequest.getItems().size() == 0) {
testDocs++;
- processor.add(new IndexRequest("test").id(Integer.toString(testDocs)).source(XContentType.JSON, "field", "value"));
+ processor.add(new IndexRequest("test").id(Integer.toString(testDocs)).source(MediaTypeRegistry.JSON, "field", "value"));
multiGetRequest.add("test", Integer.toString(testDocs));
} else {
testReadOnlyDocs++;
processor.add(
- new IndexRequest("test-ro").id(Integer.toString(testReadOnlyDocs)).source(XContentType.JSON, "field", "value")
+ new IndexRequest("test-ro").id(Integer.toString(testReadOnlyDocs)).source(MediaTypeRegistry.JSON, "field", "value")
);
}
}
@@ -334,9 +334,9 @@ public void testGlobalParametersAndSingleRequest() throws Exception {
processor.add(new IndexRequest() // <1>
- .source(XContentType.JSON, "user", "some user"));
+ .source(MediaTypeRegistry.JSON, "user", "some user"));
processor.add(new IndexRequest("blogs").id("1") // <2>
- .source(XContentType.JSON, "title", "some title"));
+ .source(MediaTypeRegistry.JSON, "title", "some title"));
}
// end::bulk-processor-mix-parameters
latch.await();
@@ -400,11 +400,11 @@ private MultiGetRequest indexDocs(BulkProcessor processor, int numDocs, String l
if (randomBoolean()) {
processor.add(
new IndexRequest(localIndex).id(Integer.toString(i))
- .source(XContentType.JSON, "field", randomRealisticUnicodeOfLengthBetween(1, 30))
+ .source(MediaTypeRegistry.JSON, "field", randomRealisticUnicodeOfLengthBetween(1, 30))
);
} else {
BytesArray data = bytesBulkRequest(localIndex, i);
- processor.add(data, globalIndex, globalPipeline, XContentType.JSON);
+ processor.add(data, globalIndex, globalPipeline, MediaTypeRegistry.JSON);
}
multiGetRequest.add(localIndex, Integer.toString(i));
}
@@ -423,7 +423,7 @@ private static BytesArray bytesBulkRequest(String localIndex, int id) throws IOE
XContentBuilder source = jsonBuilder().startObject().field("field", randomRealisticUnicodeOfLengthBetween(1, 30)).endObject();
- String request = Strings.toString(action) + "\n" + Strings.toString(source) + "\n";
+ String request = action + "\n" + source + "\n";
return new BytesArray(request);
}
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java
index 44bd085788203..3678cc042ba47 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/BulkProcessorRetryIT.java
@@ -40,8 +40,8 @@
import org.opensearch.action.get.MultiGetRequest;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.transport.RemoteTransportException;
import java.util.Collections;
@@ -170,7 +170,7 @@ private static MultiGetRequest indexDocs(BulkProcessor processor, int numDocs) {
for (int i = 1; i <= numDocs; i++) {
processor.add(
new IndexRequest(INDEX_NAME).id(Integer.toString(i))
- .source(XContentType.JSON, "field", randomRealisticUnicodeOfCodepointLengthBetween(1, 30))
+ .source(MediaTypeRegistry.JSON, "field", randomRealisticUnicodeOfCodepointLengthBetween(1, 30))
);
multiGetRequest.add(INDEX_NAME, Integer.toString(i));
}
@@ -180,7 +180,7 @@ private static MultiGetRequest indexDocs(BulkProcessor processor, int numDocs) {
/**
* Internal helper class to correlate backoff states with bulk responses. This is needed to check whether we maxed out the number
* of retries but still got rejected (which is perfectly fine and can also happen from time to time under heavy load).
- *
+ *
* This implementation relies on an implementation detail in Retry, namely that the bulk listener is notified on the same thread
* as the last call to the backoff policy's iterator. The advantage is that this is non-invasive to the rest of the production code.
*/
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java
index 35fc9d88e316c..d392aa842fb35 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/BulkRequestWithGlobalParametersIT.java
@@ -36,7 +36,7 @@
import org.opensearch.action.bulk.BulkResponse;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.search.SearchRequest;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.search.SearchHit;
import java.io.IOException;
@@ -59,8 +59,8 @@ public void testGlobalPipelineOnBulkRequest() throws IOException {
createFieldAddingPipleine("xyz", "fieldNameXYZ", "valueXYZ");
BulkRequest request = new BulkRequest();
- request.add(new IndexRequest("test").id("1").source(XContentType.JSON, "field", "bulk1"));
- request.add(new IndexRequest("test").id("2").source(XContentType.JSON, "field", "bulk2"));
+ request.add(new IndexRequest("test").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1"));
+ request.add(new IndexRequest("test").id("2").source(MediaTypeRegistry.JSON, "field", "bulk2"));
request.pipeline("xyz");
bulk(request);
@@ -76,8 +76,8 @@ public void testPipelineOnRequestOverridesGlobalPipeline() throws IOException {
BulkRequest request = new BulkRequest();
request.pipeline("globalId");
- request.add(new IndexRequest("test").id("1").source(XContentType.JSON, "field", "bulk1").setPipeline("perIndexId"));
- request.add(new IndexRequest("test").id("2").source(XContentType.JSON, "field", "bulk2").setPipeline("perIndexId"));
+ request.add(new IndexRequest("test").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1").setPipeline("perIndexId"));
+ request.add(new IndexRequest("test").id("2").source(MediaTypeRegistry.JSON, "field", "bulk2").setPipeline("perIndexId"));
bulk(request);
@@ -96,11 +96,11 @@ public void testMixPipelineOnRequestAndGlobal() throws IOException {
request.pipeline("globalId");
request.add(new IndexRequest("test").id("1")
- .source(XContentType.JSON, "field", "bulk1")
+ .source(MediaTypeRegistry.JSON, "field", "bulk1")
.setPipeline("perIndexId")); // <1>
request.add(new IndexRequest("test").id("2")
- .source(XContentType.JSON, "field", "bulk2")); // <2>
+ .source(MediaTypeRegistry.JSON, "field", "bulk2")); // <2>
// end::bulk-request-mix-pipeline
bulk(request);
@@ -116,8 +116,8 @@ public void testMixPipelineOnRequestAndGlobal() throws IOException {
public void testGlobalIndex() throws IOException {
BulkRequest request = new BulkRequest("global_index");
- request.add(new IndexRequest().id("1").source(XContentType.JSON, "field", "bulk1"));
- request.add(new IndexRequest().id("2").source(XContentType.JSON, "field", "bulk2"));
+ request.add(new IndexRequest().id("1").source(MediaTypeRegistry.JSON, "field", "bulk1"));
+ request.add(new IndexRequest().id("2").source(MediaTypeRegistry.JSON, "field", "bulk2"));
bulk(request);
@@ -128,10 +128,10 @@ public void testGlobalIndex() throws IOException {
@SuppressWarnings("unchecked")
public void testIndexGlobalAndPerRequest() throws IOException {
BulkRequest request = new BulkRequest("global_index");
- request.add(new IndexRequest("local_index").id("1").source(XContentType.JSON, "field", "bulk1"));
+ request.add(new IndexRequest("local_index").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1"));
request.add(
new IndexRequest().id("2") // will take global index
- .source(XContentType.JSON, "field", "bulk2")
+ .source(MediaTypeRegistry.JSON, "field", "bulk2")
);
bulk(request);
@@ -143,8 +143,8 @@ public void testIndexGlobalAndPerRequest() throws IOException {
public void testGlobalRouting() throws IOException {
createIndexWithMultipleShards("index");
BulkRequest request = new BulkRequest((String) null);
- request.add(new IndexRequest("index").id("1").source(XContentType.JSON, "field", "bulk1"));
- request.add(new IndexRequest("index").id("2").source(XContentType.JSON, "field", "bulk1"));
+ request.add(new IndexRequest("index").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1"));
+ request.add(new IndexRequest("index").id("2").source(MediaTypeRegistry.JSON, "field", "bulk1"));
request.routing("1");
bulk(request);
@@ -158,8 +158,8 @@ public void testGlobalRouting() throws IOException {
public void testMixLocalAndGlobalRouting() throws IOException {
BulkRequest request = new BulkRequest((String) null);
request.routing("globalRouting");
- request.add(new IndexRequest("index").id("1").source(XContentType.JSON, "field", "bulk1"));
- request.add(new IndexRequest("index").id("2").routing("localRouting").source(XContentType.JSON, "field", "bulk1"));
+ request.add(new IndexRequest("index").id("1").source(MediaTypeRegistry.JSON, "field", "bulk1"));
+ request.add(new IndexRequest("index").id("2").routing("localRouting").source(MediaTypeRegistry.JSON, "field", "bulk1"));
bulk(request);
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java
index 2ac0eee407b95..79481fd03b2a1 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterClientIT.java
@@ -61,12 +61,12 @@
import org.opensearch.cluster.routing.allocation.decider.EnableAllocationDecider;
import org.opensearch.common.compress.CompressedXContent;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.unit.ByteSizeUnit;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.common.xcontent.support.XContentMapValues;
-import org.opensearch.indices.recovery.RecoverySettings;
+import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.indices.recovery.RecoverySettings;
import org.opensearch.transport.RemoteClusterService;
import org.opensearch.transport.SniffConnectionStrategy;
@@ -125,7 +125,7 @@ public void testClusterPutSettings() throws IOException {
ClusterUpdateSettingsRequest resetRequest = new ClusterUpdateSettingsRequest();
resetRequest.transientSettings(Settings.builder().putNull(transientSettingKey));
- resetRequest.persistentSettings("{\"" + persistentSettingKey + "\": null }", XContentType.JSON);
+ resetRequest.persistentSettings("{\"" + persistentSettingKey + "\": null }", MediaTypeRegistry.JSON);
ClusterUpdateSettingsResponse resetResponse = execute(
resetRequest,
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterRequestConvertersTests.java
index f201599632969..3415868c9f8c6 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/ClusterRequestConvertersTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/ClusterRequestConvertersTests.java
@@ -32,6 +32,8 @@
package org.opensearch.client;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.opensearch.action.admin.cluster.health.ClusterHealthRequest;
import org.opensearch.action.admin.cluster.settings.ClusterGetSettingsRequest;
import org.opensearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest;
@@ -40,10 +42,8 @@
import org.opensearch.client.cluster.RemoteInfoRequest;
import org.opensearch.cluster.health.ClusterHealthStatus;
import org.opensearch.common.Priority;
-import org.opensearch.common.util.CollectionUtils;
+import org.opensearch.core.common.util.CollectionUtils;
import org.opensearch.test.OpenSearchTestCase;
-import org.apache.hc.client5.http.classic.methods.HttpGet;
-import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java
index eaf8f4f8efff7..da9f790215669 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/CrudIT.java
@@ -58,17 +58,19 @@
import org.opensearch.client.core.TermVectorsRequest;
import org.opensearch.client.core.TermVectorsResponse;
import org.opensearch.client.indices.GetIndexRequest;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.unit.ByteSizeUnit;
-import org.opensearch.common.unit.ByteSizeValue;
-import org.opensearch.core.common.Strings;
-import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.common.Strings;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.common.unit.ByteSizeUnit;
+import org.opensearch.core.common.unit.ByteSizeValue;
+import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaType;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.index.VersionType;
import org.opensearch.index.get.GetResult;
-import org.opensearch.core.rest.RestStatus;
import org.opensearch.script.Script;
import org.opensearch.script.ScriptType;
import org.opensearch.search.fetch.subphase.FetchSourceContext;
@@ -202,7 +204,7 @@ public void testExists() throws IOException {
assertFalse(execute(getRequest, highLevelClient()::exists, highLevelClient()::existsAsync));
}
IndexRequest index = new IndexRequest("index").id("id");
- index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", XContentType.JSON);
+ index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", MediaTypeRegistry.JSON);
index.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
highLevelClient().index(index, RequestOptions.DEFAULT);
{
@@ -227,7 +229,7 @@ public void testDeprecatedSourceExists() throws IOException {
assertFalse(execute(getRequest, highLevelClient()::existsSource, highLevelClient()::existsSourceAsync));
}
IndexRequest index = new IndexRequest("index").id("id");
- index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", XContentType.JSON);
+ index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", MediaTypeRegistry.JSON);
index.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
highLevelClient().index(index, RequestOptions.DEFAULT);
{
@@ -250,7 +252,7 @@ public void testSourceExists() throws IOException {
assertFalse(execute(getRequest, highLevelClient()::existsSource, highLevelClient()::existsSourceAsync));
}
IndexRequest index = new IndexRequest("index").id("id");
- index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", XContentType.JSON);
+ index.source("{\"field1\":\"value1\",\"field2\":\"value2\"}", MediaTypeRegistry.JSON);
index.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
highLevelClient().index(index, RequestOptions.DEFAULT);
{
@@ -274,9 +276,9 @@ public void testSourceDoesNotExist() throws IOException {
RestStatus.OK,
highLevelClient().bulk(
new BulkRequest().add(
- new IndexRequest(noSourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON)
+ new IndexRequest(noSourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(noSourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON))
+ .add(new IndexRequest(noSourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON))
.setRefreshPolicy(RefreshPolicy.IMMEDIATE),
RequestOptions.DEFAULT
).status()
@@ -306,7 +308,7 @@ public void testGet() throws IOException {
}
IndexRequest index = new IndexRequest("index").id("id");
String document = "{\"field1\":\"value1\",\"field2\":\"value2\"}";
- index.source(document, XContentType.JSON);
+ index.source(document, MediaTypeRegistry.JSON);
index.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
highLevelClient().index(index, RequestOptions.DEFAULT);
{
@@ -406,10 +408,10 @@ public void testMultiGet() throws IOException {
BulkRequest bulk = new BulkRequest();
bulk.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
IndexRequest index = new IndexRequest("index").id("id1");
- index.source("{\"field\":\"value1\"}", XContentType.JSON);
+ index.source("{\"field\":\"value1\"}", MediaTypeRegistry.JSON);
bulk.add(index);
index = new IndexRequest("index").id("id2");
- index.source("{\"field\":\"value2\"}", XContentType.JSON);
+ index.source("{\"field\":\"value2\"}", MediaTypeRegistry.JSON);
bulk.add(index);
highLevelClient().bulk(bulk, RequestOptions.DEFAULT);
{
@@ -436,8 +438,8 @@ public void testMultiGet() throws IOException {
public void testMultiGetWithIds() throws IOException {
BulkRequest bulk = new BulkRequest();
bulk.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
- bulk.add(new IndexRequest("index").id("id1").source("{\"field\":\"value1\"}", XContentType.JSON));
- bulk.add(new IndexRequest("index").id("id2").source("{\"field\":\"value2\"}", XContentType.JSON));
+ bulk.add(new IndexRequest("index").id("id1").source("{\"field\":\"value1\"}", MediaTypeRegistry.JSON));
+ bulk.add(new IndexRequest("index").id("id2").source("{\"field\":\"value2\"}", MediaTypeRegistry.JSON));
MultiGetRequest multiGetRequest = new MultiGetRequest();
multiGetRequest.add("index", "id1");
@@ -457,7 +459,7 @@ public void testGetSource() throws IOException {
}
IndexRequest index = new IndexRequest("index").id("id");
String document = "{\"field1\":\"value1\",\"field2\":\"value2\"}";
- index.source(document, XContentType.JSON);
+ index.source(document, MediaTypeRegistry.JSON);
index.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
highLevelClient().index(index, RequestOptions.DEFAULT);
{
@@ -815,7 +817,7 @@ public void testUpdate() throws IOException {
{
IllegalStateException exception = expectThrows(IllegalStateException.class, () -> {
UpdateRequest updateRequest = new UpdateRequest("index", "id");
- updateRequest.doc(new IndexRequest().source(Collections.singletonMap("field", "doc"), XContentType.JSON));
+ updateRequest.doc(new IndexRequest().source(Collections.singletonMap("field", "doc"), MediaTypeRegistry.JSON));
updateRequest.upsert(new IndexRequest().source(Collections.singletonMap("field", "upsert"), XContentType.YAML));
execute(updateRequest, highLevelClient()::update, highLevelClient()::updateAsync);
});
@@ -827,7 +829,7 @@ public void testUpdate() throws IOException {
{
OpenSearchException exception = expectThrows(OpenSearchException.class, () -> {
UpdateRequest updateRequest = new UpdateRequest("index", "require_alias").setRequireAlias(true);
- updateRequest.doc(new IndexRequest().source(Collections.singletonMap("field", "doc"), XContentType.JSON));
+ updateRequest.doc(new IndexRequest().source(Collections.singletonMap("field", "doc"), MediaTypeRegistry.JSON));
execute(updateRequest, highLevelClient()::update, highLevelClient()::updateAsync);
});
assertEquals(RestStatus.NOT_FOUND, exception.status());
@@ -842,7 +844,7 @@ public void testBulk() throws IOException {
int nbItems = randomIntBetween(10, 100);
boolean[] errors = new boolean[nbItems];
- XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);
+ MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE);
BulkRequest bulkRequest = new BulkRequest();
for (int i = 0; i < nbItems; i++) {
@@ -863,10 +865,10 @@ public void testBulk() throws IOException {
} else {
BytesReference source = BytesReference.bytes(
- XContentBuilder.builder(xContentType.xContent()).startObject().field("id", i).endObject()
+ XContentBuilder.builder(mediaType.xContent()).startObject().field("id", i).endObject()
);
if (opType == DocWriteRequest.OpType.INDEX) {
- IndexRequest indexRequest = new IndexRequest("index").id(id).source(source, xContentType);
+ IndexRequest indexRequest = new IndexRequest("index").id(id).source(source, mediaType);
if (erroneous) {
indexRequest.setIfSeqNo(12L);
indexRequest.setIfPrimaryTerm(12L);
@@ -874,14 +876,14 @@ public void testBulk() throws IOException {
bulkRequest.add(indexRequest);
} else if (opType == DocWriteRequest.OpType.CREATE) {
- IndexRequest createRequest = new IndexRequest("index").id(id).source(source, xContentType).create(true);
+ IndexRequest createRequest = new IndexRequest("index").id(id).source(source, mediaType).create(true);
if (erroneous) {
assertEquals(RestStatus.CREATED, highLevelClient().index(createRequest, RequestOptions.DEFAULT).status());
}
bulkRequest.add(createRequest);
} else if (opType == DocWriteRequest.OpType.UPDATE) {
- UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(source, xContentType));
+ UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(source, mediaType));
if (erroneous == false) {
assertEquals(
RestStatus.CREATED,
@@ -905,7 +907,7 @@ public void testBulkProcessorIntegration() throws IOException {
int nbItems = randomIntBetween(10, 100);
boolean[] errors = new boolean[nbItems];
- XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);
+ MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE);
AtomicReference responseRef = new AtomicReference<>();
AtomicReference requestRef = new AtomicReference<>();
@@ -953,7 +955,7 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure)
} else {
if (opType == DocWriteRequest.OpType.INDEX) {
- IndexRequest indexRequest = new IndexRequest("index").id(id).source(xContentType, "id", i);
+ IndexRequest indexRequest = new IndexRequest("index").id(id).source(mediaType, "id", i);
if (erroneous) {
indexRequest.setIfSeqNo(12L);
indexRequest.setIfPrimaryTerm(12L);
@@ -961,14 +963,14 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure)
processor.add(indexRequest);
} else if (opType == DocWriteRequest.OpType.CREATE) {
- IndexRequest createRequest = new IndexRequest("index").id(id).source(xContentType, "id", i).create(true);
+ IndexRequest createRequest = new IndexRequest("index").id(id).source(mediaType, "id", i).create(true);
if (erroneous) {
assertEquals(RestStatus.CREATED, highLevelClient().index(createRequest, RequestOptions.DEFAULT).status());
}
processor.add(createRequest);
} else if (opType == DocWriteRequest.OpType.UPDATE) {
- UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(xContentType, "id", i));
+ UpdateRequest updateRequest = new UpdateRequest("index", id).doc(new IndexRequest().source(mediaType, "id", i));
if (erroneous == false) {
assertEquals(
RestStatus.CREATED,
@@ -1106,9 +1108,12 @@ public void testTermvectors() throws IOException {
RestStatus.OK,
highLevelClient().bulk(
new BulkRequest().add(
- new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("field", "value1"), XContentType.JSON)
+ new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("field", "value1"), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("field", "value2"), XContentType.JSON))
+ .add(
+ new IndexRequest(sourceIndex).id("2")
+ .source(Collections.singletonMap("field", "value2"), MediaTypeRegistry.JSON)
+ )
.setRefreshPolicy(RefreshPolicy.IMMEDIATE),
RequestOptions.DEFAULT
).status()
@@ -1201,8 +1206,8 @@ public void testMultiTermvectors() throws IOException {
assertEquals(
RestStatus.OK,
highLevelClient().bulk(
- new BulkRequest().add(new IndexRequest(sourceIndex).id("1").source(doc1, XContentType.JSON))
- .add(new IndexRequest(sourceIndex).id("2").source(doc2, XContentType.JSON))
+ new BulkRequest().add(new IndexRequest(sourceIndex).id("1").source(doc1, MediaTypeRegistry.JSON))
+ .add(new IndexRequest(sourceIndex).id("2").source(doc2, MediaTypeRegistry.JSON))
.setRefreshPolicy(RefreshPolicy.IMMEDIATE),
RequestOptions.DEFAULT
).status()
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java
index 972c96999945f..fe7392cb0c0ce 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/CustomRestHighLevelClientTests.java
@@ -43,14 +43,14 @@
import org.apache.lucene.util.BytesRef;
import org.opensearch.Build;
import org.opensearch.Version;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.main.MainRequest;
import org.opensearch.action.main.MainResponse;
import org.opensearch.action.support.PlainActionFuture;
import org.opensearch.cluster.ClusterName;
import org.opensearch.common.SuppressForbidden;
-import org.opensearch.common.xcontent.XContentHelper;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.core.xcontent.XContentHelper;
import org.opensearch.test.OpenSearchTestCase;
import org.junit.Before;
@@ -174,7 +174,7 @@ private Response mockPerformRequest(Request request) throws IOException {
when(mockResponse.getStatusLine()).thenReturn(new StatusLine(protocol, 200, "OK"));
MainResponse response = new MainResponse(httpHeader.getValue(), Version.CURRENT, ClusterName.DEFAULT, "_na", Build.CURRENT);
- BytesRef bytesRef = XContentHelper.toXContent(response, XContentType.JSON, false).toBytesRef();
+ BytesRef bytesRef = XContentHelper.toXContent(response, MediaTypeRegistry.JSON, false).toBytesRef();
when(mockResponse.getEntity()).thenReturn(new ByteArrayEntity(bytesRef.bytes, ContentType.APPLICATION_JSON));
RequestLine requestLine = new RequestLine(HttpGet.METHOD_NAME, ENDPOINT, protocol);
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/GetAliasesResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/GetAliasesResponseTests.java
index 96f958a4ad2d8..245a720dc9825 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/GetAliasesResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/GetAliasesResponseTests.java
@@ -33,9 +33,9 @@
package org.opensearch.client;
import org.opensearch.cluster.metadata.AliasMetadata;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.json.JsonXContent;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.test.AbstractXContentTestCase;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesClientIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesClientIT.java
index 8ca5c5fa58742..c8eafb88b7495 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesClientIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesClientIT.java
@@ -108,23 +108,23 @@
import org.opensearch.cluster.metadata.MappingMetadata;
import org.opensearch.cluster.metadata.Template;
import org.opensearch.common.ValidationException;
-import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.common.compress.CompressedXContent;
import org.opensearch.common.settings.Setting;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.unit.ByteSizeUnit;
-import org.opensearch.common.unit.ByteSizeValue;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.core.common.Strings;
-import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentFactory;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.common.xcontent.json.JsonXContent;
import org.opensearch.common.xcontent.support.XContentMapValues;
+import org.opensearch.core.common.Strings;
+import org.opensearch.core.common.bytes.BytesArray;
+import org.opensearch.core.common.unit.ByteSizeUnit;
+import org.opensearch.core.common.unit.ByteSizeValue;
+import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.index.IndexSettings;
import org.opensearch.index.query.QueryBuilder;
import org.opensearch.index.query.QueryBuilders;
-import org.opensearch.core.rest.RestStatus;
import java.io.IOException;
import java.util.Arrays;
@@ -134,6 +134,10 @@
import java.util.Map;
import java.util.stream.Collectors;
+import static org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS;
+import static org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS;
+import static org.opensearch.common.xcontent.support.XContentMapValues.extractRawValues;
+import static org.opensearch.common.xcontent.support.XContentMapValues.extractValue;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.Matchers.arrayContainingInAnyOrder;
import static org.hamcrest.Matchers.contains;
@@ -149,10 +153,6 @@
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.core.IsInstanceOf.instanceOf;
-import static org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS;
-import static org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS;
-import static org.opensearch.common.xcontent.support.XContentMapValues.extractRawValues;
-import static org.opensearch.common.xcontent.support.XContentMapValues.extractValue;
public class IndicesClientIT extends OpenSearchRestHighLevelClientTestCase {
@@ -1074,7 +1074,7 @@ public void testRollover() throws IOException {
}
{
String mappings = "{\"properties\":{\"field2\":{\"type\":\"keyword\"}}}";
- rolloverRequest.getCreateIndexRequest().mapping(mappings, XContentType.JSON);
+ rolloverRequest.getCreateIndexRequest().mapping(mappings, MediaTypeRegistry.JSON);
rolloverRequest.dryRun(false);
rolloverRequest.addMaxIndexSizeCondition(new ByteSizeValue(1, ByteSizeUnit.MB));
RolloverResponse rolloverResponse = execute(
@@ -1489,7 +1489,7 @@ public void testPutTemplate() throws Exception {
.order(10)
.create(randomBoolean())
.settings(Settings.builder().put("number_of_shards", "3").put("number_of_replicas", "0"))
- .mapping("{ \"properties\": { \"host_name\": { \"type\": \"keyword\" } } }", XContentType.JSON)
+ .mapping("{ \"properties\": { \"host_name\": { \"type\": \"keyword\" } } }", MediaTypeRegistry.JSON)
.alias(new Alias("alias-1").indexRouting("abc"))
.alias(new Alias("alias-1").indexRouting("abc"))
.alias(new Alias("{index}-write").searchRouting("xyz"));
@@ -1558,7 +1558,7 @@ public void testPutTemplateWithTypesUsingUntypedAPI() throws Exception {
+ " }"
+ " }"
+ "}",
- XContentType.JSON
+ MediaTypeRegistry.JSON
)
.alias(new Alias("alias-1").indexRouting("abc"))
.alias(new Alias("{index}-write").searchRouting("xyz"));
@@ -1664,7 +1664,7 @@ public void testCRUDIndexTemplate() throws Exception {
equalTo(true)
);
PutIndexTemplateRequest putTemplate2 = new PutIndexTemplateRequest("template-2").patterns(Arrays.asList("pattern-2", "name-2"))
- .mapping("{\"properties\": { \"name\": { \"type\": \"text\" }}}", XContentType.JSON)
+ .mapping("{\"properties\": { \"name\": { \"type\": \"text\" }}}", MediaTypeRegistry.JSON)
.settings(Settings.builder().put("number_of_shards", "2").put("number_of_replicas", "0"));
assertThat(
execute(putTemplate2, client.indices()::putTemplate, client.indices()::putTemplateAsync).isAcknowledged(),
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java
index e21619ff15ef6..c3a0f049f375e 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/IndicesRequestConvertersTests.java
@@ -74,12 +74,12 @@
import org.opensearch.common.CheckedFunction;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.util.CollectionUtils;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.common.Strings;
+import org.opensearch.core.common.unit.ByteSizeValue;
+import org.opensearch.core.common.util.CollectionUtils;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.test.OpenSearchTestCase;
import org.junit.Assert;
-import org.opensearch.common.unit.ByteSizeValue;
import java.io.IOException;
import java.util.Arrays;
@@ -858,7 +858,7 @@ public void testPutTemplateRequest() throws Exception {
+ "\" : { \"type\" : \""
+ OpenSearchTestCase.randomFrom("text", "keyword")
+ "\" }}}",
- XContentType.JSON
+ MediaTypeRegistry.JSON
);
}
if (OpenSearchTestCase.randomBoolean()) {
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IngestClientIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/IngestClientIT.java
index e3c8197dc2c90..33bff06a83065 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/IngestClientIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/IngestClientIT.java
@@ -42,9 +42,9 @@
import org.opensearch.action.ingest.SimulatePipelineRequest;
import org.opensearch.action.ingest.SimulatePipelineResponse;
import org.opensearch.action.support.master.AcknowledgedResponse;
+import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.ingest.PipelineConfiguration;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java
index 0f377720b7aed..38dde4be3dd8e 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/IngestRequestConvertersTests.java
@@ -32,18 +32,18 @@
package org.opensearch.client;
+import org.apache.hc.client5.http.classic.methods.HttpDelete;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.opensearch.action.ingest.DeletePipelineRequest;
import org.opensearch.action.ingest.GetPipelineRequest;
import org.opensearch.action.ingest.PutPipelineRequest;
import org.opensearch.action.ingest.SimulatePipelineRequest;
import org.opensearch.action.support.master.AcknowledgedRequest;
import org.opensearch.core.common.bytes.BytesArray;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.test.OpenSearchTestCase;
-import org.apache.hc.client5.http.classic.methods.HttpDelete;
-import org.apache.hc.client5.http.classic.methods.HttpGet;
-import org.apache.hc.client5.http.classic.methods.HttpPost;
-import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.junit.Assert;
import java.io.IOException;
@@ -59,7 +59,7 @@ public void testPutPipeline() throws IOException {
PutPipelineRequest request = new PutPipelineRequest(
"some_pipeline_id",
new BytesArray("{}".getBytes(StandardCharsets.UTF_8)),
- XContentType.JSON
+ MediaTypeRegistry.JSON
);
Map expectedParams = new HashMap<>();
RequestConvertersTests.setRandomClusterManagerTimeout(request, expectedParams);
@@ -130,7 +130,7 @@ public void testSimulatePipeline() throws IOException {
+ "}";
SimulatePipelineRequest request = new SimulatePipelineRequest(
new BytesArray(json.getBytes(StandardCharsets.UTF_8)),
- XContentType.JSON
+ MediaTypeRegistry.JSON
);
request.setId(pipelineId);
request.setVerbose(verbose);
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/MockRestHighLevelTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/MockRestHighLevelTests.java
index e1179c0f24cb8..c7cd382d64908 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/MockRestHighLevelTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/MockRestHighLevelTests.java
@@ -32,12 +32,12 @@
package org.opensearch.client;
-import org.opensearch.test.OpenSearchTestCase;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.ProtocolVersion;
import org.apache.hc.core5.http.message.RequestLine;
import org.apache.hc.core5.http.message.StatusLine;
+import org.opensearch.test.OpenSearchTestCase;
import org.junit.Before;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java b/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java
index ee1f217f47ef2..b0a7d1e3578c0 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/OpenSearchRestHighLevelClientTestCase.java
@@ -32,8 +32,9 @@
package org.opensearch.client;
+import org.apache.hc.core5.http.ParseException;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.opensearch.OpenSearchParseException;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse;
import org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup;
@@ -48,21 +49,21 @@
import org.opensearch.client.indices.CreateIndexRequest;
import org.opensearch.common.Booleans;
import org.opensearch.common.CheckedRunnable;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.util.concurrent.ThreadContext;
-import org.opensearch.core.xcontent.XContentBuilder;
+import org.opensearch.common.util.io.IOUtils;
import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.common.xcontent.json.JsonXContent;
-import org.opensearch.common.util.io.IOUtils;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.tasks.TaskId;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.ingest.Pipeline;
import org.opensearch.search.SearchHit;
import org.opensearch.search.SearchModule;
-import org.opensearch.tasks.TaskId;
import org.opensearch.test.rest.OpenSearchRestTestCase;
-import org.apache.hc.core5.http.ParseException;
-import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.junit.AfterClass;
import org.junit.Before;
@@ -223,7 +224,7 @@ protected static void createFieldAddingPipleine(String id, String fieldName, Str
.endArray()
.endObject();
- createPipeline(new PutPipelineRequest(id, BytesReference.bytes(pipeline), XContentType.JSON));
+ createPipeline(new PutPipelineRequest(id, BytesReference.bytes(pipeline), MediaTypeRegistry.JSON));
}
protected static void createPipeline(String pipelineId) throws IOException {
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/PitIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/PitIT.java
index 1f10deb400ecc..b0990560b08ba 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/PitIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/PitIT.java
@@ -10,9 +10,7 @@
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
-import org.junit.Before;
import org.opensearch.OpenSearchStatusException;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.search.CreatePitRequest;
import org.opensearch.action.search.CreatePitResponse;
import org.opensearch.action.search.DeletePitInfo;
@@ -20,11 +18,12 @@
import org.opensearch.action.search.DeletePitResponse;
import org.opensearch.action.search.GetAllPitNodesResponse;
import org.opensearch.common.unit.TimeValue;
+import org.opensearch.core.action.ActionListener;
+import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
-import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
@@ -72,7 +71,7 @@ public void testCreateAndDeletePit() throws IOException {
assertTrue(deletePitResponse.getDeletePitResults().get(0).getPitId().equals(createPitResponse.getId()));
}
- public void testDeleteAllAndListAllPits() throws IOException, InterruptedException {
+ public void testDeleteAllAndListAllPits() throws Exception {
CreatePitRequest pitRequest = new CreatePitRequest(new TimeValue(1, TimeUnit.DAYS), true, "index");
CreatePitResponse pitResponse = execute(pitRequest, highLevelClient()::createPit, highLevelClient()::createPitAsync);
CreatePitResponse pitResponse1 = execute(pitRequest, highLevelClient()::createPit, highLevelClient()::createPitAsync);
@@ -91,11 +90,9 @@ public void testDeleteAllAndListAllPits() throws IOException, InterruptedExcepti
List pits = getAllPitResponse.getPitInfos().stream().map(r -> r.getPitId()).collect(Collectors.toList());
assertTrue(pits.contains(pitResponse.getId()));
assertTrue(pits.contains(pitResponse1.getId()));
- CountDownLatch countDownLatch = new CountDownLatch(1);
ActionListener deletePitListener = new ActionListener<>() {
@Override
public void onResponse(DeletePitResponse response) {
- countDownLatch.countDown();
for (DeletePitInfo deletePitInfo : response.getDeletePitResults()) {
assertTrue(deletePitInfo.isSuccessful());
}
@@ -103,19 +100,20 @@ public void onResponse(DeletePitResponse response) {
@Override
public void onFailure(Exception e) {
- countDownLatch.countDown();
if (!(e instanceof OpenSearchStatusException)) {
throw new AssertionError("Delete all failed");
}
}
};
final CreatePitResponse pitResponse3 = execute(pitRequest, highLevelClient()::createPit, highLevelClient()::createPitAsync);
-
+ assertTrue(pitResponse3.getId() != null);
ActionListener getPitsListener = new ActionListener() {
@Override
public void onResponse(GetAllPitNodesResponse response) {
List pits = response.getPitInfos().stream().map(r -> r.getPitId()).collect(Collectors.toList());
assertTrue(pits.contains(pitResponse3.getId()));
+ // delete all pits
+ highLevelClient().deleteAllPitsAsync(RequestOptions.DEFAULT, deletePitListener);
}
@Override
@@ -126,11 +124,12 @@ public void onFailure(Exception e) {
}
};
highLevelClient().getAllPitsAsync(RequestOptions.DEFAULT, getPitsListener);
- highLevelClient().deleteAllPitsAsync(RequestOptions.DEFAULT, deletePitListener);
- assertTrue(countDownLatch.await(10, TimeUnit.SECONDS));
+
// validate no pits case
- getAllPitResponse = highLevelClient().getAllPits(RequestOptions.DEFAULT);
- assertTrue(getAllPitResponse.getPitInfos().size() == 0);
- highLevelClient().deleteAllPitsAsync(RequestOptions.DEFAULT, deletePitListener);
+ assertBusy(() -> {
+ GetAllPitNodesResponse getAllPitResponse1 = highLevelClient().getAllPits(RequestOptions.DEFAULT);
+ assertTrue(getAllPitResponse1.getPitInfos().size() == 0);
+ highLevelClient().deleteAllPitsAsync(RequestOptions.DEFAULT, deletePitListener);
+ });
}
}
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RankEvalIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/RankEvalIT.java
index 07e5b1627942e..47add92ecaccd 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/RankEvalIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/RankEvalIT.java
@@ -32,7 +32,6 @@
package org.opensearch.client;
-import org.junit.Before;
import org.opensearch.action.search.SearchRequest;
import org.opensearch.action.support.IndicesOptions;
import org.opensearch.index.query.MatchAllQueryBuilder;
@@ -50,6 +49,7 @@
import org.opensearch.index.rankeval.RatedSearchHit;
import org.opensearch.index.rankeval.RecallAtK;
import org.opensearch.search.builder.SearchSourceBuilder;
+import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java
index 65888e79683e3..2457bafdc6a22 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/ReindexIT.java
@@ -33,7 +33,6 @@
package org.opensearch.client;
import org.opensearch.OpenSearchStatusException;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse;
import org.opensearch.action.bulk.BulkItemResponse;
import org.opensearch.action.bulk.BulkRequest;
@@ -42,15 +41,16 @@
import org.opensearch.action.support.WriteRequest;
import org.opensearch.client.tasks.TaskSubmissionResponse;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.tasks.TaskId;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.index.query.IdsQueryBuilder;
import org.opensearch.index.reindex.BulkByScrollResponse;
import org.opensearch.index.reindex.DeleteByQueryAction;
import org.opensearch.index.reindex.DeleteByQueryRequest;
import org.opensearch.index.reindex.ReindexRequest;
-import org.opensearch.core.rest.RestStatus;
import org.opensearch.tasks.RawTaskStatus;
-import org.opensearch.tasks.TaskId;
import java.io.IOException;
import java.util.Collections;
@@ -76,9 +76,9 @@ public void testReindex() throws IOException {
createIndex(sourceIndex, settings);
createIndex(destinationIndex, settings);
BulkRequest bulkRequest = new BulkRequest().add(
- new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)
+ new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON))
+ .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), MediaTypeRegistry.JSON))
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status());
}
@@ -132,9 +132,9 @@ public void testReindexTask() throws Exception {
createIndex(sourceIndex, settings);
createIndex(destinationIndex, settings);
BulkRequest bulkRequest = new BulkRequest().add(
- new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)
+ new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON))
+ .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), MediaTypeRegistry.JSON))
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status());
}
@@ -163,9 +163,9 @@ public void testReindexConflict() throws IOException {
createIndex(sourceIndex, settings);
createIndex(destIndex, settings);
final BulkRequest bulkRequest = new BulkRequest().add(
- new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)
+ new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", "bar"), XContentType.JSON))
+ .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON))
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
assertThat(highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status(), equalTo(RestStatus.OK));
@@ -205,10 +205,10 @@ public void testDeleteByQuery() throws Exception {
RestStatus.OK,
highLevelClient().bulk(
new BulkRequest().add(
- new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON)
+ new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON))
- .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), XContentType.JSON))
+ .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON))
+ .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), MediaTypeRegistry.JSON))
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE),
RequestOptions.DEFAULT
).status()
@@ -305,10 +305,10 @@ public void testDeleteByQueryTask() throws Exception {
RestStatus.OK,
highLevelClient().bulk(
new BulkRequest().add(
- new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON)
+ new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON))
- .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), XContentType.JSON))
+ .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON))
+ .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), MediaTypeRegistry.JSON))
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE),
RequestOptions.DEFAULT
).status()
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java
index 15a99b3e91685..084d754275dec 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/RequestConvertersTests.java
@@ -32,6 +32,14 @@
package org.opensearch.client;
+import org.apache.hc.client5.http.classic.methods.HttpDelete;
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.client5.http.classic.methods.HttpHead;
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.classic.methods.HttpPut;
+import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
+import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.opensearch.action.DocWriteRequest;
import org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest;
import org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest;
@@ -54,8 +62,8 @@
import org.opensearch.action.support.ActiveShardCount;
import org.opensearch.action.support.IndicesOptions;
import org.opensearch.action.support.WriteRequest;
-import org.opensearch.action.support.master.AcknowledgedRequest;
import org.opensearch.action.support.clustermanager.ClusterManagerNodeRequest;
+import org.opensearch.action.support.master.AcknowledgedRequest;
import org.opensearch.action.support.replication.ReplicationRequest;
import org.opensearch.action.update.UpdateRequest;
import org.opensearch.client.RequestConverters.EndpointBuilder;
@@ -65,18 +73,19 @@
import org.opensearch.client.core.TermVectorsRequest;
import org.opensearch.client.indices.AnalyzeRequest;
import org.opensearch.common.CheckedBiConsumer;
-import org.opensearch.core.common.bytes.BytesArray;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.collect.Tuple;
import org.opensearch.common.io.Streams;
import org.opensearch.common.logging.DeprecationLogger;
import org.opensearch.common.lucene.uid.Versions;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.common.xcontent.json.JsonXContent;
import org.opensearch.core.common.Strings;
+import org.opensearch.core.common.bytes.BytesArray;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.tasks.TaskId;
import org.opensearch.core.xcontent.MediaType;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
@@ -110,17 +119,8 @@
import org.opensearch.search.rescore.QueryRescorerBuilder;
import org.opensearch.search.suggest.SuggestBuilder;
import org.opensearch.search.suggest.completion.CompletionSuggestionBuilder;
-import org.opensearch.tasks.TaskId;
import org.opensearch.test.OpenSearchTestCase;
import org.opensearch.test.RandomObjects;
-import org.apache.hc.client5.http.classic.methods.HttpDelete;
-import org.apache.hc.client5.http.classic.methods.HttpGet;
-import org.apache.hc.client5.http.classic.methods.HttpHead;
-import org.apache.hc.client5.http.classic.methods.HttpPost;
-import org.apache.hc.client5.http.classic.methods.HttpPut;
-import org.apache.hc.core5.http.HttpEntity;
-import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
-import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.hamcrest.Matchers;
import java.io.IOException;
@@ -852,7 +852,7 @@ private static void setRandomIfSeqNoAndTerm(DocWriteRequest> request, Map {
UpdateRequest updateRequest = new UpdateRequest();
- updateRequest.doc(new IndexRequest().source(singletonMap("field", "doc"), XContentType.JSON));
+ updateRequest.doc(new IndexRequest().source(singletonMap("field", "doc"), MediaTypeRegistry.JSON));
updateRequest.upsert(new IndexRequest().source(singletonMap("field", "upsert"), XContentType.YAML));
RequestConverters.update(updateRequest);
});
@@ -876,7 +876,7 @@ public void testBulk() throws IOException {
setRandomRefreshPolicy(bulkRequest::setRefreshPolicy, expectedParams);
- XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);
+ MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE);
int nbItems = randomIntBetween(10, 100);
DocWriteRequest>[] requests = new DocWriteRequest>[nbItems];
@@ -884,21 +884,21 @@ public void testBulk() throws IOException {
String index = randomAlphaOfLength(5);
String id = randomAlphaOfLength(5);
- BytesReference source = RandomObjects.randomSource(random(), xContentType);
+ BytesReference source = RandomObjects.randomSource(random(), mediaType);
DocWriteRequest.OpType opType = randomFrom(DocWriteRequest.OpType.values());
DocWriteRequest> docWriteRequest;
if (opType == DocWriteRequest.OpType.INDEX) {
- IndexRequest indexRequest = new IndexRequest(index).id(id).source(source, xContentType);
+ IndexRequest indexRequest = new IndexRequest(index).id(id).source(source, mediaType);
docWriteRequest = indexRequest;
if (randomBoolean()) {
indexRequest.setPipeline(randomAlphaOfLength(5));
}
} else if (opType == DocWriteRequest.OpType.CREATE) {
- IndexRequest createRequest = new IndexRequest(index).id(id).source(source, xContentType).create(true);
+ IndexRequest createRequest = new IndexRequest(index).id(id).source(source, mediaType).create(true);
docWriteRequest = createRequest;
} else if (opType == DocWriteRequest.OpType.UPDATE) {
- final UpdateRequest updateRequest = new UpdateRequest(index, id).doc(new IndexRequest().source(source, xContentType));
+ final UpdateRequest updateRequest = new UpdateRequest(index, id).doc(new IndexRequest().source(source, mediaType));
docWriteRequest = updateRequest;
if (randomBoolean()) {
updateRequest.retryOnConflict(randomIntBetween(1, 5));
@@ -927,14 +927,14 @@ public void testBulk() throws IOException {
assertEquals("/_bulk", request.getEndpoint());
assertEquals(expectedParams, request.getParameters());
assertEquals(HttpPost.METHOD_NAME, request.getMethod());
- assertEquals(xContentType.mediaTypeWithoutParameters(), request.getEntity().getContentType());
+ assertEquals(mediaType.mediaTypeWithoutParameters(), request.getEntity().getContentType());
byte[] content = new byte[(int) request.getEntity().getContentLength()];
try (InputStream inputStream = request.getEntity().getContent()) {
Streams.readFully(inputStream, content);
}
BulkRequest parsedBulkRequest = new BulkRequest();
- parsedBulkRequest.add(content, 0, content.length, xContentType);
+ parsedBulkRequest.add(content, 0, content.length, mediaType);
assertEquals(bulkRequest.numberOfActions(), parsedBulkRequest.numberOfActions());
for (int i = 0; i < bulkRequest.numberOfActions(); i++) {
@@ -956,7 +956,7 @@ public void testBulk() throws IOException {
IndexRequest parsedIndexRequest = (IndexRequest) parsedRequest;
assertEquals(indexRequest.getPipeline(), parsedIndexRequest.getPipeline());
- assertToXContentEquivalent(indexRequest.source(), parsedIndexRequest.source(), xContentType);
+ assertToXContentEquivalent(indexRequest.source(), parsedIndexRequest.source(), mediaType);
} else if (opType == DocWriteRequest.OpType.UPDATE) {
UpdateRequest updateRequest = (UpdateRequest) originalRequest;
UpdateRequest parsedUpdateRequest = (UpdateRequest) parsedRequest;
@@ -964,7 +964,7 @@ public void testBulk() throws IOException {
assertEquals(updateRequest.retryOnConflict(), parsedUpdateRequest.retryOnConflict());
assertEquals(updateRequest.fetchSource(), parsedUpdateRequest.fetchSource());
if (updateRequest.doc() != null) {
- assertToXContentEquivalent(updateRequest.doc().source(), parsedUpdateRequest.doc().source(), xContentType);
+ assertToXContentEquivalent(updateRequest.doc().source(), parsedUpdateRequest.doc().source(), mediaType);
} else {
assertNull(parsedUpdateRequest.doc());
}
@@ -980,34 +980,34 @@ public void testBulkWithDifferentContentTypes() throws IOException {
bulkRequest.add(new DeleteRequest("index", "2"));
Request request = RequestConverters.bulk(bulkRequest);
- assertEquals(XContentType.JSON.mediaTypeWithoutParameters(), request.getEntity().getContentType());
+ assertEquals(MediaTypeRegistry.JSON.mediaTypeWithoutParameters(), request.getEntity().getContentType());
}
{
- XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);
+ MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE);
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new DeleteRequest("index", "0"));
- bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), xContentType));
+ bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), mediaType));
bulkRequest.add(new DeleteRequest("index", "2"));
Request request = RequestConverters.bulk(bulkRequest);
- assertEquals(xContentType.mediaTypeWithoutParameters(), request.getEntity().getContentType());
+ assertEquals(mediaType.mediaTypeWithoutParameters(), request.getEntity().getContentType());
}
{
- XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);
+ MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE);
UpdateRequest updateRequest = new UpdateRequest("index", "0");
if (randomBoolean()) {
- updateRequest.doc(new IndexRequest().source(singletonMap("field", "value"), xContentType));
+ updateRequest.doc(new IndexRequest().source(singletonMap("field", "value"), mediaType));
} else {
- updateRequest.upsert(new IndexRequest().source(singletonMap("field", "value"), xContentType));
+ updateRequest.upsert(new IndexRequest().source(singletonMap("field", "value"), mediaType));
}
Request request = RequestConverters.bulk(new BulkRequest().add(updateRequest));
- assertEquals(xContentType.mediaTypeWithoutParameters(), request.getEntity().getContentType());
+ assertEquals(mediaType.mediaTypeWithoutParameters(), request.getEntity().getContentType());
}
{
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), XContentType.SMILE));
- bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), XContentType.JSON));
+ bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), MediaTypeRegistry.JSON));
IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> RequestConverters.bulk(bulkRequest));
assertEquals(
"Mismatching content-type found for request with content-type [JSON], " + "previous requests have content-type [SMILE]",
@@ -1016,10 +1016,10 @@ public void testBulkWithDifferentContentTypes() throws IOException {
}
{
BulkRequest bulkRequest = new BulkRequest();
- bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), XContentType.JSON));
- bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), XContentType.JSON));
+ bulkRequest.add(new IndexRequest("index").id("0").source(singletonMap("field", "value"), MediaTypeRegistry.JSON));
+ bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), MediaTypeRegistry.JSON));
bulkRequest.add(
- new UpdateRequest("index", "2").doc(new IndexRequest().source(singletonMap("field", "value"), XContentType.JSON))
+ new UpdateRequest("index", "2").doc(new IndexRequest().source(singletonMap("field", "value"), MediaTypeRegistry.JSON))
.upsert(new IndexRequest().source(singletonMap("field", "value"), XContentType.SMILE))
);
IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> RequestConverters.bulk(bulkRequest));
@@ -1032,10 +1032,10 @@ public void testBulkWithDifferentContentTypes() throws IOException {
XContentType xContentType = randomFrom(XContentType.CBOR, XContentType.YAML);
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(new DeleteRequest("index", "0"));
- bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), XContentType.JSON));
+ bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), MediaTypeRegistry.JSON));
bulkRequest.add(new DeleteRequest("index", "2"));
bulkRequest.add(new DeleteRequest("index", "3"));
- bulkRequest.add(new IndexRequest("index").id("4").source(singletonMap("field", "value"), XContentType.JSON));
+ bulkRequest.add(new IndexRequest("index").id("4").source(singletonMap("field", "value"), MediaTypeRegistry.JSON));
bulkRequest.add(new IndexRequest("index").id("1").source(singletonMap("field", "value"), xContentType));
IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> RequestConverters.bulk(bulkRequest));
assertEquals(
@@ -1048,9 +1048,9 @@ public void testBulkWithDifferentContentTypes() throws IOException {
public void testGlobalPipelineOnBulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.pipeline("xyz");
- bulkRequest.add(new IndexRequest("test").id("11").source(XContentType.JSON, "field", "bulk1"));
- bulkRequest.add(new IndexRequest("test").id("12").source(XContentType.JSON, "field", "bulk2"));
- bulkRequest.add(new IndexRequest("test").id("13").source(XContentType.JSON, "field", "bulk3"));
+ bulkRequest.add(new IndexRequest("test").id("11").source(MediaTypeRegistry.JSON, "field", "bulk1"));
+ bulkRequest.add(new IndexRequest("test").id("12").source(MediaTypeRegistry.JSON, "field", "bulk2"));
+ bulkRequest.add(new IndexRequest("test").id("13").source(MediaTypeRegistry.JSON, "field", "bulk3"));
Request request = RequestConverters.bulk(bulkRequest);
@@ -1456,8 +1456,11 @@ public void testMultiSearchTemplate() throws Exception {
assertEquals(expectedParams, multiRequest.getParameters());
HttpEntity actualEntity = multiRequest.getEntity();
- byte[] expectedBytes = MultiSearchTemplateRequest.writeMultiLineFormat(multiSearchTemplateRequest, XContentType.JSON.xContent());
- assertEquals(XContentType.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType());
+ byte[] expectedBytes = MultiSearchTemplateRequest.writeMultiLineFormat(
+ multiSearchTemplateRequest,
+ MediaTypeRegistry.JSON.xContent()
+ );
+ assertEquals(MediaTypeRegistry.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType());
assertEquals(new BytesArray(expectedBytes), new BytesArray(EntityUtils.toByteArray(actualEntity)));
}
@@ -1763,8 +1766,12 @@ public void testDeleteScriptRequest() {
}
static void assertToXContentBody(ToXContent expectedBody, HttpEntity actualEntity) throws IOException {
- BytesReference expectedBytes = XContentHelper.toXContent(expectedBody, REQUEST_BODY_CONTENT_TYPE, false);
- assertEquals(XContentType.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType());
+ BytesReference expectedBytes = org.opensearch.core.xcontent.XContentHelper.toXContent(
+ expectedBody,
+ REQUEST_BODY_CONTENT_TYPE,
+ false
+ );
+ assertEquals(MediaTypeRegistry.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType());
assertEquals(expectedBytes, new BytesArray(EntityUtils.toByteArray(actualEntity)));
}
@@ -1913,12 +1920,12 @@ public void testCreateContentType() {
}
public void testEnforceSameContentType() {
- XContentType xContentType = randomFrom(XContentType.JSON, XContentType.SMILE);
- IndexRequest indexRequest = new IndexRequest().source(singletonMap("field", "value"), xContentType);
- assertEquals(xContentType, enforceSameContentType(indexRequest, null));
- assertEquals(xContentType, enforceSameContentType(indexRequest, xContentType));
+ MediaType mediaType = randomFrom(MediaTypeRegistry.JSON, XContentType.SMILE);
+ IndexRequest indexRequest = new IndexRequest().source(singletonMap("field", "value"), mediaType);
+ assertEquals(mediaType, enforceSameContentType(indexRequest, null));
+ assertEquals(mediaType, enforceSameContentType(indexRequest, mediaType));
- XContentType bulkContentType = randomBoolean() ? xContentType : null;
+ MediaType bulkContentType = randomBoolean() ? mediaType : null;
IllegalArgumentException exception = expectThrows(
IllegalArgumentException.class,
@@ -1938,18 +1945,18 @@ public void testEnforceSameContentType() {
exception.getMessage()
);
- XContentType requestContentType = xContentType == XContentType.JSON ? XContentType.SMILE : XContentType.JSON;
+ MediaType requestContentType = mediaType == MediaTypeRegistry.JSON ? XContentType.SMILE : MediaTypeRegistry.JSON;
exception = expectThrows(
IllegalArgumentException.class,
- () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), requestContentType), xContentType)
+ () -> enforceSameContentType(new IndexRequest().source(singletonMap("field", "value"), requestContentType), mediaType)
);
assertEquals(
"Mismatching content-type found for request with content-type ["
+ requestContentType
+ "], "
+ "previous requests have content-type ["
- + xContentType
+ + mediaType
+ "]",
exception.getMessage()
);
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientExtTests.java
index ad6667b0c3d50..b6289c790b511 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
@@ -35,11 +35,11 @@
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.io.entity.StringEntity;
-import org.junit.Before;
import org.opensearch.core.ParseField;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.test.OpenSearchTestCase;
+import org.junit.Before;
import java.io.IOException;
import java.util.ArrayList;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java
index 24b0fda6c18d5..b0964a22786f0 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/RestHighLevelClientTests.java
@@ -33,8 +33,19 @@
package org.opensearch.client;
import com.fasterxml.jackson.core.JsonParseException;
+
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.ContentType;
+import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.ProtocolVersion;
+import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
+import org.apache.hc.core5.http.io.entity.StringEntity;
+import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
+import org.apache.hc.core5.http.message.RequestLine;
+import org.apache.hc.core5.http.message.StatusLine;
import org.opensearch.OpenSearchException;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.ActionRequest;
import org.opensearch.action.ActionRequestValidationException;
import org.opensearch.action.search.ClearScrollRequest;
@@ -46,16 +57,18 @@
import org.opensearch.client.core.MainRequest;
import org.opensearch.client.core.MainResponse;
import org.opensearch.common.CheckedFunction;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.collect.Tuple;
import org.opensearch.common.util.set.Sets;
+import org.opensearch.common.xcontent.cbor.CborXContent;
+import org.opensearch.common.xcontent.smile.SmileXContent;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.common.xcontent.cbor.CborXContent;
-import org.opensearch.common.xcontent.smile.SmileXContent;
import org.opensearch.index.rankeval.DiscountedCumulativeGain;
import org.opensearch.index.rankeval.EvaluationMetric;
import org.opensearch.index.rankeval.ExpectedReciprocalRank;
@@ -64,27 +77,15 @@
import org.opensearch.index.rankeval.PrecisionAtK;
import org.opensearch.index.rankeval.RecallAtK;
import org.opensearch.join.aggregations.ChildrenAggregationBuilder;
-import org.opensearch.core.rest.RestStatus;
import org.opensearch.search.SearchHits;
import org.opensearch.search.aggregations.Aggregation;
import org.opensearch.search.aggregations.InternalAggregations;
import org.opensearch.search.aggregations.matrix.stats.MatrixStatsAggregationBuilder;
import org.opensearch.search.suggest.Suggest;
-import org.opensearch.test.OpenSearchTestCase;
import org.opensearch.test.InternalAggregationTestCase;
+import org.opensearch.test.OpenSearchTestCase;
import org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestApi;
import org.opensearch.test.rest.yaml.restspec.ClientYamlSuiteRestSpec;
-import org.apache.hc.client5.http.classic.methods.HttpGet;
-import org.apache.hc.core5.http.ClassicHttpResponse;
-import org.apache.hc.core5.http.ContentType;
-import org.apache.hc.core5.http.HttpEntity;
-import org.apache.hc.core5.http.HttpHost;
-import org.apache.hc.core5.http.ProtocolVersion;
-import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
-import org.apache.hc.core5.http.io.entity.StringEntity;
-import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
-import org.apache.hc.core5.http.message.RequestLine;
-import org.apache.hc.core5.http.message.StatusLine;
import org.hamcrest.Matchers;
import org.junit.Before;
@@ -106,7 +107,7 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.opensearch.common.xcontent.XContentHelper.toXContent;
+import static org.opensearch.core.xcontent.XContentHelper.toXContent;
import static org.hamcrest.CoreMatchers.endsWith;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java
index fbfab016b1ead..f2778a97c0c1a 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/SearchIT.java
@@ -32,6 +32,8 @@
package org.opensearch.client;
+import org.apache.hc.client5.http.classic.methods.HttpPost;
+import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.opensearch.OpenSearchException;
import org.opensearch.OpenSearchStatusException;
import org.opensearch.action.explain.ExplainRequest;
@@ -52,12 +54,12 @@
import org.opensearch.action.search.SearchScrollRequest;
import org.opensearch.client.core.CountRequest;
import org.opensearch.client.core.CountResponse;
-import org.opensearch.common.Strings;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentFactory;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.index.query.MatchQueryBuilder;
import org.opensearch.index.query.QueryBuilder;
import org.opensearch.index.query.QueryBuilders;
@@ -65,7 +67,6 @@
import org.opensearch.index.query.TermsQueryBuilder;
import org.opensearch.join.aggregations.Children;
import org.opensearch.join.aggregations.ChildrenAggregationBuilder;
-import org.opensearch.core.rest.RestStatus;
import org.opensearch.script.Script;
import org.opensearch.script.ScriptType;
import org.opensearch.script.mustache.MultiSearchTemplateRequest;
@@ -101,8 +102,6 @@
import org.opensearch.search.suggest.Suggest;
import org.opensearch.search.suggest.SuggestBuilder;
import org.opensearch.search.suggest.phrase.PhraseSuggestionBuilder;
-import org.apache.hc.client5.http.classic.methods.HttpPost;
-import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.hamcrest.Matchers;
import org.junit.Before;
@@ -769,7 +768,7 @@ public void testSearchScroll() throws Exception {
for (int i = 0; i < 100; i++) {
XContentBuilder builder = jsonBuilder().startObject().field("field", i).endObject();
Request doc = new Request(HttpPut.METHOD_NAME, "/test/_doc/" + Integer.toString(i));
- doc.setJsonEntity(Strings.toString(builder));
+ doc.setJsonEntity(builder.toString());
client().performRequest(doc);
}
client().performRequest(new Request(HttpPost.METHOD_NAME, "/test/_refresh"));
@@ -837,7 +836,7 @@ public void testSearchWithPit() throws Exception {
for (int i = 0; i < 100; i++) {
XContentBuilder builder = jsonBuilder().startObject().field("field", i).endObject();
Request doc = new Request(HttpPut.METHOD_NAME, "/test/_doc/" + Integer.toString(i));
- doc.setJsonEntity(Strings.toString(builder));
+ doc.setJsonEntity(builder.toString());
client().performRequest(doc);
}
client().performRequest(new Request(HttpPost.METHOD_NAME, "/test/_refresh"));
@@ -1201,7 +1200,7 @@ public void testRenderSearchTemplate() throws IOException {
BytesReference actualSource = searchTemplateResponse.getSource();
assertNotNull(actualSource);
- assertToXContentEquivalent(expectedSource, actualSource, XContentType.JSON);
+ assertToXContentEquivalent(expectedSource, actualSource, MediaTypeRegistry.JSON);
}
public void testMultiSearchTemplate() throws Exception {
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SearchPipelineClientIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/SearchPipelineClientIT.java
index 70ba39a04e8db..9304be7f21899 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/SearchPipelineClientIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/SearchPipelineClientIT.java
@@ -13,8 +13,8 @@
import org.opensearch.action.search.GetSearchPipelineResponse;
import org.opensearch.action.search.PutSearchPipelineRequest;
import org.opensearch.action.support.master.AcknowledgedResponse;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.XContentBuilder;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java
index df99d26a0a530..362a8f10d6a77 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotIT.java
@@ -54,9 +54,9 @@
import org.opensearch.action.support.master.AcknowledgedResponse;
import org.opensearch.cluster.metadata.IndexMetadata;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.xcontent.XContentType;
-import org.opensearch.repositories.fs.FsRepository;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.repositories.fs.FsRepository;
import org.opensearch.snapshots.RestoreInfo;
import org.opensearch.snapshots.SnapshotInfo;
@@ -76,7 +76,7 @@ public class SnapshotIT extends OpenSearchRestHighLevelClientTestCase {
private AcknowledgedResponse createTestRepository(String repository, String type, String settings) throws IOException {
PutRepositoryRequest request = new PutRepositoryRequest(repository);
- request.settings(settings, XContentType.JSON);
+ request.settings(settings, MediaTypeRegistry.JSON);
request.type(type);
return execute(request, highLevelClient().snapshot()::createRepository, highLevelClient().snapshot()::createRepositoryAsync);
}
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotRequestConvertersTests.java
index e86de6ba718f9..af178ad2a5d47 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotRequestConvertersTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/SnapshotRequestConvertersTests.java
@@ -48,7 +48,7 @@
import org.opensearch.action.support.master.AcknowledgedRequest;
import org.opensearch.common.io.PathUtils;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.unit.ByteSizeUnit;
+import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.repositories.fs.FsRepository;
import org.opensearch.test.OpenSearchTestCase;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java
index c86de6ae645c1..4d792e53c6064 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/StoredScriptsIT.java
@@ -38,8 +38,8 @@
import org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptResponse;
import org.opensearch.action.admin.cluster.storedscripts.PutStoredScriptRequest;
import org.opensearch.core.common.bytes.BytesArray;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.script.Script;
import org.opensearch.script.StoredScriptSource;
@@ -58,10 +58,16 @@ public void testGetStoredScript() throws Exception {
final StoredScriptSource scriptSource = new StoredScriptSource(
"painless",
"Math.log(_score * 2) + params.my_modifier",
- Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())
+ Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType())
);
- PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource);
+ PutStoredScriptRequest request = new PutStoredScriptRequest(
+ id,
+ "score",
+ new BytesArray("{}"),
+ MediaTypeRegistry.JSON,
+ scriptSource
+ );
assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync));
GetStoredScriptRequest getRequest = new GetStoredScriptRequest("calculate-score");
@@ -76,10 +82,16 @@ public void testDeleteStoredScript() throws Exception {
final StoredScriptSource scriptSource = new StoredScriptSource(
"painless",
"Math.log(_score * 2) + params.my_modifier",
- Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())
+ Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType())
);
- PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource);
+ PutStoredScriptRequest request = new PutStoredScriptRequest(
+ id,
+ "score",
+ new BytesArray("{}"),
+ MediaTypeRegistry.JSON,
+ scriptSource
+ );
assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync));
DeleteStoredScriptRequest deleteRequest = new DeleteStoredScriptRequest(id);
@@ -100,10 +112,16 @@ public void testPutScript() throws Exception {
final StoredScriptSource scriptSource = new StoredScriptSource(
"painless",
"Math.log(_score * 2) + params.my_modifier",
- Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())
+ Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType())
);
- PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource);
+ PutStoredScriptRequest request = new PutStoredScriptRequest(
+ id,
+ "score",
+ new BytesArray("{}"),
+ MediaTypeRegistry.JSON,
+ scriptSource
+ );
assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync));
Map script = getAsMap("/_scripts/" + id);
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java
index 24edd5f93bdba..c5a16ec32e686 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/TasksIT.java
@@ -32,7 +32,6 @@
package org.opensearch.client;
-import org.opensearch.index.reindex.ReindexRequest;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse;
import org.opensearch.action.admin.cluster.node.tasks.list.TaskGroup;
@@ -46,8 +45,9 @@
import org.opensearch.client.tasks.TaskId;
import org.opensearch.client.tasks.TaskSubmissionResponse;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.index.reindex.ReindexRequest;
import java.io.IOException;
import java.util.Collections;
@@ -94,9 +94,9 @@ public void testGetValidTask() throws Exception {
createIndex(sourceIndex, settings);
createIndex(destinationIndex, settings);
BulkRequest bulkRequest = new BulkRequest().add(
- new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)
+ new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), XContentType.JSON))
+ .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo2", "bar2"), MediaTypeRegistry.JSON))
.setRefreshPolicy(RefreshPolicy.IMMEDIATE);
assertEquals(RestStatus.OK, highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status());
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/TasksRequestConvertersTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/TasksRequestConvertersTests.java
index a777bbc5d1868..e4c6feb1f6bb1 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/TasksRequestConvertersTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/TasksRequestConvertersTests.java
@@ -36,7 +36,7 @@
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest;
import org.opensearch.client.tasks.CancelTasksRequest;
-import org.opensearch.tasks.TaskId;
+import org.opensearch.core.tasks.TaskId;
import org.opensearch.test.OpenSearchTestCase;
import java.util.HashMap;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java
index e5fbb30d29292..ef7b7d5a39b6f 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/UpdateByQueryIT.java
@@ -32,7 +32,6 @@
package org.opensearch.client;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksResponse;
import org.opensearch.action.bulk.BulkItemResponse;
import org.opensearch.action.bulk.BulkRequest;
@@ -41,15 +40,16 @@
import org.opensearch.action.support.WriteRequest;
import org.opensearch.client.tasks.TaskSubmissionResponse;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.tasks.TaskId;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.index.query.IdsQueryBuilder;
import org.opensearch.index.reindex.BulkByScrollResponse;
import org.opensearch.index.reindex.UpdateByQueryAction;
import org.opensearch.index.reindex.UpdateByQueryRequest;
-import org.opensearch.core.rest.RestStatus;
import org.opensearch.script.Script;
import org.opensearch.tasks.RawTaskStatus;
-import org.opensearch.tasks.TaskId;
import java.io.IOException;
import java.util.Collections;
@@ -76,9 +76,9 @@ public void testUpdateByQuery() throws Exception {
RestStatus.OK,
highLevelClient().bulk(
new BulkRequest().add(
- new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON)
+ new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON))
+ .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON))
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE),
RequestOptions.DEFAULT
).status()
@@ -197,10 +197,10 @@ public void testUpdateByQueryTask() throws Exception {
RestStatus.OK,
highLevelClient().bulk(
new BulkRequest().add(
- new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), XContentType.JSON)
+ new IndexRequest(sourceIndex).id("1").source(Collections.singletonMap("foo", 1), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), XContentType.JSON))
- .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), XContentType.JSON))
+ .add(new IndexRequest(sourceIndex).id("2").source(Collections.singletonMap("foo", 2), MediaTypeRegistry.JSON))
+ .add(new IndexRequest(sourceIndex).id("3").source(Collections.singletonMap("foo", 3), MediaTypeRegistry.JSON))
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE),
RequestOptions.DEFAULT
).status()
@@ -230,9 +230,9 @@ public void testUpdateByQueryConflict() throws IOException {
final Settings settings = Settings.builder().put("number_of_shards", 1).put("number_of_replicas", 0).build();
createIndex(index, settings);
final BulkRequest bulkRequest = new BulkRequest().add(
- new IndexRequest(index).id("1").source(Collections.singletonMap("foo", "bar"), XContentType.JSON)
+ new IndexRequest(index).id("1").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON)
)
- .add(new IndexRequest(index).id("2").source(Collections.singletonMap("foo", "bar"), XContentType.JSON))
+ .add(new IndexRequest(index).id("2").source(Collections.singletonMap("foo", "bar"), MediaTypeRegistry.JSON))
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
assertThat(highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT).status(), equalTo(RestStatus.OK));
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/cluster/RemoteInfoResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/cluster/RemoteInfoResponseTests.java
index ed60dfa36a237..201a8ee1e60ac 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/cluster/RemoteInfoResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/cluster/RemoteInfoResponseTests.java
@@ -34,8 +34,8 @@
import org.opensearch.client.AbstractResponseTestCase;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.transport.ProxyConnectionStrategy;
import org.opensearch.transport.RemoteConnectionInfo;
import org.opensearch.transport.SniffConnectionStrategy;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/AcknowledgedResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/AcknowledgedResponseTests.java
index 9c4004945b6bf..e184df7ad013c 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/core/AcknowledgedResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/AcknowledgedResponseTests.java
@@ -32,8 +32,8 @@
package org.opensearch.client.core;
import org.opensearch.client.AbstractResponseTestCase;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.XContentParser;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/BroadcastResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/BroadcastResponseTests.java
index 101f00ad25eb8..de2af42cb900f 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/core/BroadcastResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/BroadcastResponseTests.java
@@ -32,10 +32,10 @@
package org.opensearch.client.core;
-import org.opensearch.core.action.support.DefaultShardOperationFailedException;
import org.opensearch.client.AbstractResponseTestCase;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.action.support.DefaultShardOperationFailedException;
+import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.index.seqno.RetentionLeaseNotFoundException;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/CountResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/CountResponseTests.java
index 06912e0c6bb1f..946ebc1089580 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/core/CountResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/CountResponseTests.java
@@ -35,10 +35,10 @@
import org.opensearch.action.search.ShardSearchFailure;
import org.opensearch.cluster.metadata.IndexMetadata;
import org.opensearch.core.common.ParsingException;
-import org.opensearch.core.xcontent.ToXContent;
-import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.index.Index;
import org.opensearch.core.index.shard.ShardId;
+import org.opensearch.core.xcontent.ToXContent;
+import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.rest.action.RestActions;
import org.opensearch.search.SearchShardTarget;
import org.opensearch.test.OpenSearchTestCase;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/GetSourceResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/GetSourceResponseTests.java
index 03d6e6720ffed..0c2b269c7e78d 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/core/GetSourceResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/GetSourceResponseTests.java
@@ -33,13 +33,13 @@
package org.opensearch.client.core;
import org.opensearch.client.AbstractResponseTestCase;
+import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.common.xcontent.XContentType;
import java.io.IOException;
import java.io.InputStream;
@@ -61,7 +61,7 @@ static class SourceOnlyResponse implements ToXContentObject {
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
// this implementation copied from RestGetSourceAction.RestGetSourceResponseListener::buildResponse
try (InputStream stream = source.streamInput()) {
- builder.rawValue(stream, XContentHelper.xContentType(source));
+ builder.rawValue(stream, MediaTypeRegistry.xContentType(source));
}
return builder;
}
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/MainResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/MainResponseTests.java
index 3951e2b6e33fd..15546e5b4ecbe 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/core/MainResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/MainResponseTests.java
@@ -36,8 +36,8 @@
import org.opensearch.Version;
import org.opensearch.client.AbstractResponseTestCase;
import org.opensearch.cluster.ClusterName;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.test.VersionUtils;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/TermVectorsResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/TermVectorsResponseTests.java
index 10bb274b1216c..5b6b96fd9144f 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/core/TermVectorsResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/TermVectorsResponseTests.java
@@ -35,11 +35,11 @@
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.test.OpenSearchTestCase;
-import java.util.ArrayList;
-import java.util.List;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
+import java.util.List;
import static org.opensearch.test.AbstractXContentTestCase.xContentTester;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/core/tasks/GetTaskResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/core/tasks/GetTaskResponseTests.java
index 63e016fea1da7..060caeddd9826 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/core/tasks/GetTaskResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/core/tasks/GetTaskResponseTests.java
@@ -35,15 +35,15 @@
import org.opensearch.client.Requests;
import org.opensearch.client.tasks.GetTaskResponse;
import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.tasks.TaskId;
+import org.opensearch.core.tasks.resourcetracker.TaskResourceStats;
+import org.opensearch.core.tasks.resourcetracker.TaskResourceUsage;
+import org.opensearch.core.tasks.resourcetracker.TaskThreadUsage;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.tasks.RawTaskStatus;
-import org.opensearch.tasks.TaskResourceStats;
-import org.opensearch.tasks.TaskResourceUsage;
import org.opensearch.tasks.Task;
-import org.opensearch.tasks.TaskId;
import org.opensearch.tasks.TaskInfo;
-import org.opensearch.tasks.TaskThreadUsage;
import org.opensearch.test.OpenSearchTestCase;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java
index a973753aa2032..123a51a54788e 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/CRUDDocumentationIT.java
@@ -34,7 +34,6 @@
import org.apache.hc.core5.http.HttpHost;
import org.opensearch.OpenSearchException;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.DocWriteRequest;
import org.opensearch.action.DocWriteResponse;
import org.opensearch.action.LatchedActionListener;
@@ -74,16 +73,19 @@
import org.opensearch.client.core.TermVectorsResponse;
import org.opensearch.client.indices.CreateIndexRequest;
import org.opensearch.client.indices.CreateIndexResponse;
-import org.opensearch.common.Strings;
-import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.unit.ByteSizeUnit;
-import org.opensearch.common.unit.ByteSizeValue;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentFactory;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.common.xcontent.json.JsonXContent;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.common.Strings;
+import org.opensearch.core.common.bytes.BytesArray;
+import org.opensearch.core.common.unit.ByteSizeUnit;
+import org.opensearch.core.common.unit.ByteSizeValue;
+import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.tasks.TaskId;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.index.VersionType;
import org.opensearch.index.get.GetResult;
import org.opensearch.index.query.MatchAllQueryBuilder;
@@ -94,11 +96,9 @@
import org.opensearch.index.reindex.RemoteInfo;
import org.opensearch.index.reindex.ScrollableHitSource;
import org.opensearch.index.reindex.UpdateByQueryRequest;
-import org.opensearch.core.rest.RestStatus;
import org.opensearch.script.Script;
import org.opensearch.script.ScriptType;
import org.opensearch.search.fetch.subphase.FetchSourceContext;
-import org.opensearch.tasks.TaskId;
import java.util.Collections;
import java.util.Date;
@@ -173,7 +173,7 @@ public void testIndex() throws Exception {
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out OpenSearch\"" +
"}";
- request.source(jsonString, XContentType.JSON); // <3>
+ request.source(jsonString, MediaTypeRegistry.JSON); // <3>
//end::index-request-string
// tag::index-execute
@@ -298,15 +298,14 @@ public void testUpdate() throws Exception {
Request request = new Request("POST", "/_scripts/increment-field");
request.setJsonEntity(
- Strings.toString(
- JsonXContent.contentBuilder()
- .startObject()
- .startObject("script")
- .field("lang", "painless")
- .field("source", "ctx._source.field += params.count")
- .endObject()
- .endObject()
- )
+ JsonXContent.contentBuilder()
+ .startObject()
+ .startObject("script")
+ .field("lang", "painless")
+ .field("source", "ctx._source.field += params.count")
+ .endObject()
+ .endObject()
+ .toString()
);
Response response = client().performRequest(request);
assertEquals(RestStatus.OK.getStatus(), response.getStatusLine().getStatusCode());
@@ -381,7 +380,7 @@ public void testUpdate() throws Exception {
"\"updated\":\"2017-01-01\"," +
"\"reason\":\"daily update\"" +
"}";
- request.doc(jsonString, XContentType.JSON); // <1>
+ request.doc(jsonString, MediaTypeRegistry.JSON); // <1>
//end::update-request-with-doc-as-string
request.fetchSource(true);
// tag::update-execute
@@ -525,7 +524,7 @@ public void testUpdate() throws Exception {
// end::update-request-detect-noop
// tag::update-request-upsert
String jsonString = "{\"created\":\"2017-01-01\"}";
- request.upsert(jsonString, XContentType.JSON); // <1>
+ request.upsert(jsonString, MediaTypeRegistry.JSON); // <1>
// end::update-request-upsert
// tag::update-request-scripted-upsert
request.scriptedUpsert(true); // <1>
@@ -699,11 +698,11 @@ public void testBulk() throws Exception {
// tag::bulk-request
BulkRequest request = new BulkRequest(); // <1>
request.add(new IndexRequest("posts").id("1") // <2>
- .source(XContentType.JSON,"field", "foo"));
+ .source(MediaTypeRegistry.JSON,"field", "foo"));
request.add(new IndexRequest("posts").id("2") // <3>
- .source(XContentType.JSON,"field", "bar"));
+ .source(MediaTypeRegistry.JSON,"field", "bar"));
request.add(new IndexRequest("posts").id("3") // <4>
- .source(XContentType.JSON,"field", "baz"));
+ .source(MediaTypeRegistry.JSON,"field", "baz"));
// end::bulk-request
// tag::bulk-execute
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
@@ -716,9 +715,9 @@ public void testBulk() throws Exception {
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest("posts", "3")); // <1>
request.add(new UpdateRequest("posts", "2") // <2>
- .doc(XContentType.JSON,"other", "test"));
+ .doc(MediaTypeRegistry.JSON,"other", "test"));
request.add(new IndexRequest("posts").id("4") // <3>
- .source(XContentType.JSON,"field", "baz"));
+ .source(MediaTypeRegistry.JSON,"field", "baz"));
// end::bulk-request-with-mixed-operations
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
assertSame(RestStatus.OK, bulkResponse.status());
@@ -1581,13 +1580,13 @@ public void afterBulk(long executionId, BulkRequest request,
// tag::bulk-processor-add
IndexRequest one = new IndexRequest("posts").id("1")
- .source(XContentType.JSON, "title",
+ .source(MediaTypeRegistry.JSON, "title",
"In which order are my OpenSearch queries executed?");
IndexRequest two = new IndexRequest("posts").id("2")
- .source(XContentType.JSON, "title",
+ .source(MediaTypeRegistry.JSON, "title",
"Current status and upcoming changes in OpenSearch");
IndexRequest three = new IndexRequest("posts").id("3")
- .source(XContentType.JSON, "title",
+ .source(MediaTypeRegistry.JSON, "title",
"The Future of Federated Search in OpenSearch");
bulkProcessor.add(one);
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java
index f85fcae7af365..17ea5b273d2a2 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/ClusterClientDocumentationIT.java
@@ -32,7 +32,6 @@
package org.opensearch.client.documentation;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.LatchedActionListener;
import org.opensearch.action.admin.cluster.health.ClusterHealthRequest;
import org.opensearch.action.admin.cluster.health.ClusterHealthResponse;
@@ -63,11 +62,12 @@
import org.opensearch.common.Priority;
import org.opensearch.common.compress.CompressedXContent;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.unit.ByteSizeUnit;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.xcontent.XContentType;
-import org.opensearch.indices.recovery.RecoverySettings;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.common.unit.ByteSizeUnit;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.indices.recovery.RecoverySettings;
import java.io.IOException;
import java.util.HashMap;
@@ -138,7 +138,7 @@ public void testClusterPutSettings() throws IOException {
// tag::put-settings-settings-source
request.transientSettings(
"{\"indices.recovery.max_bytes_per_sec\": \"10b\"}"
- , XContentType.JSON); // <1>
+ , MediaTypeRegistry.JSON); // <1>
// end::put-settings-settings-source
}
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java
index 73346bc57646e..ce080b45273b4 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IndicesClientDocumentationIT.java
@@ -33,7 +33,6 @@
package org.opensearch.client.documentation;
import org.opensearch.OpenSearchException;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.LatchedActionListener;
import org.opensearch.action.admin.indices.alias.Alias;
import org.opensearch.action.admin.indices.alias.IndicesAliasesRequest;
@@ -61,11 +60,10 @@
import org.opensearch.action.admin.indices.validate.query.ValidateQueryRequest;
import org.opensearch.action.admin.indices.validate.query.ValidateQueryResponse;
import org.opensearch.action.support.ActiveShardCount;
-import org.opensearch.core.action.support.DefaultShardOperationFailedException;
import org.opensearch.action.support.IndicesOptions;
import org.opensearch.action.support.master.AcknowledgedResponse;
-import org.opensearch.client.OpenSearchRestHighLevelClientTestCase;
import org.opensearch.client.GetAliasesResponse;
+import org.opensearch.client.OpenSearchRestHighLevelClientTestCase;
import org.opensearch.client.RequestOptions;
import org.opensearch.client.RestHighLevelClient;
import org.opensearch.client.indices.AnalyzeRequest;
@@ -77,21 +75,21 @@
import org.opensearch.client.indices.DeleteAliasRequest;
import org.opensearch.client.indices.DeleteComposableIndexTemplateRequest;
import org.opensearch.client.indices.DetailAnalyzeResponse;
+import org.opensearch.client.indices.GetComposableIndexTemplateRequest;
+import org.opensearch.client.indices.GetComposableIndexTemplatesResponse;
import org.opensearch.client.indices.GetFieldMappingsRequest;
import org.opensearch.client.indices.GetFieldMappingsResponse;
import org.opensearch.client.indices.GetIndexRequest;
import org.opensearch.client.indices.GetIndexResponse;
-import org.opensearch.client.indices.GetComposableIndexTemplateRequest;
import org.opensearch.client.indices.GetIndexTemplatesRequest;
import org.opensearch.client.indices.GetIndexTemplatesResponse;
-import org.opensearch.client.indices.GetComposableIndexTemplatesResponse;
import org.opensearch.client.indices.GetMappingsRequest;
import org.opensearch.client.indices.GetMappingsResponse;
import org.opensearch.client.indices.IndexTemplateMetadata;
import org.opensearch.client.indices.IndexTemplatesExistRequest;
import org.opensearch.client.indices.PutComponentTemplateRequest;
-import org.opensearch.client.indices.PutIndexTemplateRequest;
import org.opensearch.client.indices.PutComposableIndexTemplateRequest;
+import org.opensearch.client.indices.PutIndexTemplateRequest;
import org.opensearch.client.indices.PutMappingRequest;
import org.opensearch.client.indices.SimulateIndexTemplateRequest;
import org.opensearch.client.indices.SimulateIndexTemplateResponse;
@@ -104,16 +102,18 @@
import org.opensearch.cluster.metadata.Template;
import org.opensearch.common.compress.CompressedXContent;
import org.opensearch.common.settings.Settings;
-import org.opensearch.common.unit.ByteSizeUnit;
-import org.opensearch.common.unit.ByteSizeValue;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentFactory;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.action.support.DefaultShardOperationFailedException;
+import org.opensearch.core.common.unit.ByteSizeUnit;
+import org.opensearch.core.common.unit.ByteSizeValue;
+import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.index.IndexSettings;
import org.opensearch.index.query.QueryBuilder;
import org.opensearch.index.query.QueryBuilders;
-import org.opensearch.core.rest.RestStatus;
import java.io.IOException;
import java.util.Arrays;
@@ -137,15 +137,15 @@
* You need to wrap your code between two tags like:
* // tag::example
* // end::example
- *
+ *
* Where example is your tag name.
- *
+ *
* Then in the documentation, you can extract what is between tag and end tags with
* ["source","java",subs="attributes,callouts,macros"]
* --------------------------------------------------
* include-tagged::{doc-tests}/IndicesClientDocumentationIT.java[example]
* --------------------------------------------------
- *
+ *
* The column width of the code block is 84. If the code contains a line longer
* than 84, the line will be cut and a horizontal scroll bar will be displayed.
* (the code indentation of the tag is not included in the width)
@@ -329,7 +329,7 @@ public void testCreateIndex() throws IOException {
" }\n" +
" }\n" +
"}", // <2>
- XContentType.JSON);
+ MediaTypeRegistry.JSON);
// end::create-index-request-mappings
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
assertTrue(createIndexResponse.isAcknowledged());
@@ -407,7 +407,7 @@ public void testCreateIndex() throws IOException {
" \"aliases\" : {\n" +
" \"twitter_alias\" : {}\n" +
" }\n" +
- "}", XContentType.JSON); // <1>
+ "}", MediaTypeRegistry.JSON); // <1>
// end::create-index-whole-source
// tag::create-index-execute
@@ -480,7 +480,7 @@ public void testPutMapping() throws IOException {
" }\n" +
" }\n" +
"}", // <1>
- XContentType.JSON);
+ MediaTypeRegistry.JSON);
// end::put-mapping-request-source
AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
assertTrue(putMappingResponse.isAcknowledged());
@@ -585,7 +585,7 @@ public void testGetMapping() throws IOException {
CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT);
assertTrue(createIndexResponse.isAcknowledged());
PutMappingRequest request = new PutMappingRequest("twitter");
- request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", XContentType.JSON);
+ request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", MediaTypeRegistry.JSON);
AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
assertTrue(putMappingResponse.isAcknowledged());
}
@@ -631,7 +631,7 @@ public void testGetMappingAsync() throws Exception {
CreateIndexResponse createIndexResponse = client.indices().create(new CreateIndexRequest("twitter"), RequestOptions.DEFAULT);
assertTrue(createIndexResponse.isAcknowledged());
PutMappingRequest request = new PutMappingRequest("twitter");
- request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", XContentType.JSON);
+ request.source("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", MediaTypeRegistry.JSON);
AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
assertTrue(putMappingResponse.isAcknowledged());
}
@@ -703,7 +703,7 @@ public void testGetFieldMapping() throws IOException, InterruptedException {
+ " }\n"
+ " }\n"
+ "}", // <1>
- XContentType.JSON
+ MediaTypeRegistry.JSON
);
AcknowledgedResponse putMappingResponse = client.indices().putMapping(request, RequestOptions.DEFAULT);
assertTrue(putMappingResponse.isAcknowledged());
@@ -1127,7 +1127,8 @@ public void testGetIndex() throws Exception {
{
Settings settings = Settings.builder().put("number_of_shards", 3).build();
String mappings = "{\"properties\":{\"field-1\":{\"type\":\"integer\"}}}";
- CreateIndexRequest createIndexRequest = new CreateIndexRequest("index").settings(settings).mapping(mappings, XContentType.JSON);
+ CreateIndexRequest createIndexRequest = new CreateIndexRequest("index").settings(settings)
+ .mapping(mappings, MediaTypeRegistry.JSON);
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
assertTrue(createIndexResponse.isAcknowledged());
}
@@ -1830,7 +1831,7 @@ public void testRolloverIndex() throws Exception {
// end::rollover-index-request-settings
// tag::rollover-index-request-mapping
String mappings = "{\"properties\":{\"field-1\":{\"type\":\"keyword\"}}}";
- request.getCreateIndexRequest().mapping(mappings, XContentType.JSON); // <1>
+ request.getCreateIndexRequest().mapping(mappings, MediaTypeRegistry.JSON); // <1>
// end::rollover-index-request-mapping
// tag::rollover-index-request-alias
request.getCreateIndexRequest().alias(new Alias("another_alias")); // <1>
@@ -2009,7 +2010,7 @@ public void testIndexPutSettings() throws Exception {
// tag::indices-put-settings-settings-source
request.settings(
"{\"index.number_of_replicas\": \"2\"}"
- , XContentType.JSON); // <1>
+ , MediaTypeRegistry.JSON); // <1>
// end::indices-put-settings-settings-source
}
@@ -2090,7 +2091,7 @@ public void testPutTemplate() throws Exception {
" }\n" +
" }\n" +
"}",
- XContentType.JSON);
+ MediaTypeRegistry.JSON);
// end::put-template-request-mappings-json
assertTrue(client.indices().putTemplate(request, RequestOptions.DEFAULT).isAcknowledged());
}
@@ -2165,7 +2166,7 @@ public void testPutTemplate() throws Exception {
" \"alias-1\": {},\n" +
" \"{index}-alias\": {}\n" +
" }\n" +
- "}", XContentType.JSON); // <1>
+ "}", MediaTypeRegistry.JSON); // <1>
// end::put-template-whole-source
// tag::put-template-request-create
@@ -2220,7 +2221,7 @@ public void testGetTemplates() throws Exception {
PutIndexTemplateRequest putRequest = new PutIndexTemplateRequest("my-template");
putRequest.patterns(Arrays.asList("pattern-1", "log-*"));
putRequest.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 1));
- putRequest.mapping("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", XContentType.JSON);
+ putRequest.mapping("{ \"properties\": { \"message\": { \"type\": \"text\" } } }", MediaTypeRegistry.JSON);
assertTrue(client.indices().putTemplate(putRequest, RequestOptions.DEFAULT).isAcknowledged());
}
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java
index 6c11aff3d292e..28909cf58541a 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/IngestClientDocumentationIT.java
@@ -32,7 +32,6 @@
package org.opensearch.client.documentation;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.LatchedActionListener;
import org.opensearch.action.ingest.DeletePipelineRequest;
import org.opensearch.action.ingest.GetPipelineRequest;
@@ -48,9 +47,10 @@
import org.opensearch.client.OpenSearchRestHighLevelClientTestCase;
import org.opensearch.client.RequestOptions;
import org.opensearch.client.RestHighLevelClient;
-import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.common.bytes.BytesArray;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.ingest.PipelineConfiguration;
import java.io.IOException;
@@ -65,15 +65,15 @@
* You need to wrap your code between two tags like:
* // tag::example
* // end::example
- *
+ *
* Where example is your tag name.
- *
+ *
* Then in the documentation, you can extract what is between tag and end tags with
* ["source","java",subs="attributes,callouts,macros"]
* --------------------------------------------------
* include-tagged::{doc-tests}/IngestClientDocumentationIT.java[example]
* --------------------------------------------------
- *
+ *
* The column width of the code block is 84. If the code contains a line longer
* than 84, the line will be cut and a horizontal scroll bar will be displayed.
* (the code indentation of the tag is not included in the width)
@@ -91,7 +91,7 @@ public void testPutPipeline() throws IOException {
PutPipelineRequest request = new PutPipelineRequest(
"my-pipeline-id", // <1>
new BytesArray(source.getBytes(StandardCharsets.UTF_8)), // <2>
- XContentType.JSON // <3>
+ MediaTypeRegistry.JSON // <3>
);
// end::put-pipeline-request
@@ -125,7 +125,7 @@ public void testPutPipelineAsync() throws Exception {
PutPipelineRequest request = new PutPipelineRequest(
"my-pipeline-id",
new BytesArray(source.getBytes(StandardCharsets.UTF_8)),
- XContentType.JSON
+ MediaTypeRegistry.JSON
);
// tag::put-pipeline-execute-listener
@@ -314,7 +314,7 @@ public void testSimulatePipeline() throws IOException {
"}";
SimulatePipelineRequest request = new SimulatePipelineRequest(
new BytesArray(source.getBytes(StandardCharsets.UTF_8)), // <1>
- XContentType.JSON // <2>
+ MediaTypeRegistry.JSON // <2>
);
// end::simulate-pipeline-request
@@ -370,7 +370,7 @@ public void testSimulatePipelineAsync() throws Exception {
+ "}";
SimulatePipelineRequest request = new SimulatePipelineRequest(
new BytesArray(source.getBytes(StandardCharsets.UTF_8)),
- XContentType.JSON
+ MediaTypeRegistry.JSON
);
// tag::simulate-pipeline-execute-listener
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/QueryDSLDocumentationTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/QueryDSLDocumentationTests.java
index 9f5c2e51a7960..4304ef04f6dc4 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/QueryDSLDocumentationTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/QueryDSLDocumentationTests.java
@@ -39,10 +39,10 @@
import org.opensearch.common.geo.builders.MultiPointBuilder;
import org.opensearch.common.unit.DistanceUnit;
import org.opensearch.index.query.GeoShapeQueryBuilder;
+import org.opensearch.index.query.RankFeatureQueryBuilders;
import org.opensearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.opensearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder;
import org.opensearch.join.query.JoinQueryBuilders;
-import org.opensearch.index.query.RankFeatureQueryBuilders;
import org.opensearch.script.Script;
import org.opensearch.script.ScriptType;
import org.opensearch.test.OpenSearchTestCase;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java
index 7f7062f0e8a4c..bf0f70304168e 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SearchDocumentationIT.java
@@ -34,7 +34,6 @@
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.TotalHits;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.LatchedActionListener;
import org.opensearch.action.bulk.BulkRequest;
import org.opensearch.action.bulk.BulkResponse;
@@ -65,13 +64,15 @@
import org.opensearch.client.core.CountResponse;
import org.opensearch.client.indices.CreateIndexRequest;
import org.opensearch.client.indices.CreateIndexResponse;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.document.DocumentField;
-import org.opensearch.core.common.text.Text;
import org.opensearch.common.unit.Fuzziness;
import org.opensearch.common.unit.TimeValue;
import org.opensearch.common.xcontent.XContentFactory;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.common.text.Text;
+import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.index.get.GetResult;
import org.opensearch.index.query.MatchQueryBuilder;
import org.opensearch.index.query.QueryBuilder;
@@ -86,7 +87,6 @@
import org.opensearch.index.rankeval.RatedDocument;
import org.opensearch.index.rankeval.RatedRequest;
import org.opensearch.index.rankeval.RatedSearchHit;
-import org.opensearch.core.rest.RestStatus;
import org.opensearch.script.ScriptType;
import org.opensearch.script.mustache.MultiSearchTemplateRequest;
import org.opensearch.script.mustache.MultiSearchTemplateResponse;
@@ -319,9 +319,9 @@ public void testSearchRequestAggregations() throws IOException {
RestHighLevelClient client = highLevelClient();
{
BulkRequest request = new BulkRequest();
- request.add(new IndexRequest("posts").id("1").source(XContentType.JSON, "company", "OpenSearch", "age", 20));
- request.add(new IndexRequest("posts").id("2").source(XContentType.JSON, "company", "OpenSearch", "age", 30));
- request.add(new IndexRequest("posts").id("3").source(XContentType.JSON, "company", "OpenSearch", "age", 40));
+ request.add(new IndexRequest("posts").id("1").source(MediaTypeRegistry.JSON, "company", "OpenSearch", "age", 20));
+ request.add(new IndexRequest("posts").id("2").source(MediaTypeRegistry.JSON, "company", "OpenSearch", "age", 30));
+ request.add(new IndexRequest("posts").id("3").source(MediaTypeRegistry.JSON, "company", "OpenSearch", "age", 40));
request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
assertSame(RestStatus.OK, bulkResponse.status());
@@ -392,10 +392,10 @@ public void testSearchRequestSuggestions() throws IOException {
RestHighLevelClient client = highLevelClient();
{
BulkRequest request = new BulkRequest();
- request.add(new IndexRequest("posts").id("1").source(XContentType.JSON, "user", "foobar"));
- request.add(new IndexRequest("posts").id("2").source(XContentType.JSON, "user", "quxx"));
- request.add(new IndexRequest("posts").id("3").source(XContentType.JSON, "user", "quzz"));
- request.add(new IndexRequest("posts").id("4").source(XContentType.JSON, "user", "corge"));
+ request.add(new IndexRequest("posts").id("1").source(MediaTypeRegistry.JSON, "user", "foobar"));
+ request.add(new IndexRequest("posts").id("2").source(MediaTypeRegistry.JSON, "user", "quxx"));
+ request.add(new IndexRequest("posts").id("3").source(MediaTypeRegistry.JSON, "user", "quzz"));
+ request.add(new IndexRequest("posts").id("4").source(MediaTypeRegistry.JSON, "user", "corge"));
request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
assertSame(RestStatus.OK, bulkResponse.status());
@@ -438,7 +438,7 @@ public void testSearchRequestHighlighting() throws IOException {
request.add(
new IndexRequest("posts").id("1")
.source(
- XContentType.JSON,
+ MediaTypeRegistry.JSON,
"title",
"In which order are my OpenSearch queries executed?",
"user",
@@ -450,7 +450,7 @@ public void testSearchRequestHighlighting() throws IOException {
request.add(
new IndexRequest("posts").id("2")
.source(
- XContentType.JSON,
+ MediaTypeRegistry.JSON,
"title",
"Current status and upcoming changes in OpenSearch",
"user",
@@ -462,7 +462,7 @@ public void testSearchRequestHighlighting() throws IOException {
request.add(
new IndexRequest("posts").id("3")
.source(
- XContentType.JSON,
+ MediaTypeRegistry.JSON,
"title",
"The Future of Federated Search in OpenSearch",
"user",
@@ -525,7 +525,7 @@ public void testSearchRequestHighlighting() throws IOException {
public void testSearchRequestProfiling() throws IOException {
RestHighLevelClient client = highLevelClient();
{
- IndexRequest request = new IndexRequest("posts").id("1").source(XContentType.JSON, "tags", "opensearch", "comments", 123);
+ IndexRequest request = new IndexRequest("posts").id("1").source(MediaTypeRegistry.JSON, "tags", "opensearch", "comments", 123);
request.setRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
assertSame(RestStatus.CREATED, indexResponse.status());
@@ -597,13 +597,15 @@ public void testScroll() throws Exception {
{
BulkRequest request = new BulkRequest();
request.add(
- new IndexRequest("posts").id("1").source(XContentType.JSON, "title", "In which order are my OpenSearch queries executed?")
+ new IndexRequest("posts").id("1")
+ .source(MediaTypeRegistry.JSON, "title", "In which order are my OpenSearch queries executed?")
);
request.add(
- new IndexRequest("posts").id("2").source(XContentType.JSON, "title", "Current status and upcoming changes in OpenSearch")
+ new IndexRequest("posts").id("2")
+ .source(MediaTypeRegistry.JSON, "title", "Current status and upcoming changes in OpenSearch")
);
request.add(
- new IndexRequest("posts").id("3").source(XContentType.JSON, "title", "The Future of Federated Search in OpenSearch")
+ new IndexRequest("posts").id("3").source(MediaTypeRegistry.JSON, "title", "The Future of Federated Search in OpenSearch")
);
request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
BulkResponse bulkResponse = client.bulk(request, RequestOptions.DEFAULT);
@@ -1320,7 +1322,7 @@ private void indexSearchTestData() throws IOException {
bulkRequest.add(
new IndexRequest("posts").id("1")
.source(
- XContentType.JSON,
+ MediaTypeRegistry.JSON,
"id",
1,
"title",
@@ -1334,7 +1336,7 @@ private void indexSearchTestData() throws IOException {
bulkRequest.add(
new IndexRequest("posts").id("2")
.source(
- XContentType.JSON,
+ MediaTypeRegistry.JSON,
"id",
2,
"title",
@@ -1348,7 +1350,7 @@ private void indexSearchTestData() throws IOException {
bulkRequest.add(
new IndexRequest("posts").id("3")
.source(
- XContentType.JSON,
+ MediaTypeRegistry.JSON,
"id",
3,
"title",
@@ -1360,8 +1362,8 @@ private void indexSearchTestData() throws IOException {
)
);
- bulkRequest.add(new IndexRequest("authors").id("1").source(XContentType.JSON, "id", 1, "user", "foobar"));
- bulkRequest.add(new IndexRequest("contributors").id("1").source(XContentType.JSON, "id", 1, "user", "quuz"));
+ bulkRequest.add(new IndexRequest("authors").id("1").source(MediaTypeRegistry.JSON, "id", 1, "user", "foobar"));
+ bulkRequest.add(new IndexRequest("contributors").id("1").source(MediaTypeRegistry.JSON, "id", 1, "user", "quuz"));
bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
BulkResponse bulkResponse = highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT);
@@ -1472,7 +1474,7 @@ private static void indexCountTestData() throws IOException {
bulkRequest.add(
new IndexRequest("blog").id("1")
.source(
- XContentType.JSON,
+ MediaTypeRegistry.JSON,
"title",
"Doubling Down on Open?",
"user",
@@ -1484,7 +1486,7 @@ private static void indexCountTestData() throws IOException {
bulkRequest.add(
new IndexRequest("blog").id("2")
.source(
- XContentType.JSON,
+ MediaTypeRegistry.JSON,
"title",
"XYZ Joins Forces with OpenSearch",
"user",
@@ -1496,7 +1498,7 @@ private static void indexCountTestData() throws IOException {
bulkRequest.add(
new IndexRequest("blog").id("3")
.source(
- XContentType.JSON,
+ MediaTypeRegistry.JSON,
"title",
"On Net Neutrality",
"user",
@@ -1506,7 +1508,7 @@ private static void indexCountTestData() throws IOException {
)
);
- bulkRequest.add(new IndexRequest("author").id("1").source(XContentType.JSON, "user", "foobar"));
+ bulkRequest.add(new IndexRequest("author").id("1").source(MediaTypeRegistry.JSON, "user", "foobar"));
bulkRequest.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
BulkResponse bulkResponse = highLevelClient().bulk(bulkRequest, RequestOptions.DEFAULT);
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java
index 976c69910d309..d0015db044843 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/SnapshotClientDocumentationIT.java
@@ -32,7 +32,6 @@
package org.opensearch.client.documentation;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.LatchedActionListener;
import org.opensearch.action.admin.cluster.repositories.delete.DeleteRepositoryRequest;
import org.opensearch.action.admin.cluster.repositories.get.GetRepositoriesRequest;
@@ -64,9 +63,10 @@
import org.opensearch.common.Booleans;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.common.xcontent.XContentType;
-import org.opensearch.repositories.fs.FsRepository;
+import org.opensearch.core.action.ActionListener;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.repositories.fs.FsRepository;
import org.opensearch.snapshots.RestoreInfo;
import org.opensearch.snapshots.SnapshotId;
import org.opensearch.snapshots.SnapshotInfo;
@@ -90,15 +90,15 @@
* You need to wrap your code between two tags like:
* // tag::example
* // end::example
- *
+ *
* Where example is your tag name.
- *
+ *
* Then in the documentation, you can extract what is between tag and end tags with
* ["source","java",subs="attributes,callouts,macros"]
* --------------------------------------------------
* include-tagged::{doc-tests}/SnapshotClientDocumentationIT.java[example]
* --------------------------------------------------
- *
+ *
* The column width of the code block is 84. If the code contains a line longer
* than 84, the line will be cut and a horizontal scroll bar will be displayed.
* (the code indentation of the tag is not included in the width)
@@ -156,7 +156,7 @@ public void testSnapshotCreateRepository() throws IOException {
{
// tag::create-repository-settings-source
request.settings("{\"location\": \".\", \"compress\": \"true\"}",
- XContentType.JSON); // <1>
+ MediaTypeRegistry.JSON); // <1>
// end::create-repository-settings-source
}
@@ -818,7 +818,7 @@ public void onFailure(Exception e) {
private void createTestRepositories() throws IOException {
PutRepositoryRequest request = new PutRepositoryRequest(repositoryName);
request.type(FsRepository.TYPE);
- request.settings("{\"location\": \".\"}", XContentType.JSON);
+ request.settings("{\"location\": \".\"}", MediaTypeRegistry.JSON);
assertTrue(highLevelClient().snapshot().createRepository(request, RequestOptions.DEFAULT).isAcknowledged());
}
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java
index 742dfa69e718b..2e2d15df5392a 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/StoredScriptsDocumentationIT.java
@@ -32,7 +32,6 @@
package org.opensearch.client.documentation;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.LatchedActionListener;
import org.opensearch.action.admin.cluster.storedscripts.DeleteStoredScriptRequest;
import org.opensearch.action.admin.cluster.storedscripts.GetStoredScriptRequest;
@@ -42,12 +41,13 @@
import org.opensearch.client.OpenSearchRestHighLevelClientTestCase;
import org.opensearch.client.RequestOptions;
import org.opensearch.client.RestHighLevelClient;
+import org.opensearch.common.unit.TimeValue;
+import org.opensearch.common.xcontent.XContentFactory;
+import org.opensearch.core.action.ActionListener;
import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.common.bytes.BytesReference;
-import org.opensearch.common.unit.TimeValue;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.common.xcontent.XContentFactory;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.script.Script;
import org.opensearch.script.StoredScriptSource;
@@ -66,15 +66,15 @@
* You need to wrap your code between two tags like:
* // tag::example
* // end::example
- *
+ *
* Where example is your tag name.
- *
+ *
* Then in the documentation, you can extract what is between tag and end tags with
* ["source","java",subs="attributes,callouts,macros"]
* --------------------------------------------------
* include-tagged::{doc-tests}/StoredScriptsDocumentationIT.java[example]
* --------------------------------------------------
- *
+ *
* The column width of the code block is 84. If the code contains a line longer
* than 84, the line will be cut and a horizontal scroll bar will be displayed.
* (the code indentation of the tag is not included in the width)
@@ -88,7 +88,7 @@ public void testGetStoredScript() throws Exception {
final StoredScriptSource scriptSource = new StoredScriptSource(
"painless",
"Math.log(_score * 2) + params.my_modifier",
- Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())
+ Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType())
);
putStoredScript("calculate-score", scriptSource);
@@ -152,7 +152,7 @@ public void testDeleteStoredScript() throws Exception {
final StoredScriptSource scriptSource = new StoredScriptSource(
"painless",
"Math.log(_score * 2) + params.my_modifier",
- Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType())
+ Collections.singletonMap(Script.CONTENT_TYPE_OPTION, MediaTypeRegistry.JSON.mediaType())
);
putStoredScript("calculate-score", scriptSource);
@@ -221,7 +221,7 @@ public void testPutScript() throws Exception {
"\"source\": \"Math.log(_score * 2) + params.multiplier\"" +
"}\n" +
"}\n"
- ), XContentType.JSON); // <2>
+ ), MediaTypeRegistry.JSON); // <2>
// end::put-stored-script-request
// tag::put-stored-script-context
@@ -255,7 +255,7 @@ public void testPutScript() throws Exception {
builder.endObject();
}
builder.endObject();
- request.content(BytesReference.bytes(builder), XContentType.JSON); // <1>
+ request.content(BytesReference.bytes(builder), MediaTypeRegistry.JSON); // <1>
// end::put-stored-script-content-painless
// tag::put-stored-script-execute
@@ -310,7 +310,7 @@ public void onFailure(Exception e) {
builder.endObject();
}
builder.endObject();
- request.content(BytesReference.bytes(builder), XContentType.JSON); // <1>
+ request.content(BytesReference.bytes(builder), MediaTypeRegistry.JSON); // <1>
// end::put-stored-script-content-mustache
client.putScript(request, RequestOptions.DEFAULT);
@@ -322,7 +322,13 @@ public void onFailure(Exception e) {
}
private void putStoredScript(String id, StoredScriptSource scriptSource) throws IOException {
- PutStoredScriptRequest request = new PutStoredScriptRequest(id, "score", new BytesArray("{}"), XContentType.JSON, scriptSource);
+ PutStoredScriptRequest request = new PutStoredScriptRequest(
+ id,
+ "score",
+ new BytesArray("{}"),
+ MediaTypeRegistry.JSON,
+ scriptSource
+ );
assertAcked(execute(request, highLevelClient()::putScript, highLevelClient()::putScriptAsync));
}
}
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/TasksClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/TasksClientDocumentationIT.java
index 05479e2e3e81c..cbac0b8c97d9c 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/documentation/TasksClientDocumentationIT.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/documentation/TasksClientDocumentationIT.java
@@ -33,7 +33,6 @@
package org.opensearch.client.documentation;
import org.opensearch.OpenSearchException;
-import org.opensearch.action.ActionListener;
import org.opensearch.action.LatchedActionListener;
import org.opensearch.action.TaskOperationFailure;
import org.opensearch.action.admin.cluster.node.tasks.list.ListTasksRequest;
@@ -45,7 +44,8 @@
import org.opensearch.client.tasks.CancelTasksRequest;
import org.opensearch.client.tasks.CancelTasksResponse;
import org.opensearch.common.unit.TimeValue;
-import org.opensearch.tasks.TaskId;
+import org.opensearch.core.action.ActionListener;
+import org.opensearch.core.tasks.TaskId;
import org.opensearch.tasks.TaskInfo;
import java.io.IOException;
@@ -66,15 +66,15 @@
* You need to wrap your code between two tags like:
* // tag::example
* // end::example
- *
+ *
* Where example is your tag name.
- *
+ *
* Then in the documentation, you can extract what is between tag and end tags with
* ["source","java",subs="attributes,callouts,macros"]
* --------------------------------------------------
* include-tagged::{doc-tests}/{@link TasksClientDocumentationIT}.java[example]
* --------------------------------------------------
- *
+ *
* The column width of the code block is 84. If the code contains a line longer
* than 84, the line will be cut and a horizontal scroll bar will be displayed.
* (the code indentation of the tag is not included in the width)
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/AnalyzeResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/AnalyzeResponseTests.java
index 920235d848f66..dadd64f8329cc 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/AnalyzeResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/AnalyzeResponseTests.java
@@ -34,8 +34,8 @@
import org.opensearch.action.admin.indices.analyze.AnalyzeAction;
import org.opensearch.client.AbstractResponseTestCase;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.test.RandomObjects;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/CloseIndexResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/CloseIndexResponseTests.java
index b83bdab899a41..6aafee142bd22 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/CloseIndexResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/CloseIndexResponseTests.java
@@ -35,16 +35,15 @@
import org.opensearch.action.support.master.AcknowledgedResponse;
import org.opensearch.action.support.master.ShardsAcknowledgedResponse;
import org.opensearch.client.AbstractResponseTestCase;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.xcontent.LoggingDeprecationHandler;
+import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.index.Index;
+import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.XContent;
-import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.common.xcontent.XContentType;
-import org.opensearch.core.index.Index;
import org.opensearch.index.IndexNotFoundException;
-import org.opensearch.core.rest.RestStatus;
import org.opensearch.transport.ActionNotFoundTransportException;
import java.io.IOException;
@@ -194,7 +193,7 @@ public final void testBwcFromXContent() throws IOException {
final XContentType xContentType = randomFrom(XContentType.values());
final BytesReference bytes = toShuffledXContent(expected, xContentType, getParams(), randomBoolean());
- final XContent xContent = XContentFactory.xContent(xContentType);
+ final XContent xContent = xContentType.xContent();
final XContentParser parser = xContent.createParser(
NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE,
@@ -215,7 +214,7 @@ public final void testBwcFromXContent() throws IOException {
final XContentType xContentType = randomFrom(XContentType.values());
final BytesReference bytes = toShuffledXContent(expected, xContentType, getParams(), randomBoolean());
- final XContent xContent = XContentFactory.xContent(xContentType);
+ final XContent xContent = xContentType.xContent();
final XContentParser parser = xContent.createParser(
NamedXContentRegistry.EMPTY,
LoggingDeprecationHandler.INSTANCE,
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/DataStreamsStatsResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/DataStreamsStatsResponseTests.java
index 96db2fb43c161..9418a82fc6107 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/DataStreamsStatsResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/DataStreamsStatsResponseTests.java
@@ -34,11 +34,11 @@
import org.opensearch.OpenSearchException;
import org.opensearch.action.admin.indices.datastream.DataStreamsStatsAction;
-import org.opensearch.core.action.support.DefaultShardOperationFailedException;
import org.opensearch.client.AbstractResponseTestCase;
-import org.opensearch.common.unit.ByteSizeValue;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.action.support.DefaultShardOperationFailedException;
+import org.opensearch.core.common.unit.ByteSizeValue;
+import org.opensearch.core.xcontent.XContentParser;
import java.io.IOException;
import java.util.ArrayList;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetDataStreamResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetDataStreamResponseTests.java
index 523758c11de6b..3f0d56a3d9455 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetDataStreamResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetDataStreamResponseTests.java
@@ -38,9 +38,9 @@
import org.opensearch.cluster.health.ClusterHealthStatus;
import org.opensearch.cluster.metadata.DataStream;
import org.opensearch.common.UUIDs;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.index.Index;
+import org.opensearch.core.xcontent.XContentParser;
import java.io.IOException;
import java.util.ArrayList;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexResponseTests.java
index 374c33389dd3a..a00f0487116dc 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexResponseTests.java
@@ -39,8 +39,8 @@
import org.opensearch.cluster.metadata.MappingMetadata;
import org.opensearch.common.settings.IndexScopedSettings;
import org.opensearch.common.settings.Settings;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.index.RandomCreateIndexGenerator;
import org.opensearch.index.mapper.MapperService;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexTemplatesResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexTemplatesResponseTests.java
index 6f924898096a0..507dc7802283f 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexTemplatesResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetIndexTemplatesResponseTests.java
@@ -34,18 +34,18 @@
import org.opensearch.cluster.metadata.AliasMetadata;
import org.opensearch.cluster.metadata.MappingMetadata;
-import org.opensearch.core.common.bytes.BytesArray;
-import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.common.compress.CompressedXContent;
import org.opensearch.common.settings.Settings;
+import org.opensearch.common.xcontent.XContentHelper;
+import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.common.bytes.BytesArray;
+import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.DeprecationHandler;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.NamedXContentRegistry;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.common.xcontent.XContentFactory;
-import org.opensearch.common.xcontent.XContentHelper;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.index.mapper.MapperService;
import org.opensearch.test.OpenSearchTestCase;
@@ -164,7 +164,7 @@ private Predicate randomFieldsExcludeFilter() {
private static void assertEqualInstances(GetIndexTemplatesResponse expectedInstance, GetIndexTemplatesResponse newInstance) {
assertEquals(expectedInstance, newInstance);
// Check there's no doc types at the root of the mapping
- Map expectedMap = XContentHelper.convertToMap(new BytesArray(mappingString), true, XContentType.JSON).v2();
+ Map expectedMap = XContentHelper.convertToMap(new BytesArray(mappingString), true, MediaTypeRegistry.JSON).v2();
for (IndexTemplateMetadata template : newInstance.getIndexTemplates()) {
MappingMetadata mappingMD = template.mappings();
if (mappingMD != null) {
@@ -194,7 +194,7 @@ static GetIndexTemplatesResponse createTestInstance() {
templateBuilder.version(between(0, 100));
}
if (randomBoolean()) {
- Map map = XContentHelper.convertToMap(new BytesArray(mappingString), true, XContentType.JSON).v2();
+ Map map = XContentHelper.convertToMap(new BytesArray(mappingString), true, MediaTypeRegistry.JSON).v2();
MappingMetadata mapping = new MappingMetadata(MapperService.SINGLE_MAPPING_NAME, map);
templateBuilder.mapping(mapping);
}
@@ -262,7 +262,7 @@ private static AliasMetadata randomAliasMetadata(String name) {
}
static XContentBuilder randomMapping(String type, XContentType xContentType) throws IOException {
- XContentBuilder builder = XContentFactory.contentBuilder(xContentType);
+ XContentBuilder builder = MediaTypeRegistry.contentBuilder(xContentType);
builder.startObject().startObject(type);
randomMappingFields(builder, true);
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetMappingsResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetMappingsResponseTests.java
index fe87e0fe6aac9..6d80cdd3ad074 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetMappingsResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/GetMappingsResponseTests.java
@@ -34,8 +34,8 @@
import org.opensearch.client.AbstractResponseTestCase;
import org.opensearch.cluster.metadata.MappingMetadata;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.index.mapper.MapperService;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/RandomCreateIndexGenerator.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/RandomCreateIndexGenerator.java
index 415ed18ddf4f2..edb4d16c6d992 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/RandomCreateIndexGenerator.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/RandomCreateIndexGenerator.java
@@ -32,8 +32,8 @@
package org.opensearch.client.indices;
-import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentFactory;
+import org.opensearch.core.xcontent.XContentBuilder;
import java.io.IOException;
@@ -44,7 +44,7 @@ public class RandomCreateIndexGenerator {
/**
* Returns a random {@link CreateIndexRequest}.
- *
+ *
* Randomizes the index name, the aliases, mappings and settings associated with the
* index. When present, the mappings make no mention of types.
*/
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/ResizeResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/ResizeResponseTests.java
index 1539f500dabc7..919cc89a9ae44 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/ResizeResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/ResizeResponseTests.java
@@ -33,8 +33,8 @@
package org.opensearch.client.indices;
import org.opensearch.client.AbstractResponseTestCase;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.XContentParser;
import java.io.IOException;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverRequestTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverRequestTests.java
index 9d51c09ba2e44..b4e0fc8f7f38c 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverRequestTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverRequestTests.java
@@ -36,8 +36,8 @@
import org.opensearch.action.admin.indices.rollover.MaxAgeCondition;
import org.opensearch.action.admin.indices.rollover.MaxDocsCondition;
import org.opensearch.action.admin.indices.rollover.MaxSizeCondition;
-import org.opensearch.common.unit.ByteSizeValue;
import org.opensearch.common.unit.TimeValue;
+import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.test.OpenSearchTestCase;
import java.util.ArrayList;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverResponseTests.java
index ff2418c5caee2..14477f07f8b42 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/indices/rollover/RolloverResponseTests.java
@@ -36,8 +36,8 @@
import org.opensearch.action.admin.indices.rollover.MaxAgeCondition;
import org.opensearch.action.admin.indices.rollover.MaxDocsCondition;
import org.opensearch.action.admin.indices.rollover.MaxSizeCondition;
-import org.opensearch.common.unit.ByteSizeValue;
import org.opensearch.common.unit.TimeValue;
+import org.opensearch.core.common.unit.ByteSizeValue;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.test.OpenSearchTestCase;
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/tasks/CancelTasksResponseTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/tasks/CancelTasksResponseTests.java
index e6411b615df07..faf5024d0c173 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/tasks/CancelTasksResponseTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/tasks/CancelTasksResponseTests.java
@@ -38,14 +38,14 @@
import org.opensearch.client.AbstractResponseTestCase;
import org.opensearch.cluster.node.DiscoveryNode;
import org.opensearch.cluster.node.DiscoveryNodes;
+import org.opensearch.common.xcontent.XContentType;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
-import org.opensearch.common.transport.TransportAddress;
+import org.opensearch.core.common.transport.TransportAddress;
+import org.opensearch.core.tasks.TaskId;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.common.xcontent.XContentType;
import org.opensearch.tasks.Task;
-import org.opensearch.tasks.TaskId;
import org.opensearch.tasks.TaskInfo;
import java.io.IOException;
@@ -84,6 +84,10 @@ protected CancelTasksResponseTests.ByNodeCancelTasksResponse createServerTestIns
for (int i = 0; i < 4; i++) {
boolean cancellable = randomBoolean();
boolean cancelled = cancellable == true ? randomBoolean() : false;
+ Long cancellationStartTime = null;
+ if (cancelled) {
+ cancellationStartTime = randomNonNegativeLong();
+ }
tasks.add(
new org.opensearch.tasks.TaskInfo(
new TaskId(NODE_ID, (long) i),
@@ -97,7 +101,8 @@ protected CancelTasksResponseTests.ByNodeCancelTasksResponse createServerTestIns
cancelled,
new TaskId("node1", randomLong()),
Collections.singletonMap("x-header-of", "some-value"),
- null
+ null,
+ cancellationStartTime
)
);
}
@@ -135,6 +140,7 @@ protected void assertInstances(
assertEquals(ti.isCancelled(), taskInfo.isCancelled());
assertEquals(ti.getParentTaskId().getNodeId(), taskInfo.getParentTaskId().getNodeId());
assertEquals(ti.getParentTaskId().getId(), taskInfo.getParentTaskId().getId());
+ assertEquals(ti.getCancellationStartTime(), taskInfo.getCancellationStartTime());
FakeTaskStatus status = (FakeTaskStatus) ti.getStatus();
assertEquals(status.code, taskInfo.getStatus().get("code"));
assertEquals(status.status, taskInfo.getStatus().get("status"));
diff --git a/client/rest-high-level/src/test/java/org/opensearch/client/tasks/OpenSearchExceptionTests.java b/client/rest-high-level/src/test/java/org/opensearch/client/tasks/OpenSearchExceptionTests.java
index df621e67ca3b7..fb8e4f731fb19 100644
--- a/client/rest-high-level/src/test/java/org/opensearch/client/tasks/OpenSearchExceptionTests.java
+++ b/client/rest-high-level/src/test/java/org/opensearch/client/tasks/OpenSearchExceptionTests.java
@@ -32,8 +32,8 @@
package org.opensearch.client.tasks;
import org.opensearch.client.AbstractResponseTestCase;
-import org.opensearch.core.xcontent.XContentParser;
import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.XContentParser;
import java.io.IOException;
import java.util.Collections;
diff --git a/client/rest/build.gradle b/client/rest/build.gradle
index 2c437c909fb03..f18df65dfddfa 100644
--- a/client/rest/build.gradle
+++ b/client/rest/build.gradle
@@ -34,13 +34,13 @@ apply plugin: 'opensearch.build'
apply plugin: 'opensearch.publish'
java {
- targetCompatibility = JavaVersion.VERSION_11
- sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_1_8
+ sourceCompatibility = JavaVersion.VERSION_1_8
}
base {
group = 'org.opensearch.client'
- archivesBaseName = 'opensearch-rest-client'
+ archivesName = 'opensearch-rest-client'
}
dependencies {
@@ -109,3 +109,10 @@ thirdPartyAudit.ignoreMissingClasses(
'javax.servlet.ServletContextEvent',
'javax.servlet.ServletContextListener'
)
+
+tasks.withType(JavaCompile) {
+ // Suppressing '[options] target value 8 is obsolete and will be removed in a future release'
+ configure(options) {
+ options.compilerArgs << '-Xlint:-options'
+ }
+}
diff --git a/client/rest/src/main/java/org/opensearch/client/RestClient.java b/client/rest/src/main/java/org/opensearch/client/RestClient.java
index 9d140a145b004..15905add76c4f 100644
--- a/client/rest/src/main/java/org/opensearch/client/RestClient.java
+++ b/client/rest/src/main/java/org/opensearch/client/RestClient.java
@@ -33,22 +33,13 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.apache.hc.core5.http.ClassicHttpResponse;
-import org.apache.hc.core5.http.ConnectionClosedException;
-import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.HttpEntity;
-import org.apache.hc.core5.http.io.entity.HttpEntityWrapper;
-import org.apache.hc.core5.http.HttpHost;
-import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.client5.http.ClientProtocolException;
+import org.apache.hc.client5.http.ConnectTimeoutException;
import org.apache.hc.client5.http.auth.AuthCache;
import org.apache.hc.client5.http.auth.AuthScheme;
import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.Credentials;
import org.apache.hc.client5.http.auth.CredentialsProvider;
-import org.apache.hc.client5.http.ConnectTimeoutException;
-import org.apache.hc.client5.http.ClientProtocolException;
-import org.apache.hc.client5.http.entity.GzipDecompressingEntity;
-import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpHead;
@@ -56,9 +47,22 @@
import org.apache.hc.client5.http.classic.methods.HttpPatch;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
-import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.classic.methods.HttpTrace;
+import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
+import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.entity.GzipDecompressingEntity;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.auth.BasicAuthCache;
+import org.apache.hc.client5.http.impl.auth.BasicScheme;
import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ClassicHttpResponse;
+import org.apache.hc.core5.http.ConnectionClosedException;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpEntity;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.io.entity.HttpEntityWrapper;
import org.apache.hc.core5.http.message.RequestLine;
import org.apache.hc.core5.http.nio.AsyncRequestProducer;
import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
@@ -66,12 +70,9 @@
import org.apache.hc.core5.reactor.IOReactorStatus;
import org.apache.hc.core5.util.Args;
import org.opensearch.client.http.HttpUriRequestProducer;
-import org.apache.hc.core5.concurrent.FutureCallback;
-import org.apache.hc.client5.http.impl.auth.BasicScheme;
-import org.apache.hc.client5.http.impl.auth.BasicAuthCache;
-import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
import javax.net.ssl.SSLHandshakeException;
+
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
@@ -309,7 +310,7 @@ public boolean isRunning() {
* they will be retried). In case of failures all of the alive nodes (or
* dead nodes that deserve a retry) are retried until one responds or none
* of them does, in which case an {@link IOException} will be thrown.
- *
+ *
* This method works by performing an asynchronous call and waiting
* for the result. If the asynchronous call throws an exception we wrap
* it and rethrow it so that the stack trace attached to the exception
@@ -1115,9 +1116,15 @@ public long getContentLength() {
if (chunkedEnabled.get()) {
return -1L;
} else {
- long size;
+ long size = 0;
+ final byte[] buf = new byte[8192];
+ int nread = 0;
+
try (InputStream is = getContent()) {
- size = is.readAllBytes().length;
+ // read to EOF which may read more or less than buffer size
+ while ((nread = is.read(buf)) > 0) {
+ size += nread;
+ }
} catch (IOException ex) {
size = -1L;
}
diff --git a/client/rest/src/main/java/org/opensearch/client/RestClientBuilder.java b/client/rest/src/main/java/org/opensearch/client/RestClientBuilder.java
index a01cf2f403099..3e38f9ae95dec 100644
--- a/client/rest/src/main/java/org/opensearch/client/RestClientBuilder.java
+++ b/client/rest/src/main/java/org/opensearch/client/RestClientBuilder.java
@@ -32,22 +32,22 @@
package org.opensearch.client;
-import org.apache.hc.core5.function.Factory;
-import org.apache.hc.core5.http.Header;
-import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
-import org.apache.hc.core5.reactor.ssl.TlsDetails;
-import org.apache.hc.core5.util.Timeout;
import org.apache.hc.client5.http.async.HttpAsyncClient;
import org.apache.hc.client5.http.auth.CredentialsProvider;
import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
-import org.apache.hc.client5.http.impl.DefaultAuthenticationStrategy;
-import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
-import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder;
+import org.apache.hc.core5.function.Factory;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
+import org.apache.hc.core5.reactor.ssl.TlsDetails;
+import org.apache.hc.core5.util.Timeout;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
diff --git a/client/rest/src/main/java/org/opensearch/client/nio/HeapBufferedAsyncEntityConsumer.java b/client/rest/src/main/java/org/opensearch/client/nio/HeapBufferedAsyncEntityConsumer.java
index 9bd17d1c24c7e..ae38c1a0308d1 100644
--- a/client/rest/src/main/java/org/opensearch/client/nio/HeapBufferedAsyncEntityConsumer.java
+++ b/client/rest/src/main/java/org/opensearch/client/nio/HeapBufferedAsyncEntityConsumer.java
@@ -86,25 +86,29 @@ protected void data(final ByteBuffer src, final boolean endOfStream) throws IOEx
return;
}
+ int len = src.limit();
+ if (len < 0) {
+ len = 4096;
+ } else if (len > bufferLimitBytes) {
+ throw new ContentTooLongException(
+ "entity content is too long [" + len + "] for the configured buffer limit [" + bufferLimitBytes + "]"
+ );
+ }
+
ByteArrayBuffer buffer = bufferRef.get();
if (buffer == null) {
- buffer = new ByteArrayBuffer(bufferLimitBytes);
+ buffer = new ByteArrayBuffer(len);
if (bufferRef.compareAndSet(null, buffer) == false) {
buffer = bufferRef.get();
}
}
- int len = src.limit();
if (buffer.length() + len > bufferLimitBytes) {
throw new ContentTooLongException(
"entity content is too long [" + len + "] for the configured buffer limit [" + bufferLimitBytes + "]"
);
}
- if (len < 0) {
- len = 4096;
- }
-
if (src.hasArray()) {
buffer.append(src.array(), src.arrayOffset() + src.position(), src.remaining());
} else {
@@ -136,4 +140,12 @@ public void releaseResources() {
buffer = null;
}
}
+
+ /**
+ * Gets current byte buffer instance
+ * @return byte buffer instance
+ */
+ ByteArrayBuffer getBuffer() {
+ return bufferRef.get();
+ }
}
diff --git a/client/rest/src/test/java/org/opensearch/client/FailureTrackingResponseListenerTests.java b/client/rest/src/test/java/org/opensearch/client/FailureTrackingResponseListenerTests.java
index 9722ec867a376..9c12c79cdb1c3 100644
--- a/client/rest/src/test/java/org/opensearch/client/FailureTrackingResponseListenerTests.java
+++ b/client/rest/src/test/java/org/opensearch/client/FailureTrackingResponseListenerTests.java
@@ -35,8 +35,8 @@
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.ProtocolVersion;
-import org.apache.hc.core5.http.message.RequestLine;
import org.apache.hc.core5.http.message.BasicClassicHttpResponse;
+import org.apache.hc.core5.http.message.RequestLine;
import java.util.concurrent.atomic.AtomicReference;
diff --git a/client/rest/src/test/java/org/opensearch/client/NodeTests.java b/client/rest/src/test/java/org/opensearch/client/NodeTests.java
index 748bec5fb7de5..9efc34d72c341 100644
--- a/client/rest/src/test/java/org/opensearch/client/NodeTests.java
+++ b/client/rest/src/test/java/org/opensearch/client/NodeTests.java
@@ -46,11 +46,11 @@
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
+import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
-import static org.hamcrest.CoreMatchers.equalTo;
public class NodeTests extends RestClientTestCase {
public void testToString() {
diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientBuilderIntegTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientBuilderIntegTests.java
index f5e1735042e66..0b7cf6e8bb5fe 100644
--- a/client/rest/src/test/java/org/opensearch/client/RestClientBuilderIntegTests.java
+++ b/client/rest/src/test/java/org/opensearch/client/RestClientBuilderIntegTests.java
@@ -45,6 +45,7 @@
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManagerFactory;
+
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostIntegTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostIntegTests.java
index beee1c5ca21a0..de04dd843b2db 100644
--- a/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostIntegTests.java
+++ b/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostIntegTests.java
@@ -48,15 +48,16 @@
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicHeader;
import org.apache.hc.core5.http.nio.AsyncResponseConsumer;
import org.apache.hc.core5.net.URIBuilder;
-import org.junit.After;
-import org.junit.Before;
import org.opensearch.client.http.HttpUriRequestProducer;
import org.opensearch.client.nio.HeapBufferedAsyncResponseConsumer;
+import org.junit.After;
+import org.junit.Before;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -73,6 +74,7 @@
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
+import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
@@ -298,37 +300,70 @@ public void testRequestResetAndAbort() throws Exception {
httpGet.reset();
assertFalse(httpGet.isAborted());
- Future future = client.execute(getRequestProducer(httpGet, httpHost), getResponseConsumer(), null);
- httpGet.setDependency((org.apache.hc.core5.concurrent.Cancellable) future);
- httpGet.abort();
+ final Phaser phaser = new Phaser(2);
+ phaser.register();
try {
- future.get();
- fail("expected cancellation exception");
- } catch (CancellationException e) {
- // expected
+ Future future = client.execute(
+ getRequestProducer(httpGet, httpHost),
+ getResponseConsumer(phaser),
+ null
+ );
+ httpGet.setDependency((org.apache.hc.core5.concurrent.Cancellable) future);
+ httpGet.abort();
+
+ try {
+ phaser.arriveAndDeregister();
+ future.get();
+ fail("expected cancellation exception");
+ } catch (CancellationException e) {
+ // expected
+ }
+ assertTrue(future.isCancelled());
+ } finally {
+ // Forcing termination since the AsyncResponseConsumer may not be reached,
+ // the request is aborted right before
+ phaser.forceTermination();
}
- assertTrue(future.isCancelled());
}
{
- httpGet.reset();
- Future future = client.execute(getRequestProducer(httpGet, httpHost), getResponseConsumer(), null);
- assertFalse(httpGet.isAborted());
- httpGet.setDependency((org.apache.hc.core5.concurrent.Cancellable) future);
- httpGet.abort();
- assertTrue(httpGet.isAborted());
+ final Phaser phaser = new Phaser(2);
+ phaser.register();
+
try {
- assertTrue(future.isCancelled());
- future.get();
- throw new AssertionError("exception should have been thrown");
- } catch (CancellationException e) {
- // expected
+ httpGet.reset();
+ Future future = client.execute(
+ getRequestProducer(httpGet, httpHost),
+ getResponseConsumer(phaser),
+ null
+ );
+ assertFalse(httpGet.isAborted());
+ httpGet.setDependency((org.apache.hc.core5.concurrent.Cancellable) future);
+ httpGet.abort();
+ assertTrue(httpGet.isAborted());
+ try {
+ phaser.arriveAndDeregister();
+ assertTrue(future.isCancelled());
+ future.get();
+ throw new AssertionError("exception should have been thrown");
+ } catch (CancellationException e) {
+ // expected
+ }
+ } finally {
+ // Forcing termination since the AsyncResponseConsumer may not be reached,
+ // the request is aborted right before
+ phaser.forceTermination();
}
}
{
httpGet.reset();
assertFalse(httpGet.isAborted());
- Future future = client.execute(getRequestProducer(httpGet, httpHost), getResponseConsumer(), null);
+ final Phaser phaser = new Phaser(0);
+ Future future = client.execute(
+ getRequestProducer(httpGet, httpHost),
+ getResponseConsumer(phaser),
+ null
+ );
assertFalse(httpGet.isAborted());
assertEquals(200, future.get().getCode());
assertFalse(future.isCancelled());
@@ -554,8 +589,15 @@ private Response bodyTest(RestClient restClient, String method, int statusCode,
return esResponse;
}
- private AsyncResponseConsumer getResponseConsumer() {
- return new HeapBufferedAsyncResponseConsumer(1024);
+ private AsyncResponseConsumer getResponseConsumer(Phaser phaser) {
+ phaser.register();
+ return new HeapBufferedAsyncResponseConsumer(1024) {
+ @Override
+ protected ClassicHttpResponse buildResult(HttpResponse response, byte[] entity, ContentType contentType) {
+ phaser.arriveAndAwaitAdvance();
+ return super.buildResult(response, entity, contentType);
+ }
+ };
}
private HttpUriRequestProducer getRequestProducer(HttpUriRequestBase request, HttpHost host) {
diff --git a/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostTests.java b/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostTests.java
index f46a91aa910f8..1d57fe2c8dcab 100644
--- a/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostTests.java
+++ b/client/rest/src/test/java/org/opensearch/client/RestClientSingleHostTests.java
@@ -67,11 +67,12 @@
import org.apache.hc.core5.net.URIBuilder;
import org.apache.hc.core5.reactor.IOReactorStatus;
import org.apache.hc.core5.util.TimeValue;
+import org.opensearch.client.http.HttpUriRequestProducer;
import org.junit.After;
import org.junit.Before;
-import org.opensearch.client.http.HttpUriRequestProducer;
import javax.net.ssl.SSLHandshakeException;
+
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
diff --git a/client/rest/src/test/java/org/opensearch/client/documentation/RestClientDocumentation.java b/client/rest/src/test/java/org/opensearch/client/documentation/RestClientDocumentation.java
index b2807d35d230e..42c31864e0578 100644
--- a/client/rest/src/test/java/org/opensearch/client/documentation/RestClientDocumentation.java
+++ b/client/rest/src/test/java/org/opensearch/client/documentation/RestClientDocumentation.java
@@ -89,15 +89,15 @@
* You need to wrap your code between two tags like:
* // tag::example[]
* // end::example[]
- *
+ *
* Where example is your tag name.
- *
+ *
* Then in the documentation, you can extract what is between tag and end tags with
* ["source","java",subs="attributes,callouts,macros"]
* --------------------------------------------------
* include-tagged::{doc-tests}/RestClientDocumentation.java[example]
* --------------------------------------------------
- *
+ *
* Note that this is not a test class as we are only interested in testing that docs snippets compile. We don't want
* to send requests to a node and we don't even have the tools to do it.
*/
diff --git a/client/rest/src/test/java/org/opensearch/client/nio/HeapBufferedAsyncEntityConsumerTests.java b/client/rest/src/test/java/org/opensearch/client/nio/HeapBufferedAsyncEntityConsumerTests.java
new file mode 100644
index 0000000000000..fdfe49ca901c9
--- /dev/null
+++ b/client/rest/src/test/java/org/opensearch/client/nio/HeapBufferedAsyncEntityConsumerTests.java
@@ -0,0 +1,71 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.client.nio;
+
+import org.apache.hc.core5.http.ContentTooLongException;
+import org.opensearch.client.RestClientTestCase;
+import org.junit.After;
+import org.junit.Before;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+
+import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertThrows;
+
+public class HeapBufferedAsyncEntityConsumerTests extends RestClientTestCase {
+ private static final int BUFFER_LIMIT = 100 * 1024 * 1024 /* 100Mb */;
+ private HeapBufferedAsyncEntityConsumer consumer;
+
+ @Before
+ public void setUp() {
+ consumer = new HeapBufferedAsyncEntityConsumer(BUFFER_LIMIT);
+ }
+
+ @After
+ public void tearDown() {
+ consumer.releaseResources();
+ }
+
+ public void testConsumerAllocatesBufferLimit() throws IOException {
+ consumer.consume((ByteBuffer) randomByteBufferOfLength(1000).flip());
+ assertThat(consumer.getBuffer().capacity(), equalTo(1000));
+ }
+
+ public void testConsumerAllocatesEmptyBuffer() throws IOException {
+ consumer.consume((ByteBuffer) ByteBuffer.allocate(0).flip());
+ assertThat(consumer.getBuffer().capacity(), equalTo(0));
+ }
+
+ public void testConsumerExpandsBufferLimits() throws IOException {
+ consumer.consume((ByteBuffer) randomByteBufferOfLength(1000).flip());
+ consumer.consume((ByteBuffer) randomByteBufferOfLength(2000).flip());
+ consumer.consume((ByteBuffer) randomByteBufferOfLength(3000).flip());
+ assertThat(consumer.getBuffer().capacity(), equalTo(6000));
+ }
+
+ public void testConsumerAllocatesLimit() throws IOException {
+ consumer.consume((ByteBuffer) randomByteBufferOfLength(BUFFER_LIMIT).flip());
+ assertThat(consumer.getBuffer().capacity(), equalTo(BUFFER_LIMIT));
+ }
+
+ public void testConsumerFailsToAllocateOverLimit() throws IOException {
+ assertThrows(ContentTooLongException.class, () -> consumer.consume((ByteBuffer) randomByteBufferOfLength(BUFFER_LIMIT + 1).flip()));
+ }
+
+ public void testConsumerFailsToExpandOverLimit() throws IOException {
+ consumer.consume((ByteBuffer) randomByteBufferOfLength(BUFFER_LIMIT).flip());
+ assertThrows(ContentTooLongException.class, () -> consumer.consume((ByteBuffer) randomByteBufferOfLength(1).flip()));
+ }
+
+ private static ByteBuffer randomByteBufferOfLength(int length) {
+ return ByteBuffer.allocate(length).put(randomBytesOfLength(length));
+ }
+}
diff --git a/client/sniffer/build.gradle b/client/sniffer/build.gradle
index f645b2dbbc933..4b50a996d1f9f 100644
--- a/client/sniffer/build.gradle
+++ b/client/sniffer/build.gradle
@@ -37,7 +37,7 @@ java {
base {
group = 'org.opensearch.client'
- archivesBaseName = 'opensearch-rest-client-sniffer'
+ archivesName = 'opensearch-rest-client-sniffer'
}
dependencies {
diff --git a/client/sniffer/licenses/jackson-core-2.15.2.jar.sha1 b/client/sniffer/licenses/jackson-core-2.15.2.jar.sha1
deleted file mode 100644
index ec6781b968eed..0000000000000
--- a/client/sniffer/licenses/jackson-core-2.15.2.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-a6fe1836469a69b3ff66037c324d75fc66ef137c
\ No newline at end of file
diff --git a/client/sniffer/licenses/jackson-core-2.16.2.jar.sha1 b/client/sniffer/licenses/jackson-core-2.16.2.jar.sha1
new file mode 100644
index 0000000000000..68646a1e66ffc
--- /dev/null
+++ b/client/sniffer/licenses/jackson-core-2.16.2.jar.sha1
@@ -0,0 +1 @@
+b4f588bf070f77b604c645a7d60b71eae2e6ea09
\ No newline at end of file
diff --git a/client/sniffer/src/main/java/org/opensearch/client/sniff/OpenSearchNodesSniffer.java b/client/sniffer/src/main/java/org/opensearch/client/sniff/OpenSearchNodesSniffer.java
index e6696c1fc4039..1a87e4f7a5b45 100644
--- a/client/sniffer/src/main/java/org/opensearch/client/sniff/OpenSearchNodesSniffer.java
+++ b/client/sniffer/src/main/java/org/opensearch/client/sniff/OpenSearchNodesSniffer.java
@@ -35,6 +35,7 @@
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hc.core5.http.HttpEntity;
diff --git a/client/sniffer/src/main/java/org/opensearch/client/sniff/Sniffer.java b/client/sniffer/src/main/java/org/opensearch/client/sniff/Sniffer.java
index adddb3bda725c..f609fae4e3c81 100644
--- a/client/sniffer/src/main/java/org/opensearch/client/sniff/Sniffer.java
+++ b/client/sniffer/src/main/java/org/opensearch/client/sniff/Sniffer.java
@@ -305,6 +305,7 @@ public void shutdown() {
}
}
+ @SuppressWarnings("removal")
static class SnifferThreadFactory implements ThreadFactory {
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
diff --git a/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferTests.java b/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferTests.java
index b678fb050e8f8..5520a5acab2d1 100644
--- a/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferTests.java
+++ b/client/sniffer/src/test/java/org/opensearch/client/sniff/OpenSearchNodesSnifferTests.java
@@ -35,18 +35,21 @@
import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import com.carrotsearch.randomizedtesting.generators.RandomStrings;
+
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
+
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
+
+import org.apache.hc.client5.http.classic.methods.HttpGet;
+import org.apache.hc.core5.http.HttpHost;
import org.opensearch.client.Node;
import org.opensearch.client.Response;
import org.opensearch.client.ResponseException;
import org.opensearch.client.RestClient;
import org.opensearch.client.RestClientTestCase;
-import org.apache.hc.client5.http.classic.methods.HttpGet;
-import org.apache.hc.core5.http.HttpHost;
import org.junit.After;
import org.junit.Before;
diff --git a/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferTests.java b/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferTests.java
index 36923281dde6b..3aef4f6360a3e 100644
--- a/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferTests.java
+++ b/client/sniffer/src/test/java/org/opensearch/client/sniff/SnifferTests.java
@@ -32,14 +32,12 @@
package org.opensearch.client.sniff;
+import org.apache.hc.core5.http.HttpHost;
import org.opensearch.client.Node;
import org.opensearch.client.RestClient;
import org.opensearch.client.RestClientTestCase;
import org.opensearch.client.sniff.Sniffer.DefaultScheduler;
import org.opensearch.client.sniff.Sniffer.Scheduler;
-import org.apache.hc.core5.http.HttpHost;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
import java.io.IOException;
import java.util.ArrayList;
@@ -61,6 +59,9 @@
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
+import org.mockito.invocation.InvocationOnMock;
+import org.mockito.stubbing.Answer;
+
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.greaterThan;
diff --git a/client/sniffer/src/test/java/org/opensearch/client/sniff/documentation/SnifferDocumentation.java b/client/sniffer/src/test/java/org/opensearch/client/sniff/documentation/SnifferDocumentation.java
index 8f3e446d8aefb..8a4ca1fb0a136 100644
--- a/client/sniffer/src/test/java/org/opensearch/client/sniff/documentation/SnifferDocumentation.java
+++ b/client/sniffer/src/test/java/org/opensearch/client/sniff/documentation/SnifferDocumentation.java
@@ -35,8 +35,8 @@
import org.apache.hc.core5.http.HttpHost;
import org.opensearch.client.Node;
import org.opensearch.client.RestClient;
-import org.opensearch.client.sniff.OpenSearchNodesSniffer;
import org.opensearch.client.sniff.NodesSniffer;
+import org.opensearch.client.sniff.OpenSearchNodesSniffer;
import org.opensearch.client.sniff.SniffOnFailureListener;
import org.opensearch.client.sniff.Sniffer;
@@ -49,15 +49,15 @@
* You need to wrap your code between two tags like:
* // tag::example[]
* // end::example[]
- *
+ *
* Where example is your tag name.
- *
+ *
* Then in the documentation, you can extract what is between tag and end tags with
* ["source","java",subs="attributes,callouts,macros"]
* --------------------------------------------------
* include-tagged::{doc-tests}/SnifferDocumentation.java[example]
* --------------------------------------------------
- *
+ *
* Note that this is not a test class as we are only interested in testing that docs snippets compile. We don't want
* to send requests to a node and we don't even have the tools to do it.
*/
diff --git a/client/test/build.gradle b/client/test/build.gradle
index f81a009389681..b77865df6decf 100644
--- a/client/test/build.gradle
+++ b/client/test/build.gradle
@@ -30,8 +30,8 @@
apply plugin: 'opensearch.build'
java {
- targetCompatibility = JavaVersion.VERSION_11
- sourceCompatibility = JavaVersion.VERSION_11
+ targetCompatibility = JavaVersion.VERSION_1_8
+ sourceCompatibility = JavaVersion.VERSION_1_8
}
base {
@@ -69,3 +69,10 @@ dependenciesInfo.enabled = false
//we aren't releasing this jar
thirdPartyAudit.enabled = false
test.enabled = false
+
+tasks.withType(JavaCompile) {
+ // Suppressing '[options] target value 8 is obsolete and will be removed in a future release'
+ configure(options) {
+ options.compilerArgs << '-Xlint:-options'
+ }
+}
diff --git a/distribution/archives/build.gradle b/distribution/archives/build.gradle
index e7137127053e2..161b8008525b4 100644
--- a/distribution/archives/build.gradle
+++ b/distribution/archives/build.gradle
@@ -28,9 +28,11 @@
* under the License.
*/
+import org.opensearch.gradle.JavaPackageType
+
apply plugin: 'opensearch.internal-distribution-archive-setup'
-CopySpec archiveFiles(CopySpec modulesFiles, String distributionType, String platform, String architecture, boolean jdk) {
+CopySpec archiveFiles(CopySpec modulesFiles, String distributionType, String platform, String architecture, JavaPackageType java) {
return copySpec {
into("opensearch-${version}") {
into('lib') {
@@ -39,19 +41,23 @@ CopySpec archiveFiles(CopySpec modulesFiles, String distributionType, String pla
into('config') {
dirMode 0750
fileMode 0660
- with configFiles(distributionType, jdk)
+ with configFiles(distributionType, java)
from {
dirMode 0750
jvmOptionsDir.getParent()
}
}
into('bin') {
- with binFiles(distributionType, jdk)
+ with binFiles(distributionType, java)
}
- if (jdk) {
+ if (java == JavaPackageType.JDK) {
into("darwin".equals(platform) ? 'jdk.app' : 'jdk') {
with jdkFiles(project, platform, architecture)
}
+ } else if (java == JavaPackageType.JRE) {
+ into("darwin".equals(platform) ? 'jre.app' : 'jre') {
+ with jreFiles(project, platform, architecture)
+ }
}
into('') {
from {
@@ -73,7 +79,7 @@ CopySpec archiveFiles(CopySpec modulesFiles, String distributionType, String pla
rename { 'LICENSE.txt' }
}
- with noticeFile(jdk)
+ with noticeFile(java)
into('modules') {
with modulesFiles
}
@@ -84,77 +90,84 @@ CopySpec archiveFiles(CopySpec modulesFiles, String distributionType, String pla
distribution_archives {
integTestZip {
content {
- archiveFiles(transportModulesFiles, 'zip', null, 'x64', false)
+ archiveFiles(transportModulesFiles, 'zip', null, 'x64', JavaPackageType.NONE)
}
}
darwinTar {
archiveClassifier = 'darwin-x64'
content {
- archiveFiles(modulesFiles('darwin-x64'), 'tar', 'darwin', 'x64', true)
+ archiveFiles(modulesFiles('darwin-x64'), 'tar', 'darwin', 'x64', JavaPackageType.JDK)
}
}
darwinArm64Tar {
archiveClassifier = 'darwin-arm64'
content {
- archiveFiles(modulesFiles('darwin-arm64'), 'tar', 'darwin', 'arm64', true)
+ archiveFiles(modulesFiles('darwin-arm64'), 'tar', 'darwin', 'arm64', JavaPackageType.JDK)
}
}
noJdkDarwinTar {
archiveClassifier = 'no-jdk-darwin-x64'
content {
- archiveFiles(modulesFiles('darwin-x64'), 'tar', 'darwin', 'x64', false)
+ archiveFiles(modulesFiles('darwin-x64'), 'tar', 'darwin', 'x64', JavaPackageType.NONE)
}
}
noJdkDarwinArm64Tar {
archiveClassifier = 'no-jdk-darwin-arm64'
content {
- archiveFiles(modulesFiles('darwin-arm64'), 'tar', 'darwin', 'arm64', false)
+ archiveFiles(modulesFiles('darwin-arm64'), 'tar', 'darwin', 'arm64', JavaPackageType.NONE)
}
}
freebsdTar {
archiveClassifier = 'freebsd-x64'
content {
- archiveFiles(modulesFiles('freebsd-x64'), 'tar', 'freebsd', 'x64', false)
+ archiveFiles(modulesFiles('freebsd-x64'), 'tar', 'freebsd', 'x64', JavaPackageType.NONE)
}
}
noJdkFreebsdTar {
archiveClassifier = 'no-jdk-freebsd-x64'
content {
- archiveFiles(modulesFiles('freebsd-x64'), 'tar', 'freebsd', 'x64', false)
+ archiveFiles(modulesFiles('freebsd-x64'), 'tar', 'freebsd', 'x64', JavaPackageType.NONE)
}
}
linuxArm64Tar {
archiveClassifier = 'linux-arm64'
content {
- archiveFiles(modulesFiles('linux-arm64'), 'tar', 'linux', 'arm64', true)
+ archiveFiles(modulesFiles('linux-arm64'), 'tar', 'linux', 'arm64', JavaPackageType.JDK)
}
}
noJdkLinuxArm64Tar {
archiveClassifier = 'no-jdk-linux-arm64'
content {
- archiveFiles(modulesFiles('linux-arm64'), 'tar', 'linux', 'arm64', false)
+ archiveFiles(modulesFiles('linux-arm64'), 'tar', 'linux', 'arm64', JavaPackageType.NONE)
}
}
linuxTar {
archiveClassifier = 'linux-x64'
content {
- archiveFiles(modulesFiles('linux-x64'), 'tar', 'linux', 'x64', true)
+ archiveFiles(modulesFiles('linux-x64'), 'tar', 'linux', 'x64', JavaPackageType.JDK)
}
}
noJdkLinuxTar {
archiveClassifier = 'no-jdk-linux-x64'
content {
- archiveFiles(modulesFiles('linux-x64'), 'tar', 'linux', 'x64', false)
+ archiveFiles(modulesFiles('linux-x64'), 'tar', 'linux', 'x64', JavaPackageType.NONE)
+ }
+ }
+
+ jreLinuxTar {
+ archiveClassifier = 'jre-linux-x64'
+ content {
+ archiveFiles(modulesFiles('linux-x64'), 'tar', 'linux', 'x64', JavaPackageType.JRE)
}
}
@@ -163,7 +176,7 @@ distribution_archives {
linuxS390xTar {
archiveClassifier = 'linux-s390x'
content {
- archiveFiles(modulesFiles('linux-s390x'), 'tar', 'linux', 's390x', false)
+ archiveFiles(modulesFiles('linux-s390x'), 'tar', 'linux', 's390x', JavaPackageType.NONE)
}
}
@@ -171,28 +184,28 @@ distribution_archives {
linuxPpc64leTar {
archiveClassifier = 'linux-ppc64le'
content {
- archiveFiles(modulesFiles('linux-ppc64le'), 'tar', 'linux', 'ppc64le', true)
+ archiveFiles(modulesFiles('linux-ppc64le'), 'tar', 'linux', 'ppc64le', JavaPackageType.JDK)
}
}
noJdkLinuxPpc64leTar {
archiveClassifier = 'no-jdk-linux-ppc64le'
content {
- archiveFiles(modulesFiles('linux-ppc64le'), 'tar', 'linux', 'ppc64le', false)
+ archiveFiles(modulesFiles('linux-ppc64le'), 'tar', 'linux', 'ppc64le', JavaPackageType.NONE)
}
}
windowsZip {
archiveClassifier = 'windows-x64'
content {
- archiveFiles(modulesFiles('windows-x64'), 'zip', 'windows', 'x64', true)
+ archiveFiles(modulesFiles('windows-x64'), 'zip', 'windows', 'x64', JavaPackageType.JDK)
}
}
noJdkWindowsZip {
archiveClassifier = 'no-jdk-windows-x64'
content {
- archiveFiles(modulesFiles('windows-x64'), 'zip', 'windows', 'x64', false)
+ archiveFiles(modulesFiles('windows-x64'), 'zip', 'windows', 'x64', JavaPackageType.NONE)
}
}
}
diff --git a/distribution/archives/darwin-arm64-tar/build.gradle b/distribution/archives/darwin-arm64-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/darwin-arm64-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/darwin-tar/build.gradle b/distribution/archives/darwin-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/darwin-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/freebsd-tar/build.gradle b/distribution/archives/freebsd-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/freebsd-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/integ-test-zip/build.gradle b/distribution/archives/integ-test-zip/build.gradle
index 9418223b0a44d..ffaea5e8ca771 100644
--- a/distribution/archives/integ-test-zip/build.gradle
+++ b/distribution/archives/integ-test-zip/build.gradle
@@ -38,7 +38,7 @@ apply plugin: 'com.netflix.nebula.maven-publish'
base {
group = "org.opensearch.distribution.integ-test-zip"
- archivesBaseName = "opensearch"
+ archivesName = "opensearch"
}
integTest {
diff --git a/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/JsonLogsFormatAndParseIT.java b/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/JsonLogsFormatAndParseIT.java
index 88f667549f3e8..faef1441d0a02 100644
--- a/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/JsonLogsFormatAndParseIT.java
+++ b/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/JsonLogsFormatAndParseIT.java
@@ -51,6 +51,7 @@ protected Matcher nodeNameMatcher() {
return is("integTest-0");
}
+ @SuppressWarnings("removal")
@Override
protected BufferedReader openReader(Path logFile) {
assumeFalse("Skipping test because it is being run against an external cluster.",
diff --git a/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/NodeRestUsageIT.java b/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/NodeRestUsageIT.java
index d397a1c967ad0..59df4122713d5 100644
--- a/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/NodeRestUsageIT.java
+++ b/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/NodeRestUsageIT.java
@@ -35,8 +35,8 @@
import org.opensearch.client.Request;
import org.opensearch.client.Response;
import org.opensearch.client.ResponseException;
-import org.opensearch.common.Strings;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.common.Strings;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.search.aggregations.AggregationBuilders;
import org.opensearch.search.builder.SearchSourceBuilder;
@@ -172,8 +172,8 @@ public void testAggregationUsage() throws IOException {
.aggregation(AggregationBuilders.terms("str_terms").field("str.keyword"))
.aggregation(AggregationBuilders.terms("num_terms").field("num"))
.aggregation(AggregationBuilders.avg("num_avg").field("num"));
- searchRequest.setJsonEntity(Strings.toString(XContentType.JSON, searchSource));
- searchRequest.setJsonEntity(Strings.toString(XContentType.JSON, searchSource));
+ searchRequest.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, searchSource));
+ searchRequest.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, searchSource));
client().performRequest(searchRequest);
searchRequest = new Request("GET", "/test/_search");
@@ -182,8 +182,8 @@ public void testAggregationUsage() throws IOException {
.aggregation(AggregationBuilders.avg("num1").field("num"))
.aggregation(AggregationBuilders.avg("num2").field("num"))
.aggregation(AggregationBuilders.terms("foo").field("foo.keyword"));
- String r = Strings.toString(XContentType.JSON, searchSource);
- searchRequest.setJsonEntity(Strings.toString(XContentType.JSON, searchSource));
+ String r = Strings.toString(MediaTypeRegistry.JSON, searchSource);
+ searchRequest.setJsonEntity(Strings.toString(MediaTypeRegistry.JSON, searchSource));
client().performRequest(searchRequest);
Response response = client().performRequest(new Request("GET", "_nodes/usage"));
diff --git a/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/WaitForRefreshAndCloseIT.java b/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/WaitForRefreshAndCloseIT.java
index 07576dacffb03..b98941874ec6c 100644
--- a/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/WaitForRefreshAndCloseIT.java
+++ b/distribution/archives/integ-test-zip/src/test/java/org/opensearch/test/rest/WaitForRefreshAndCloseIT.java
@@ -32,7 +32,7 @@
package org.opensearch.test.rest;
-import org.opensearch.action.ActionFuture;
+import org.opensearch.common.action.ActionFuture;
import org.opensearch.action.support.PlainActionFuture;
import org.opensearch.client.Request;
import org.opensearch.client.Response;
diff --git a/distribution/archives/jre-linux-tar/build.gradle b/distribution/archives/jre-linux-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/jre-linux-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/linux-arm64-tar/build.gradle b/distribution/archives/linux-arm64-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/linux-arm64-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/linux-ppc64le-tar/build.gradle b/distribution/archives/linux-ppc64le-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/linux-ppc64le-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/linux-s390x-tar/build.gradle b/distribution/archives/linux-s390x-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/linux-s390x-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/linux-tar/build.gradle b/distribution/archives/linux-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/linux-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/no-jdk-darwin-arm64-tar/build.gradle b/distribution/archives/no-jdk-darwin-arm64-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/no-jdk-darwin-arm64-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/no-jdk-darwin-tar/build.gradle b/distribution/archives/no-jdk-darwin-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/no-jdk-darwin-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/no-jdk-freebsd-tar/build.gradle b/distribution/archives/no-jdk-freebsd-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/no-jdk-freebsd-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/no-jdk-linux-arm64-tar/build.gradle b/distribution/archives/no-jdk-linux-arm64-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/no-jdk-linux-arm64-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/no-jdk-linux-ppc64le-tar/build.gradle b/distribution/archives/no-jdk-linux-ppc64le-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/no-jdk-linux-ppc64le-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/no-jdk-linux-tar/build.gradle b/distribution/archives/no-jdk-linux-tar/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/no-jdk-linux-tar/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/no-jdk-windows-zip/build.gradle b/distribution/archives/no-jdk-windows-zip/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/no-jdk-windows-zip/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/archives/windows-zip/build.gradle b/distribution/archives/windows-zip/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/archives/windows-zip/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/build.gradle b/distribution/build.gradle
index 2378ed833ead7..35ca84ca66dba 100644
--- a/distribution/build.gradle
+++ b/distribution/build.gradle
@@ -36,6 +36,7 @@ import org.opensearch.gradle.MavenFilteringHack
import org.opensearch.gradle.NoticeTask
import org.opensearch.gradle.VersionProperties
import org.opensearch.gradle.info.BuildParams
+import org.opensearch.gradle.JavaPackageType
import java.nio.file.Files
import java.nio.file.Path
@@ -275,13 +276,14 @@ project(':test:external-modules').subprojects.each { Project testModule ->
configure(subprojects.findAll { ['archives', 'packages'].contains(it.name) }) {
apply plugin: 'opensearch.jdk-download'
+ apply plugin: 'opensearch.jre-download'
apply plugin: 'opensearch.repositories'
// Setup all required JDKs
project.jdks {
['darwin', 'linux', 'windows'].each { platform ->
(platform == 'linux' || platform == 'darwin' ? ['x64', 'aarch64', 's390x', 'ppc64le'] : ['x64']).each { architecture ->
- "bundled_${platform}_${architecture}" {
+ "bundled_jdk_${platform}_${architecture}" {
it.platform = platform
it.version = VersionProperties.getBundledJdk(platform, architecture)
it.vendor = VersionProperties.bundledJdkVendor
@@ -291,6 +293,20 @@ configure(subprojects.findAll { ['archives', 'packages'].contains(it.name) }) {
}
}
+ // Setup all required JREs
+ project.jres {
+ ['darwin', 'linux', 'windows'].each { platform ->
+ (platform == 'linux' || platform == 'darwin' ? ['x64', 'aarch64', 's390x', 'ppc64le'] : ['x64']).each { architecture ->
+ "bundled_jre_${platform}_${architecture}" {
+ it.platform = platform
+ it.version = VersionProperties.getBundledJre(platform, architecture)
+ it.vendor = VersionProperties.bundledJdkVendor
+ it.architecture = architecture
+ }
+ }
+ }
+ }
+
// TODO: the map needs to be an input of the tasks, so that when it changes, the task will re-run...
/*****************************************************************************
* Properties to expand when copying packaging files *
@@ -377,20 +393,20 @@ configure(subprojects.findAll { ['archives', 'packages'].contains(it.name) }) {
from buildTransportModulesTaskProvider
}
- configFiles = { distributionType, jdk ->
+ configFiles = { distributionType, java ->
copySpec {
with copySpec {
// main config files, processed with distribution specific substitutions
from '../src/config'
exclude 'log4j2.properties' // this is handled separately below
- MavenFilteringHack.filter(it, expansionsForDistribution(distributionType, jdk))
+ MavenFilteringHack.filter(it, expansionsForDistribution(distributionType, java))
}
from project(':distribution').buildLog4jConfig
from project(':distribution').buildConfig
}
}
- binFiles = { distributionType, jdk ->
+ binFiles = { distributionType, java ->
copySpec {
// non-windows files, for all distributions
with copySpec {
@@ -398,7 +414,7 @@ configure(subprojects.findAll { ['archives', 'packages'].contains(it.name) }) {
exclude '*.exe'
exclude '*.bat'
eachFile { it.setMode(0755) }
- MavenFilteringHack.filter(it, expansionsForDistribution(distributionType, jdk))
+ MavenFilteringHack.filter(it, expansionsForDistribution(distributionType, java))
}
// windows files, only for zip
if (distributionType == 'zip') {
@@ -406,7 +422,7 @@ configure(subprojects.findAll { ['archives', 'packages'].contains(it.name) }) {
from '../src/bin'
include '*.bat'
filter(FixCrLfFilter, eol: FixCrLfFilter.CrLf.newInstance('crlf'))
- MavenFilteringHack.filter(it, expansionsForDistribution(distributionType, jdk))
+ MavenFilteringHack.filter(it, expansionsForDistribution(distributionType, java))
}
with copySpec {
from '../src/bin'
@@ -424,12 +440,12 @@ configure(subprojects.findAll { ['archives', 'packages'].contains(it.name) }) {
}
}
- noticeFile = { jdk ->
+ noticeFile = { java ->
copySpec {
if (project.name == 'integ-test-zip') {
from buildServerNoticeTaskProvider
} else {
- if (jdk) {
+ if (java != JavaPackageType.NONE) {
from buildNoticeTaskProvider
} else {
from buildNoJdkNoticeTaskProvider
@@ -446,7 +462,7 @@ configure(subprojects.findAll { ['archives', 'packages'].contains(it.name) }) {
if ("arm64".equals(architecture)) {
architecture = "aarch64"
}
- from project.jdks."bundled_${platform}_${architecture}"
+ from project.jdks."bundled_jdk_${platform}_${architecture}"
exclude "demo/**"
/*
* The Contents/MacOS directory interferes with notarization, and is unused by our distribution, so we exclude
@@ -465,6 +481,31 @@ configure(subprojects.findAll { ['archives', 'packages'].contains(it.name) }) {
}
}
}
+
+ jreFiles = { Project project, String platform, String architecture ->
+ return copySpec {
+ /*
+ * Jdk uses aarch64 from ARM. Translating from arm64 to aarch64 which Jdk understands.
+ */
+ if ("arm64".equals(architecture)) {
+ architecture = "aarch64"
+ }
+ from project.jres."bundled_jre_${platform}_${architecture}"
+ exclude "demo/**"
+ /*
+ * The Contents/MacOS directory interferes with notarization, and is unused by our distribution, so we exclude
+ * it from the build.
+ */
+ if ("darwin".equals(platform)) {
+ exclude "Contents/MacOS"
+ }
+ eachFile { FileCopyDetails details ->
+ if (details.relativePath.segments[-2] == 'bin' || details.relativePath.segments[-1] == 'jspawnhelper') {
+ details.mode = 0755
+ }
+ }
+ }
+ }
}
}
@@ -583,7 +624,7 @@ subprojects {
],
'opensearch.bundled_jdk': [
- 'def': jdk ? 'true' : 'false'
+ 'def': jdk != JavaPackageType.NONE ? true : false
],
'license.name': [
diff --git a/distribution/docker/docker-arm64-build-context/build.gradle b/distribution/docker/docker-arm64-build-context/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/docker/docker-arm64-build-context/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/docker/docker-arm64-export/build.gradle b/distribution/docker/docker-arm64-export/build.gradle
new file mode 100644
index 0000000000000..62f3dc68b0c8e
--- /dev/null
+++ b/distribution/docker/docker-arm64-export/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// export is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/docker/docker-export/build.gradle b/distribution/docker/docker-export/build.gradle
index 3506c4e39c234..62f3dc68b0c8e 100644
--- a/distribution/docker/docker-export/build.gradle
+++ b/distribution/docker/docker-export/build.gradle
@@ -11,3 +11,5 @@
// This file is intentionally blank. All configuration of the
// export is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/docker/docker-ppc64le-export/build.gradle b/distribution/docker/docker-ppc64le-export/build.gradle
index 820a0cdf69dfc..ae7def32c4d6c 100644
--- a/distribution/docker/docker-ppc64le-export/build.gradle
+++ b/distribution/docker/docker-ppc64le-export/build.gradle
@@ -10,3 +10,5 @@
// This file is intentionally blank. All configuration of the
// export is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/docker/docker-s390x-export/build.gradle b/distribution/docker/docker-s390x-export/build.gradle
new file mode 100644
index 0000000000000..62f3dc68b0c8e
--- /dev/null
+++ b/distribution/docker/docker-s390x-export/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// export is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/docker/src/docker/config/log4j2.properties b/distribution/docker/src/docker/config/log4j2.properties
index 761478a9fdc6e..8edd6a7354a16 100644
--- a/distribution/docker/src/docker/config/log4j2.properties
+++ b/distribution/docker/src/docker/config/log4j2.properties
@@ -34,6 +34,16 @@ logger.deprecation.appenderRef.deprecation_rolling.ref = deprecation_rolling
logger.deprecation.appenderRef.header_warning.ref = header_warning
logger.deprecation.additivity = false
+appender.search_request_slowlog_json_appender.type = Console
+appender.search_request_slowlog_json_appender.name = search_request_slowlog_json_appender
+appender.search_request_slowlog_json_appender.layout.type = OpenSearchJsonLayout
+appender.search_request_slowlog_json_appender.layout.type_name = search_request_slowlog
+
+logger.search_request_slowlog_logger.name = cluster.search.request.slowlog
+logger.search_request_slowlog_logger.level = trace
+logger.search_request_slowlog_logger.appenderRef.search_request_slowlog_json_appender.ref = search_request_slowlog_json_appender
+logger.search_request_slowlog_logger.additivity = false
+
appender.index_search_slowlog_rolling.type = Console
appender.index_search_slowlog_rolling.name = index_search_slowlog_rolling
appender.index_search_slowlog_rolling.layout.type = OpenSearchJsonLayout
diff --git a/distribution/packages/arm64-deb/build.gradle b/distribution/packages/arm64-deb/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/arm64-deb/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/arm64-no-jdk-deb/build.gradle b/distribution/packages/arm64-no-jdk-deb/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/arm64-no-jdk-deb/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/arm64-no-jdk-rpm/build.gradle b/distribution/packages/arm64-no-jdk-rpm/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/arm64-no-jdk-rpm/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/arm64-rpm/build.gradle b/distribution/packages/arm64-rpm/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/arm64-rpm/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/build.gradle b/distribution/packages/build.gradle
index 7914fcc172ef4..4e85d19986e43 100644
--- a/distribution/packages/build.gradle
+++ b/distribution/packages/build.gradle
@@ -63,7 +63,7 @@ import java.util.regex.Pattern
*/
plugins {
- id "com.netflix.nebula.ospackage-base" version "11.4.0"
+ id "com.netflix.nebula.ospackage-base" version "11.8.1"
}
void addProcessFilesTask(String type, boolean jdk) {
@@ -213,7 +213,7 @@ Closure commonPackageConfig(String type, boolean jdk, String architecture) {
configurationFile '/etc/opensearch/jvm.options'
configurationFile '/etc/opensearch/log4j2.properties'
from("${packagingFiles}") {
- dirMode 02750
+ dirMode 0750
into('/etc')
permissionGroup 'opensearch'
includeEmptyDirs true
@@ -223,7 +223,7 @@ Closure commonPackageConfig(String type, boolean jdk, String architecture) {
}
from("${packagingFiles}/etc/opensearch") {
into('/etc/opensearch')
- dirMode 02750
+ dirMode 0750
fileMode 0660
permissionGroup 'opensearch'
includeEmptyDirs true
@@ -281,8 +281,8 @@ Closure commonPackageConfig(String type, boolean jdk, String architecture) {
dirMode mode
}
}
- copyEmptyDir('/var/log/opensearch', 'opensearch', 'opensearch', 02750)
- copyEmptyDir('/var/lib/opensearch', 'opensearch', 'opensearch', 02750)
+ copyEmptyDir('/var/log/opensearch', 'opensearch', 'opensearch', 0750)
+ copyEmptyDir('/var/lib/opensearch', 'opensearch', 'opensearch', 0750)
copyEmptyDir('/usr/share/opensearch/plugins', 'root', 'root', 0755)
into '/usr/share/opensearch'
diff --git a/distribution/packages/deb/build.gradle b/distribution/packages/deb/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/deb/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/no-jdk-arm64-deb/build.gradle b/distribution/packages/no-jdk-arm64-deb/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/no-jdk-arm64-deb/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/no-jdk-arm64-rpm/build.gradle b/distribution/packages/no-jdk-arm64-rpm/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/no-jdk-arm64-rpm/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/no-jdk-deb/build.gradle b/distribution/packages/no-jdk-deb/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/no-jdk-deb/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/no-jdk-rpm/build.gradle b/distribution/packages/no-jdk-rpm/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/no-jdk-rpm/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/rpm/build.gradle b/distribution/packages/rpm/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/distribution/packages/rpm/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/distribution/packages/src/deb/lintian/opensearch b/distribution/packages/src/deb/lintian/opensearch
index 854b23131ecbc..e6db8e8c6b322 100644
--- a/distribution/packages/src/deb/lintian/opensearch
+++ b/distribution/packages/src/deb/lintian/opensearch
@@ -15,11 +15,11 @@ missing-dep-on-jarwrapper
# we prefer to not make our config and log files world readable
non-standard-file-perm etc/default/opensearch 0660 != 0644
-non-standard-dir-perm etc/opensearch/ 2750 != 0755
-non-standard-dir-perm etc/opensearch/jvm.options.d/ 2750 != 0755
+non-standard-dir-perm etc/opensearch/ 0750 != 0755
+non-standard-dir-perm etc/opensearch/jvm.options.d/ 0750 != 0755
non-standard-file-perm etc/opensearch/*
-non-standard-dir-perm var/lib/opensearch/ 2750 != 0755
-non-standard-dir-perm var/log/opensearch/ 2750 != 0755
+non-standard-dir-perm var/lib/opensearch/ 0750 != 0755
+non-standard-dir-perm var/log/opensearch/ 0750 != 0755
executable-is-not-world-readable etc/init.d/opensearch 0750
non-standard-file-permissions-for-etc-init.d-script etc/init.d/opensearch 0750 != 0755
diff --git a/distribution/src/bin/opensearch-env b/distribution/src/bin/opensearch-env
index f94824576b122..cd7a0b2b4520b 100644
--- a/distribution/src/bin/opensearch-env
+++ b/distribution/src/bin/opensearch-env
@@ -46,7 +46,7 @@ fi
# now set the classpath
OPENSEARCH_CLASSPATH="$OPENSEARCH_HOME/lib/*"
-# now set the path to java: OPENSEARCH_JAVA_HOME -> JAVA_HOME -> bundled JDK
+# now set the path to java: OPENSEARCH_JAVA_HOME -> JAVA_HOME -> bundled JRE -> bundled JDK
if [ ! -z "$OPENSEARCH_JAVA_HOME" ]; then
JAVA="$OPENSEARCH_JAVA_HOME/bin/java"
JAVA_TYPE="OPENSEARCH_JAVA_HOME"
@@ -57,13 +57,18 @@ else
if [ $OS = "darwin" ]; then
# macOS bundled Java
JAVA="$OPENSEARCH_HOME/jdk.app/Contents/Home/bin/java"
+ JAVA_TYPE="bundled jdk"
elif [ $OS = "freebsd" ]; then
# using FreeBSD default java from ports if JAVA_HOME is not set
JAVA="/usr/local/bin/java"
+ JAVA_TYPE="bundled jdk"
+ elif [ -d "$OPENSEARCH_HOME/jre" ]; then
+ JAVA="$OPENSEARCH_HOME/jre/bin/java"
+ JAVA_TYPE="bundled jre"
else
JAVA="$OPENSEARCH_HOME/jdk/bin/java"
+ JAVA_TYPE="bundled jdk"
fi
- JAVA_TYPE="bundled jdk"
fi
if [ ! -x "$JAVA" ]; then
diff --git a/distribution/src/config/jvm.options b/distribution/src/config/jvm.options
index 952110c6c0289..f0ac98faffda9 100644
--- a/distribution/src/config/jvm.options
+++ b/distribution/src/config/jvm.options
@@ -38,12 +38,12 @@
8-10:-XX:+UseCMSInitiatingOccupancyOnly
## G1GC Configuration
-# NOTE: G1 GC is only supported on JDK version 10 or later
-# to use G1GC, uncomment the next two lines and update the version on the
-# following three lines to your version of the JDK
-# 10:-XX:-UseConcMarkSweepGC
-# 10:-XX:-UseCMSInitiatingOccupancyOnly
+# NOTE: G1GC is the default GC for all JDKs 11 and newer
11-:-XX:+UseG1GC
+# See https://github.com/elastic/elasticsearch/pull/46169 for the history
+# behind these settings, but the tl;dr is that default values can lead
+# to situations where heap usage grows enough to trigger a circuit breaker
+# before GC kicks in.
11-:-XX:G1ReservePercent=25
11-:-XX:InitiatingHeapOccupancyPercent=30
@@ -81,7 +81,7 @@ ${error.file}
# JDK 20+ Incubating Vector Module for SIMD optimizations;
# disabling may reduce performance on vector optimized lucene
-20:--add-modules=jdk.incubator.vector
+20-:--add-modules=jdk.incubator.vector
# HDFS ForkJoinPool.common() support by SecurityManager
-Djava.util.concurrent.ForkJoinPool.common.threadFactory=org.opensearch.secure_sm.SecuredForkJoinWorkerThreadFactory
diff --git a/distribution/src/config/log4j2.properties b/distribution/src/config/log4j2.properties
index bb27aaf2e22e6..d040afae82e53 100644
--- a/distribution/src/config/log4j2.properties
+++ b/distribution/src/config/log4j2.properties
@@ -113,6 +113,47 @@ logger.deprecation.appenderRef.deprecation_rolling_old.ref = deprecation_rolling
logger.deprecation.appenderRef.header_warning.ref = header_warning
logger.deprecation.additivity = false
+######## Search Request Slowlog JSON ####################
+appender.search_request_slowlog_json_appender.type = RollingFile
+appender.search_request_slowlog_json_appender.name = search_request_slowlog_json_appender
+appender.search_request_slowlog_json_appender.fileName = ${sys:opensearch.logs.base_path}${sys:file.separator}${sys:opensearch.logs\
+ .cluster_name}_index_search_slowlog.json
+appender.search_request_slowlog_json_appender.filePermissions = rw-r-----
+appender.search_request_slowlog_json_appender.layout.type = OpenSearchJsonLayout
+appender.search_request_slowlog_json_appender.layout.type_name = search_request_slowlog
+appender.search_request_slowlog_json_appender.layout.opensearchmessagefields=message,took,took_millis,phase_took,total_hits,search_type,shards,source,id
+
+appender.search_request_slowlog_json_appender.filePattern = ${sys:opensearch.logs.base_path}${sys:file.separator}${sys:opensearch.logs\
+ .cluster_name}_index_search_slowlog-%i.json.gz
+appender.search_request_slowlog_json_appender.policies.type = Policies
+appender.search_request_slowlog_json_appender.policies.size.type = SizeBasedTriggeringPolicy
+appender.search_request_slowlog_json_appender.policies.size.size = 1GB
+appender.search_request_slowlog_json_appender.strategy.type = DefaultRolloverStrategy
+appender.search_request_slowlog_json_appender.strategy.max = 4
+#################################################
+######## Search Request Slowlog Log File - old style pattern ####
+appender.search_request_slowlog_log_appender.type = RollingFile
+appender.search_request_slowlog_log_appender.name = search_request_slowlog_log_appender
+appender.search_request_slowlog_log_appender.fileName = ${sys:opensearch.logs.base_path}${sys:file.separator}${sys:opensearch.logs.cluster_name}\
+ _index_search_slowlog.log
+appender.search_request_slowlog_log_appender.filePermissions = rw-r-----
+appender.search_request_slowlog_log_appender.layout.type = PatternLayout
+appender.search_request_slowlog_log_appender.layout.pattern = [%d{ISO8601}][%-5p][%c{1.}] [%node_name]%marker %m%n
+
+appender.search_request_slowlog_log_appender.filePattern = ${sys:opensearch.logs.base_path}${sys:file.separator}${sys:opensearch.logs.cluster_name}\
+ _index_search_slowlog-%i.log.gz
+appender.search_request_slowlog_log_appender.policies.type = Policies
+appender.search_request_slowlog_log_appender.policies.size.type = SizeBasedTriggeringPolicy
+appender.search_request_slowlog_log_appender.policies.size.size = 1GB
+appender.search_request_slowlog_log_appender.strategy.type = DefaultRolloverStrategy
+appender.search_request_slowlog_log_appender.strategy.max = 4
+#################################################
+logger.search_request_slowlog_logger.name = cluster.search.request.slowlog
+logger.search_request_slowlog_logger.level = trace
+logger.search_request_slowlog_logger.appenderRef.search_request_slowlog_json_appender.ref = search_request_slowlog_json_appender
+logger.search_request_slowlog_logger.appenderRef.search_request_slowlog_log_appender.ref = search_request_slowlog_log_appender
+logger.search_request_slowlog_logger.additivity = false
+
######## Search slowlog JSON ####################
appender.index_search_slowlog_rolling.type = RollingFile
appender.index_search_slowlog_rolling.name = index_search_slowlog_rolling
diff --git a/distribution/src/config/opensearch.yml b/distribution/src/config/opensearch.yml
index 3c4fe822005e0..10bab9b3fce92 100644
--- a/distribution/src/config/opensearch.yml
+++ b/distribution/src/config/opensearch.yml
@@ -92,24 +92,16 @@ ${path.logs}
# cluster.remote_store.enabled: true
#
# Repository to use for segment upload while enforcing remote store for an index
-# cluster.remote_store.segment.repository: my-repo-1
+# node.attr.remote_store.segment.repository: my-repo-1
#
# Repository to use for translog upload while enforcing remote store for an index
-# cluster.remote_store.translog.repository: my-repo-1
+# node.attr.remote_store.translog.repository: my-repo-1
#
# ---------------------------------- Experimental Features -----------------------------------
-#
# Gates the visibility of the experimental segment replication features until they are production ready.
#
#opensearch.experimental.feature.segment_replication_experimental.enabled: false
#
-#
-# Gates the visibility of the index setting that allows persisting data to remote store along with local disk.
-# Once the feature is ready for production release, this feature flag can be removed.
-#
-#opensearch.experimental.feature.remote_store.enabled: false
-#
-#
# Gates the functionality of a new parameter to the snapshot restore API
# that allows for creation of a new index type that searches a snapshot
# directly in a remote repository without restoring all index data to disk
@@ -125,7 +117,11 @@ ${path.logs}
#opensearch.experimental.feature.extensions.enabled: false
#
#
-# Gates the concurrent segment search feature. This feature enables concurrent segment search in a separate
-# index searcher threadpool.
+# Gates the optimization of datetime formatters caching along with change in default datetime formatter
+# Once there is no observed impact on performance, this feature flag can be removed.
+#
+#opensearch.experimental.optimization.datetime_formatter_caching.enabled: false
+#
+# Gates the functionality of enabling Opensearch to use pluggable caches with respective store names via setting.
#
-#opensearch.experimental.feature.concurrent_segment_search.enabled: false
+#opensearch.experimental.feature.pluggable.caching.enabled: false
diff --git a/distribution/tools/keystore-cli/src/main/java/org/opensearch/common/settings/CreateKeyStoreCommand.java b/distribution/tools/keystore-cli/src/main/java/org/opensearch/common/settings/CreateKeyStoreCommand.java
index 05c1cfdc2fb9a..a4ab98ce730ee 100644
--- a/distribution/tools/keystore-cli/src/main/java/org/opensearch/common/settings/CreateKeyStoreCommand.java
+++ b/distribution/tools/keystore-cli/src/main/java/org/opensearch/common/settings/CreateKeyStoreCommand.java
@@ -32,10 +32,6 @@
package org.opensearch.common.settings;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Arrays;
-
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.opensearch.cli.ExitCodes;
@@ -45,6 +41,10 @@
import org.opensearch.core.common.settings.SecureString;
import org.opensearch.env.Environment;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+
/**
* A sub-command for the keystore cli to create a new keystore.
*/
diff --git a/distribution/tools/keystore-cli/src/main/java/org/opensearch/common/settings/ListKeyStoreCommand.java b/distribution/tools/keystore-cli/src/main/java/org/opensearch/common/settings/ListKeyStoreCommand.java
index 32f03ec3822de..379b61efc5d32 100644
--- a/distribution/tools/keystore-cli/src/main/java/org/opensearch/common/settings/ListKeyStoreCommand.java
+++ b/distribution/tools/keystore-cli/src/main/java/org/opensearch/common/settings/ListKeyStoreCommand.java
@@ -32,14 +32,14 @@
package org.opensearch.common.settings;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
import joptsimple.OptionSet;
import org.opensearch.cli.Terminal;
import org.opensearch.env.Environment;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
/**
* A subcommand for the keystore cli to list all settings in the keystore.
*/
diff --git a/distribution/tools/keystore-cli/src/test/java/org/opensearch/bootstrap/BootstrapTests.java b/distribution/tools/keystore-cli/src/test/java/org/opensearch/bootstrap/BootstrapTests.java
index d06ffb650dc82..e9219de218aef 100644
--- a/distribution/tools/keystore-cli/src/test/java/org/opensearch/bootstrap/BootstrapTests.java
+++ b/distribution/tools/keystore-cli/src/test/java/org/opensearch/bootstrap/BootstrapTests.java
@@ -31,12 +31,12 @@
package org.opensearch.bootstrap;
-import org.opensearch.common.util.io.IOUtils;
import org.opensearch.common.settings.KeyStoreCommandTestCase;
import org.opensearch.common.settings.KeyStoreWrapper;
import org.opensearch.common.settings.SecureSettings;
-import org.opensearch.core.common.settings.SecureString;
import org.opensearch.common.settings.Settings;
+import org.opensearch.common.util.io.IOUtils;
+import org.opensearch.core.common.settings.SecureString;
import org.opensearch.env.Environment;
import org.opensearch.test.OpenSearchTestCase;
import org.junit.After;
diff --git a/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/CreateKeyStoreCommandTests.java b/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/CreateKeyStoreCommandTests.java
index 11bfc26e2425c..f554f17c50813 100644
--- a/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/CreateKeyStoreCommandTests.java
+++ b/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/CreateKeyStoreCommandTests.java
@@ -32,16 +32,16 @@
package org.opensearch.common.settings;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Map;
-
import org.opensearch.cli.Command;
import org.opensearch.cli.ExitCodes;
import org.opensearch.cli.UserException;
import org.opensearch.env.Environment;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Map;
+
import static org.hamcrest.Matchers.containsString;
public class CreateKeyStoreCommandTests extends KeyStoreCommandTestCase {
diff --git a/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/KeyStoreCommandTestCase.java b/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/KeyStoreCommandTestCase.java
index b87d08bb08399..0ac653d35b07e 100644
--- a/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/KeyStoreCommandTestCase.java
+++ b/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/KeyStoreCommandTestCase.java
@@ -32,25 +32,25 @@
package org.opensearch.common.settings;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.FileSystem;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.ArrayList;
-import java.util.List;
-
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
-import org.opensearch.common.util.io.IOUtils;
import org.apache.lucene.tests.util.LuceneTestCase;
import org.opensearch.cli.CommandTestCase;
import org.opensearch.common.io.PathUtilsForTesting;
+import org.opensearch.common.util.io.IOUtils;
import org.opensearch.env.Environment;
import org.opensearch.env.TestEnvironment;
import org.junit.After;
import org.junit.Before;
+import java.io.IOException;
+import java.io.InputStream;
+import java.nio.file.FileSystem;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
/**
* Base test case for manipulating the OpenSearch keystore.
*/
diff --git a/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/ListKeyStoreCommandTests.java b/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/ListKeyStoreCommandTests.java
index 62d27c4010849..42452d5c12beb 100644
--- a/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/ListKeyStoreCommandTests.java
+++ b/distribution/tools/keystore-cli/src/test/java/org/opensearch/common/settings/ListKeyStoreCommandTests.java
@@ -32,13 +32,13 @@
package org.opensearch.common.settings;
-import java.util.Map;
-
import org.opensearch.cli.Command;
import org.opensearch.cli.ExitCodes;
import org.opensearch.cli.UserException;
import org.opensearch.env.Environment;
+import java.util.Map;
+
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsString;
diff --git a/distribution/tools/launchers/build.gradle b/distribution/tools/launchers/build.gradle
index e75267f7c4a74..aee205a24dea3 100644
--- a/distribution/tools/launchers/build.gradle
+++ b/distribution/tools/launchers/build.gradle
@@ -39,7 +39,7 @@ dependencies {
}
base {
- archivesBaseName = 'opensearch-launchers'
+ archivesName = 'opensearch-launchers'
}
tasks.withType(CheckForbiddenApis).configureEach {
diff --git a/distribution/tools/launchers/src/main/java/org/opensearch/tools/launchers/SystemJvmOptions.java b/distribution/tools/launchers/src/main/java/org/opensearch/tools/launchers/SystemJvmOptions.java
index aa3dfbe39ee96..726c381db09f6 100644
--- a/distribution/tools/launchers/src/main/java/org/opensearch/tools/launchers/SystemJvmOptions.java
+++ b/distribution/tools/launchers/src/main/java/org/opensearch/tools/launchers/SystemJvmOptions.java
@@ -101,15 +101,15 @@ private static String maybeShowCodeDetailsInExceptionMessages() {
}
private static String javaLocaleProviders() {
- /**
- * SPI setting is used to allow loading custom CalendarDataProvider
- * in jdk8 it has to be loaded from jre/lib/ext,
- * in jdk9+ it is already within ES project and on a classpath
- *
- * Due to internationalization enhancements in JDK 9 OpenSearch need to set the provider to COMPAT otherwise time/date
- * parsing will break in an incompatible way for some date patterns and locales.
- * //TODO COMPAT will be deprecated in at some point, see please https://bugs.openjdk.java.net/browse/JDK-8232906
- * See also: documentation in server/org.opensearch.common.time.IsoCalendarDataProvider
+ /*
+ SPI setting is used to allow loading custom CalendarDataProvider
+ in jdk8 it has to be loaded from jre/lib/ext,
+ in jdk9+ it is already within ES project and on a classpath
+
+ Due to internationalization enhancements in JDK 9 OpenSearch need to set the provider to COMPAT otherwise time/date
+ parsing will break in an incompatible way for some date patterns and locales.
+ //TODO COMPAT will be deprecated in at some point, see please https://bugs.openjdk.java.net/browse/JDK-8232906
+ See also: documentation in server/org.opensearch.common.time.IsoCalendarDataProvider
*/
return "-Djava.locale.providers=SPI,COMPAT";
}
diff --git a/distribution/tools/plugin-cli/build.gradle b/distribution/tools/plugin-cli/build.gradle
index 5103999428814..f40fb1c4b0a9f 100644
--- a/distribution/tools/plugin-cli/build.gradle
+++ b/distribution/tools/plugin-cli/build.gradle
@@ -31,21 +31,21 @@
apply plugin: 'opensearch.build'
base {
- archivesBaseName = 'opensearch-plugin-cli'
+ archivesName = 'opensearch-plugin-cli'
}
dependencies {
compileOnly project(":server")
compileOnly project(":libs:opensearch-cli")
api "org.bouncycastle:bcpg-fips:1.0.7.1"
- api "org.bouncycastle:bc-fips:1.0.2.3"
+ api "org.bouncycastle:bc-fips:1.0.2.4"
testImplementation project(":test:framework")
testImplementation 'com.google.jimfs:jimfs:1.3.0'
testRuntimeOnly("com.google.guava:guava:${versions.guava}") {
transitive = false
}
- implementation 'org.apache.commons:commons-compress:1.23.0'
+ implementation "org.apache.commons:commons-compress:${versions.commonscompress}"
}
tasks.named("dependencyLicenses").configure {
diff --git a/distribution/tools/plugin-cli/licenses/bc-fips-1.0.2.3.jar.sha1 b/distribution/tools/plugin-cli/licenses/bc-fips-1.0.2.3.jar.sha1
deleted file mode 100644
index c71320050b7de..0000000000000
--- a/distribution/tools/plugin-cli/licenses/bc-fips-1.0.2.3.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-da62b32cb72591f5b4d322e6ab0ce7de3247b534
\ No newline at end of file
diff --git a/distribution/tools/plugin-cli/licenses/bc-fips-1.0.2.4.jar.sha1 b/distribution/tools/plugin-cli/licenses/bc-fips-1.0.2.4.jar.sha1
new file mode 100644
index 0000000000000..da37449f80d7e
--- /dev/null
+++ b/distribution/tools/plugin-cli/licenses/bc-fips-1.0.2.4.jar.sha1
@@ -0,0 +1 @@
+9008d04fc13da6455e6a792935b93b629757335d
\ No newline at end of file
diff --git a/distribution/tools/plugin-cli/licenses/commons-compress-1.23.0.jar.sha1 b/distribution/tools/plugin-cli/licenses/commons-compress-1.23.0.jar.sha1
deleted file mode 100644
index 48dba88409c17..0000000000000
--- a/distribution/tools/plugin-cli/licenses/commons-compress-1.23.0.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-4af2060ea9b0c8b74f1854c6cafe4d43cfc161fc
\ No newline at end of file
diff --git a/distribution/tools/plugin-cli/licenses/commons-compress-1.24.0.jar.sha1 b/distribution/tools/plugin-cli/licenses/commons-compress-1.24.0.jar.sha1
new file mode 100644
index 0000000000000..23999d1bfbde4
--- /dev/null
+++ b/distribution/tools/plugin-cli/licenses/commons-compress-1.24.0.jar.sha1
@@ -0,0 +1 @@
+b4b1b5a3d9573b2970fddab236102c0a4d27d35e
\ No newline at end of file
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 66f43b1e30d28..838d6e22a37bd 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
@@ -107,7 +107,7 @@
/**
* A command for the plugin cli to install a plugin into opensearch.
- *
+ *
* The install command takes a plugin id, which may be any of the following:
*
* An official opensearch plugin name
@@ -411,7 +411,7 @@ private String getMavenUrl(Terminal terminal, String[] coordinates, String platf
/**
* Returns {@code true} if the given url exists, and {@code false} otherwise.
- *
+ *
* The given url must be {@code https} and existing means a {@code HEAD} request returns 200.
*/
// pkg private for tests to manipulate
@@ -698,7 +698,6 @@ InputStream getPublicKey() {
/**
* Creates a URL and opens a connection.
- *
* If the URL returns a 404, {@code null} is returned, otherwise the open URL opject is returned.
*/
// pkg private for tests
diff --git a/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/ListPluginsCommand.java b/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/ListPluginsCommand.java
index d269603656114..9ca42ac5f4ec1 100644
--- a/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/ListPluginsCommand.java
+++ b/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/ListPluginsCommand.java
@@ -78,15 +78,14 @@ private void printPlugin(Environment env, Terminal terminal, Path plugin, String
PluginInfo info = PluginInfo.readFromProperties(env.pluginsDir().resolve(plugin));
terminal.println(Terminal.Verbosity.SILENT, prefix + info.getName());
terminal.println(Terminal.Verbosity.VERBOSE, info.toString(prefix));
- if (info.getOpenSearchVersion().equals(Version.CURRENT) == false) {
+ if (!PluginsService.isPluginVersionCompatible(info, Version.CURRENT)) {
terminal.errorPrintln(
"WARNING: plugin ["
+ info.getName()
+ "] was built for OpenSearch version "
- + info.getVersion()
- + " but version "
+ + info.getOpenSearchVersionRangesString()
+ + " and is not compatible with "
+ Version.CURRENT
- + " is required"
);
}
}
diff --git a/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/PluginCli.java b/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/PluginCli.java
index 3ea8e539cdd5c..f87b72c7ecb5f 100644
--- a/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/PluginCli.java
+++ b/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/PluginCli.java
@@ -32,10 +32,10 @@
package org.opensearch.plugins;
-import org.opensearch.common.util.io.IOUtils;
import org.opensearch.cli.Command;
import org.opensearch.cli.LoggingAwareMultiCommand;
import org.opensearch.cli.Terminal;
+import org.opensearch.common.util.io.IOUtils;
import java.io.IOException;
import java.util.Collection;
diff --git a/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/ProgressInputStream.java b/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/ProgressInputStream.java
index 579f676631a5a..02be3dbc82a44 100644
--- a/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/ProgressInputStream.java
+++ b/distribution/tools/plugin-cli/src/main/java/org/opensearch/plugins/ProgressInputStream.java
@@ -41,7 +41,7 @@
* The listener is triggered whenever a full percent is increased
* The listener is never triggered twice on the same percentage
* The listener will always return 99 percent, if the expectedTotalSize is exceeded, until it is finished
- *
+ *
* Only used by the InstallPluginCommand, thus package private here
*/
abstract class ProgressInputStream extends FilterInputStream {
diff --git a/distribution/tools/plugin-cli/src/test/java/org/opensearch/plugins/InstallPluginCommandTests.java b/distribution/tools/plugin-cli/src/test/java/org/opensearch/plugins/InstallPluginCommandTests.java
index 3d92f0c52ba1c..c264788df20e8 100644
--- a/distribution/tools/plugin-cli/src/test/java/org/opensearch/plugins/InstallPluginCommandTests.java
+++ b/distribution/tools/plugin-cli/src/test/java/org/opensearch/plugins/InstallPluginCommandTests.java
@@ -33,6 +33,7 @@
package org.opensearch.plugins;
import com.carrotsearch.randomizedtesting.annotations.ParametersFactory;
+
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.apache.lucene.tests.util.LuceneTestCase;
@@ -63,14 +64,16 @@
import org.opensearch.common.SuppressForbidden;
import org.opensearch.common.collect.Tuple;
import org.opensearch.common.hash.MessageDigests;
-import org.opensearch.core.util.FileSystemUtils;
import org.opensearch.common.io.PathUtils;
import org.opensearch.common.io.PathUtilsForTesting;
import org.opensearch.common.settings.Settings;
+import org.opensearch.core.util.FileSystemUtils;
import org.opensearch.env.Environment;
import org.opensearch.env.TestEnvironment;
+import org.opensearch.semver.SemverRange;
import org.opensearch.test.OpenSearchTestCase;
import org.opensearch.test.PosixPermissionsResetter;
+import org.opensearch.test.VersionUtils;
import org.junit.After;
import org.junit.Before;
@@ -283,6 +286,35 @@ static void writePlugin(String name, Path structure, String... additionalProps)
writeJar(structure.resolve("plugin.jar"), className);
}
+ static void writePlugin(String name, Path structure, SemverRange opensearchVersionRange, String... additionalProps) throws IOException {
+ String[] properties = Stream.concat(
+ Stream.of(
+ "description",
+ "fake desc",
+ "name",
+ name,
+ "version",
+ "1.0",
+ "dependencies",
+ "{opensearch:\"" + opensearchVersionRange + "\"}",
+ "java.version",
+ System.getProperty("java.specification.version"),
+ "classname",
+ "FakePlugin"
+ ),
+ Arrays.stream(additionalProps)
+ ).toArray(String[]::new);
+ PluginTestUtil.writePluginProperties(structure, properties);
+ String className = name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1) + "Plugin";
+ writeJar(structure.resolve("plugin.jar"), className);
+ }
+
+ static Path createPlugin(String name, Path structure, SemverRange opensearchVersionRange, String... additionalProps)
+ throws IOException {
+ writePlugin(name, structure, opensearchVersionRange, additionalProps);
+ return writeZip(structure, null);
+ }
+
static void writePluginSecurityPolicy(Path pluginDir, String... permissions) throws IOException {
StringBuilder securityPolicyContent = new StringBuilder("grant {\n ");
for (String permission : permissions) {
@@ -866,6 +898,32 @@ public void testInstallMisspelledOfficialPlugins() throws Exception {
assertThat(e.getMessage(), containsString("Unknown plugin unknown_plugin"));
}
+ public void testInstallPluginWithCompatibleDependencies() throws Exception {
+ Tuple env = createEnv(fs, temp);
+ Path pluginDir = createPluginDir(temp);
+ String pluginZip = createPlugin("fake", pluginDir, SemverRange.fromString("~" + Version.CURRENT.toString())).toUri()
+ .toURL()
+ .toString();
+ skipJarHellCommand.execute(terminal, Collections.singletonList(pluginZip), false, env.v2());
+ assertThat(terminal.getOutput(), containsString("100%"));
+ }
+
+ public void testInstallPluginWithIncompatibleDependencies() throws Exception {
+ Tuple env = createEnv(fs, temp);
+ Path pluginDir = createPluginDir(temp);
+ // Core version is behind plugin version by one w.r.t patch, hence incompatible
+ Version coreVersion = Version.CURRENT;
+ Version pluginVersion = VersionUtils.getVersion(coreVersion.major, coreVersion.minor, (byte) (coreVersion.revision + 1));
+ String pluginZip = createPlugin("fake", pluginDir, SemverRange.fromString("~" + pluginVersion.toString())).toUri()
+ .toURL()
+ .toString();
+ IllegalArgumentException e = expectThrows(
+ IllegalArgumentException.class,
+ () -> skipJarHellCommand.execute(terminal, Collections.singletonList(pluginZip), false, env.v2())
+ );
+ assertThat(e.getMessage(), containsString("Plugin [fake] was built for OpenSearch version ~" + pluginVersion));
+ }
+
public void testBatchFlag() throws Exception {
MockTerminal terminal = new MockTerminal();
installPlugin(terminal, true);
diff --git a/distribution/tools/plugin-cli/src/test/java/org/opensearch/plugins/ListPluginsCommandTests.java b/distribution/tools/plugin-cli/src/test/java/org/opensearch/plugins/ListPluginsCommandTests.java
index d84f36d818046..6878efce4c804 100644
--- a/distribution/tools/plugin-cli/src/test/java/org/opensearch/plugins/ListPluginsCommandTests.java
+++ b/distribution/tools/plugin-cli/src/test/java/org/opensearch/plugins/ListPluginsCommandTests.java
@@ -32,14 +32,6 @@
package org.opensearch.plugins;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.NoSuchFileException;
-import java.nio.file.Path;
-import java.util.Arrays;
-import java.util.Map;
-import java.util.stream.Collectors;
-
import org.apache.lucene.tests.util.LuceneTestCase;
import org.opensearch.LegacyESVersion;
import org.opensearch.Version;
@@ -52,6 +44,14 @@
import org.opensearch.test.OpenSearchTestCase;
import org.junit.Before;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.stream.Collectors;
+
@LuceneTestCase.SuppressFileSystems("*")
public class ListPluginsCommandTests extends OpenSearchTestCase {
@@ -278,7 +278,7 @@ public void testExistingIncompatiblePlugin() throws Exception {
buildFakePlugin(env, "fake desc 2", "fake_plugin2", "org.fake2");
MockTerminal terminal = listPlugins(home);
- String message = "plugin [fake_plugin1] was built for OpenSearch version 1.0 but version " + Version.CURRENT + " is required";
+ String message = "plugin [fake_plugin1] was built for OpenSearch version 5.0.0 and is not compatible with " + Version.CURRENT;
assertEquals("fake_plugin1\nfake_plugin2\n", terminal.getOutput());
assertEquals("WARNING: " + message + "\n", terminal.getErrorOutput());
@@ -286,4 +286,41 @@ public void testExistingIncompatiblePlugin() throws Exception {
terminal = listPlugins(home, params);
assertEquals("fake_plugin1\nfake_plugin2\n", terminal.getOutput());
}
+
+ public void testPluginWithDependencies() throws Exception {
+ PluginTestUtil.writePluginProperties(
+ env.pluginsDir().resolve("fake_plugin1"),
+ "description",
+ "fake desc 1",
+ "name",
+ "fake_plugin1",
+ "version",
+ "1.0",
+ "dependencies",
+ "{opensearch:\"" + Version.CURRENT + "\"}",
+ "java.version",
+ System.getProperty("java.specification.version"),
+ "classname",
+ "org.fake1"
+ );
+ String[] params = { "-v" };
+ MockTerminal terminal = listPlugins(home, params);
+ assertEquals(
+ buildMultiline(
+ "Plugins directory: " + env.pluginsDir(),
+ "fake_plugin1",
+ "- Plugin information:",
+ "Name: fake_plugin1",
+ "Description: fake desc 1",
+ "Version: 1.0",
+ "OpenSearch Version: " + Version.CURRENT.toString(),
+ "Java Version: " + System.getProperty("java.specification.version"),
+ "Native Controller: false",
+ "Extended Plugins: []",
+ " * Classname: org.fake1",
+ "Folder name: null"
+ ),
+ terminal.getOutput()
+ );
+ }
}
diff --git a/distribution/tools/upgrade-cli/build.gradle b/distribution/tools/upgrade-cli/build.gradle
index 99824463f14f8..92c043132c021 100644
--- a/distribution/tools/upgrade-cli/build.gradle
+++ b/distribution/tools/upgrade-cli/build.gradle
@@ -10,7 +10,7 @@
apply plugin: 'opensearch.build'
base {
- archivesBaseName = 'opensearch-upgrade-cli'
+ archivesName = 'opensearch-upgrade-cli'
}
dependencies {
diff --git a/distribution/tools/upgrade-cli/licenses/jackson-annotations-2.15.2.jar.sha1 b/distribution/tools/upgrade-cli/licenses/jackson-annotations-2.15.2.jar.sha1
deleted file mode 100644
index f63416ddb8ceb..0000000000000
--- a/distribution/tools/upgrade-cli/licenses/jackson-annotations-2.15.2.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-4724a65ac8e8d156a24898d50fd5dbd3642870b8
\ No newline at end of file
diff --git a/distribution/tools/upgrade-cli/licenses/jackson-annotations-2.16.2.jar.sha1 b/distribution/tools/upgrade-cli/licenses/jackson-annotations-2.16.2.jar.sha1
new file mode 100644
index 0000000000000..d7dfc5ff83706
--- /dev/null
+++ b/distribution/tools/upgrade-cli/licenses/jackson-annotations-2.16.2.jar.sha1
@@ -0,0 +1 @@
+dfcd11c847ea7276aa073c25f5fe8ee361748d7f
\ No newline at end of file
diff --git a/distribution/tools/upgrade-cli/licenses/jackson-databind-2.15.2.jar.sha1 b/distribution/tools/upgrade-cli/licenses/jackson-databind-2.15.2.jar.sha1
deleted file mode 100644
index f16d80af8dce6..0000000000000
--- a/distribution/tools/upgrade-cli/licenses/jackson-databind-2.15.2.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-9353b021f10c307c00328f52090de2bdb4b6ff9c
\ No newline at end of file
diff --git a/distribution/tools/upgrade-cli/licenses/jackson-databind-2.16.2.jar.sha1 b/distribution/tools/upgrade-cli/licenses/jackson-databind-2.16.2.jar.sha1
new file mode 100644
index 0000000000000..86998b4558461
--- /dev/null
+++ b/distribution/tools/upgrade-cli/licenses/jackson-databind-2.16.2.jar.sha1
@@ -0,0 +1 @@
+7fda67535b54d74eebf6157682b835c847410932
\ No newline at end of file
diff --git a/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/DetectEsInstallationTask.java b/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/DetectEsInstallationTask.java
index 24f4b79d12528..90067ffd221bf 100644
--- a/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/DetectEsInstallationTask.java
+++ b/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/DetectEsInstallationTask.java
@@ -9,6 +9,7 @@
package org.opensearch.upgrade;
import com.fasterxml.jackson.databind.ObjectMapper;
+
import org.opensearch.Version;
import org.opensearch.cli.Terminal;
import org.opensearch.common.SuppressForbidden;
diff --git a/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/ImportYmlConfigTask.java b/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/ImportYmlConfigTask.java
index cd7c525dd393d..6e29bd2d04239 100644
--- a/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/ImportYmlConfigTask.java
+++ b/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/ImportYmlConfigTask.java
@@ -12,9 +12,9 @@
import org.opensearch.common.collect.Tuple;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.settings.SettingsException;
+import org.opensearch.common.xcontent.yaml.YamlXContent;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.common.xcontent.yaml.YamlXContent;
import java.io.IOException;
import java.io.OutputStream;
diff --git a/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/UpgradeTask.java b/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/UpgradeTask.java
index b7dcbd50cf781..708f644bcdeb6 100644
--- a/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/UpgradeTask.java
+++ b/distribution/tools/upgrade-cli/src/main/java/org/opensearch/upgrade/UpgradeTask.java
@@ -17,7 +17,7 @@
* An interface for an upgrade task, which in this instance is an unit of
* operation that is part of the overall upgrade process. This extends the
* {@link java.util.function.Consumer} interface.
- *
+ *
* The implementing tasks consume and instance of a tuple of {@link TaskInput}
* and {@link Terminal} and operate via side effects.
*
diff --git a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/DetectEsInstallationTaskTests.java b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/DetectEsInstallationTaskTests.java
index 1038e6d4a484f..a1391ba70a8e8 100644
--- a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/DetectEsInstallationTaskTests.java
+++ b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/DetectEsInstallationTaskTests.java
@@ -8,7 +8,6 @@
package org.opensearch.upgrade;
-import org.junit.Before;
import org.opensearch.cli.MockTerminal;
import org.opensearch.cli.Terminal;
import org.opensearch.common.SuppressForbidden;
@@ -17,6 +16,7 @@
import org.opensearch.env.Environment;
import org.opensearch.env.TestEnvironment;
import org.opensearch.test.OpenSearchTestCase;
+import org.junit.Before;
import java.io.File;
import java.nio.file.Path;
diff --git a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ImportLog4jPropertiesTaskTests.java b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ImportLog4jPropertiesTaskTests.java
index 96544d3297ad4..529253c9ce824 100644
--- a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ImportLog4jPropertiesTaskTests.java
+++ b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ImportLog4jPropertiesTaskTests.java
@@ -10,7 +10,6 @@
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
-import org.junit.Before;
import org.opensearch.cli.MockTerminal;
import org.opensearch.common.SuppressForbidden;
import org.opensearch.common.collect.Tuple;
@@ -19,6 +18,7 @@
import org.opensearch.env.Environment;
import org.opensearch.env.TestEnvironment;
import org.opensearch.test.OpenSearchTestCase;
+import org.junit.Before;
import java.io.File;
import java.io.IOException;
diff --git a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ImportYmlConfigTaskTests.java b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ImportYmlConfigTaskTests.java
index f328cc21685ad..be03470b201a1 100644
--- a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ImportYmlConfigTaskTests.java
+++ b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ImportYmlConfigTaskTests.java
@@ -10,7 +10,6 @@
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
-import org.junit.Before;
import org.opensearch.cli.MockTerminal;
import org.opensearch.common.SuppressForbidden;
import org.opensearch.common.collect.Tuple;
@@ -19,6 +18,7 @@
import org.opensearch.env.Environment;
import org.opensearch.env.TestEnvironment;
import org.opensearch.test.OpenSearchTestCase;
+import org.junit.Before;
import java.io.File;
import java.io.IOException;
diff --git a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/InstallPluginsTaskTests.java b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/InstallPluginsTaskTests.java
index 6cb6f0b7cf116..46e189a4765d0 100644
--- a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/InstallPluginsTaskTests.java
+++ b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/InstallPluginsTaskTests.java
@@ -8,18 +8,19 @@
package org.opensearch.upgrade;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import org.junit.Before;
-import org.mockito.Mockito;
import org.opensearch.cli.MockTerminal;
import org.opensearch.common.collect.Tuple;
import org.opensearch.common.settings.Settings;
import org.opensearch.env.Environment;
import org.opensearch.env.TestEnvironment;
import org.opensearch.test.OpenSearchTestCase;
+import org.junit.Before;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.mockito.Mockito;
import static org.hamcrest.Matchers.containsString;
import static org.mockito.Mockito.spy;
diff --git a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/UpgradeCliTests.java b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/UpgradeCliTests.java
index ee871e1d89001..a139480c71a2f 100644
--- a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/UpgradeCliTests.java
+++ b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/UpgradeCliTests.java
@@ -10,8 +10,6 @@
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
-import org.junit.After;
-import org.junit.Before;
import org.opensearch.cli.Command;
import org.opensearch.cli.CommandTestCase;
import org.opensearch.common.SuppressForbidden;
@@ -21,6 +19,8 @@
import org.opensearch.common.util.io.IOUtils;
import org.opensearch.env.Environment;
import org.opensearch.env.TestEnvironment;
+import org.junit.After;
+import org.junit.Before;
import java.io.File;
import java.io.IOException;
diff --git a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ValidateInputTaskTests.java b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ValidateInputTaskTests.java
index 195c57e5b457f..b9a536afb1361 100644
--- a/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ValidateInputTaskTests.java
+++ b/distribution/tools/upgrade-cli/src/test/java/org/opensearch/upgrade/ValidateInputTaskTests.java
@@ -8,7 +8,6 @@
package org.opensearch.upgrade;
-import org.junit.Before;
import org.opensearch.LegacyESVersion;
import org.opensearch.cli.MockTerminal;
import org.opensearch.common.collect.Tuple;
@@ -17,6 +16,7 @@
import org.opensearch.env.Environment;
import org.opensearch.env.TestEnvironment;
import org.opensearch.test.OpenSearchTestCase;
+import org.junit.Before;
import java.util.Arrays;
import java.util.Map;
diff --git a/doc-tools/missing-doclet/src/main/java/org/opensearch/missingdoclet/MissingDoclet.java b/doc-tools/missing-doclet/src/main/java/org/opensearch/missingdoclet/MissingDoclet.java
index e6122e7baf91a..e1ad55fe4b60b 100644
--- a/doc-tools/missing-doclet/src/main/java/org/opensearch/missingdoclet/MissingDoclet.java
+++ b/doc-tools/missing-doclet/src/main/java/org/opensearch/missingdoclet/MissingDoclet.java
@@ -45,7 +45,7 @@
* It isn't recursive, just ignores exactly the elements you tell it.
* Has option --missing-method to apply "method" level to selected packages (fix one at a time).
* Matches package names exactly: so you'll need to list subpackages separately.
- *
+ *
* Note: This by default ignores javadoc validation on overridden methods.
*/
// Original version of this class is ported from MissingDoclet code in Lucene,
diff --git a/docs/build.gradle b/docs/build.gradle
new file mode 100644
index 0000000000000..385d5ff27433e
--- /dev/null
+++ b/docs/build.gradle
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+// This file is intentionally blank. All configuration of the
+// distribution is done in the parent project.
+
+// See please https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#deprecated_missing_project_directory
diff --git a/gradle/code-coverage.gradle b/gradle/code-coverage.gradle
index dfb4ddba24113..3ca6b1fe84ea7 100644
--- a/gradle/code-coverage.gradle
+++ b/gradle/code-coverage.gradle
@@ -13,7 +13,7 @@ repositories {
gradlePluginPortal()
// TODO: Find the way to use the repositories from RepositoriesSetupPlugin
maven {
- url = "https://d1nvenhzbhpy0q.cloudfront.net/snapshots/lucene/"
+ url = "https://ci.opensearch.org/ci/dbc/snapshots/lucene/"
}
}
@@ -37,7 +37,7 @@ tasks.withType(JacocoReport).configureEach {
if (System.getProperty("tests.coverage")) {
reporting {
reports {
- testCodeCoverageReport(JacocoCoverageReport) {
+ testCodeCoverageReport(JacocoCoverageReport) {
testType = TestSuiteType.UNIT_TEST
}
}
@@ -45,6 +45,6 @@ if (System.getProperty("tests.coverage")) {
// Attach code coverage report task to Gradle check task
project.getTasks().named(JavaBasePlugin.CHECK_TASK_NAME).configure {
- dependsOn tasks.named('testCodeCoverageReport', JacocoReport)
+ dependsOn tasks.named('testCodeCoverageReport', JacocoReport)
}
}
diff --git a/gradle/formatting.gradle b/gradle/formatting.gradle
index 93be7b454d650..f3a4bf5cc765b 100644
--- a/gradle/formatting.gradle
+++ b/gradle/formatting.gradle
@@ -66,6 +66,22 @@ allprojects {
target '**/*.java'
removeUnusedImports()
+ importOrder(
+ 'de.thetaphi',
+ 'com.carrotsearch',
+ 'com.fasterxml',
+ 'com.avast',
+ 'com.sun',
+ 'com.maxmind|com.github|com.networknt|groovy|nebula',
+ 'org.antlr',
+ 'software.amazon',
+ 'com.azure|com.microsoft|com.ibm|com.google|joptsimple|org.apache|org.bouncycastle|org.codehaus|org.opensearch|org.objectweb|org.joda|org.hamcrest|org.openjdk|org.gradle|org.junit',
+ 'javax',
+ 'java',
+ '',
+ '\\#java|\\#org.opensearch|\\#org.hamcrest|\\#'
+ )
+
eclipse().configFile rootProject.file('buildSrc/formatterConfig.xml')
trimTrailingWhitespace()
endWithNewline()
@@ -83,7 +99,9 @@ allprojects {
}
}
format 'misc', {
- target '*.md', '*.gradle', '**/*.yaml', '**/*.yml', '**/*.svg'
+ target '*.md', '*.gradle', '**/*.json', '**/*.yaml', '**/*.yml', '**/*.svg'
+
+ targetExclude '**/simple-bulk11.json', '**/simple-msearch5.json'
trimTrailingWhitespace()
endWithNewline()
diff --git a/gradle/ide.gradle b/gradle/ide.gradle
index bc442a081adf0..14d6b2982ccd0 100644
--- a/gradle/ide.gradle
+++ b/gradle/ide.gradle
@@ -82,6 +82,9 @@ if (System.getProperty('idea.active') == 'true') {
runConfigurations {
defaults(JUnit) {
vmParameters = '-ea -Djava.locale.providers=SPI,COMPAT'
+ if (BuildParams.runtimeJavaVersion > JavaVersion.VERSION_17) {
+ vmParameters += ' -Djava.security.manager=allow'
+ }
}
}
copyright {
diff --git a/gradle/missing-javadoc.gradle b/gradle/missing-javadoc.gradle
index 03addc1ba3616..e9a6d798b8323 100644
--- a/gradle/missing-javadoc.gradle
+++ b/gradle/missing-javadoc.gradle
@@ -147,6 +147,7 @@ configure([
project(":plugins:repository-s3"),
project(":plugins:store-smb"),
project(":plugins:transport-nio"),
+ project(":plugins:crypto-kms"),
project(":qa:die-with-dignity"),
project(":qa:wildfly"),
project(":test:external-modules:test-delayed-aggs"),
@@ -166,6 +167,7 @@ configure([
configure([
project(":libs:opensearch-common"),
project(":libs:opensearch-core"),
+ project(":libs:opensearch-compress"),
project(":plugins:events-correlation-engine"),
project(":server")
]) {
diff --git a/gradle/run.gradle b/gradle/run.gradle
index 639479e97d28f..34651f1d94964 100644
--- a/gradle/run.gradle
+++ b/gradle/run.gradle
@@ -39,6 +39,12 @@ testClusters {
testDistribution = 'archive'
if (numZones > 1) numberOfZones = numZones
if (numNodes > 1) numberOfNodes = numNodes
+ if (findProperty("installedPlugins")) {
+ installedPlugins = Eval.me(installedPlugins)
+ for (String p : installedPlugins) {
+ plugin('plugins:'.concat(p))
+ }
+ }
}
}
diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar
index 033e24c4cdf41..d64cd4917707c 100644
Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index e10ceefe2a012..82a4add334a7d 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -11,7 +11,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
-distributionUrl=https\://services.gradle.org/distributions/gradle-8.2.1-all.zip
+distributionUrl=https\://services.gradle.org/distributions/gradle-8.6-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-distributionSha256Sum=7c3ad722e9b0ce8205b91560fd6ce8296ac3eadf065672242fd73c06b8eeb6ee
+distributionSha256Sum=85719317abd2112f021d4f41f09ec370534ba288432065f4b477b6a3b652910d
diff --git a/gradlew b/gradlew
index fcb6fca147c0c..1aa94a4269074 100755
--- a/gradlew
+++ b/gradlew
@@ -83,7 +83,8 @@ done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
-APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
+# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
+APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
@@ -144,7 +145,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC3045
+ # shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
@@ -152,7 +153,7 @@ if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
- # shellcheck disable=SC3045
+ # shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
@@ -201,11 +202,11 @@ fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
-# Collect all arguments for the java command;
-# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
-# shell script including quotes and variable substitutions, so put them in
-# double quotes to make sure that they get re-expanded; and
-# * put everything else in single quotes, so that it's not re-expanded.
+# Collect all arguments for the java command:
+# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
+# and any embedded shellness will be escaped.
+# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
+# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
diff --git a/libs/cli/src/main/java/org/opensearch/cli/Command.java b/libs/cli/src/main/java/org/opensearch/cli/Command.java
index eed5c4ba4ee6f..cc9230bdb2282 100644
--- a/libs/cli/src/main/java/org/opensearch/cli/Command.java
+++ b/libs/cli/src/main/java/org/opensearch/cli/Command.java
@@ -162,7 +162,7 @@ protected static void exit(int status) {
/**
* Executes this command.
- *
+ *
* Any runtime user errors (like an input file that does not exist), should throw a {@link UserException}. */
protected abstract void execute(Terminal terminal, OptionSet options) throws Exception;
diff --git a/libs/cli/src/main/java/org/opensearch/cli/ExitCodes.java b/libs/cli/src/main/java/org/opensearch/cli/ExitCodes.java
index c705177b0d7b6..90efc89a08caf 100644
--- a/libs/cli/src/main/java/org/opensearch/cli/ExitCodes.java
+++ b/libs/cli/src/main/java/org/opensearch/cli/ExitCodes.java
@@ -36,20 +36,34 @@
* POSIX exit codes.
*/
public class ExitCodes {
+ /** No error */
public static final int OK = 0;
- public static final int USAGE = 64; /* command line usage error */
- public static final int DATA_ERROR = 65; /* data format error */
- public static final int NO_INPUT = 66; /* cannot open input */
- public static final int NO_USER = 67; /* addressee unknown */
- public static final int NO_HOST = 68; /* host name unknown */
- public static final int UNAVAILABLE = 69; /* service unavailable */
- public static final int CODE_ERROR = 70; /* internal software error */
- public static final int CANT_CREATE = 73; /* can't create (user) output file */
- public static final int IO_ERROR = 74; /* input/output error */
- public static final int TEMP_FAILURE = 75; /* temp failure; user is invited to retry */
- public static final int PROTOCOL = 76; /* remote error in protocol */
- public static final int NOPERM = 77; /* permission denied */
- public static final int CONFIG = 78; /* configuration error */
+ /** command line usage error */
+ public static final int USAGE = 64;
+ /** data format error */
+ public static final int DATA_ERROR = 65;
+ /** cannot open input */
+ public static final int NO_INPUT = 66;
+ /** addressee unknown */
+ public static final int NO_USER = 67;
+ /** host name unknown */
+ public static final int NO_HOST = 68;
+ /** service unavailable */
+ public static final int UNAVAILABLE = 69;
+ /** internal software error */
+ public static final int CODE_ERROR = 70;
+ /** can't create (user) output file */
+ public static final int CANT_CREATE = 73;
+ /** input/output error */
+ public static final int IO_ERROR = 74;
+ /** temp failure; user is invited to retry */
+ public static final int TEMP_FAILURE = 75;
+ /** remote error in protocol */
+ public static final int PROTOCOL = 76;
+ /** permission denied */
+ public static final int NOPERM = 77;
+ /** configuration error */
+ public static final int CONFIG = 78;
private ExitCodes() { /* no instance, just constants */ }
}
diff --git a/libs/cli/src/main/java/org/opensearch/cli/Terminal.java b/libs/cli/src/main/java/org/opensearch/cli/Terminal.java
index 657b95fa052ab..fb1097178e5a3 100644
--- a/libs/cli/src/main/java/org/opensearch/cli/Terminal.java
+++ b/libs/cli/src/main/java/org/opensearch/cli/Terminal.java
@@ -44,13 +44,15 @@
/**
* A Terminal wraps access to reading input and writing output for a cli.
- *
+ *
* The available methods are similar to those of {@link Console}, with the ability
* to read either normal text or a password, and the ability to print a line
* of text. Printing is also gated by the {@link Verbosity} of the terminal,
* which allows {@link #println(Verbosity,String)} calls which act like a logger,
* only actually printing if the verbosity level of the terminal is above
* the verbosity of the message.
+ * @see ConsoleTerminal
+ * @see SystemTerminal
*/
public abstract class Terminal {
@@ -65,35 +67,57 @@ private static PrintWriter newErrorWriter() {
return new PrintWriter(System.err);
}
- /** Defines the available verbosity levels of messages to be printed. */
+ /** Defines the available verbosity levels of messages to be printed.*/
public enum Verbosity {
- SILENT, /* always printed */
- NORMAL, /* printed when no options are given to cli */
- VERBOSE /* printed only when cli is passed verbose option */
+ /** always printed */
+ SILENT,
+ /** printed when no options are given to cli */
+ NORMAL,
+ /** printed only when cli is passed verbose option */
+ VERBOSE
}
/** The current verbosity for the terminal, defaulting to {@link Verbosity#NORMAL}. */
private Verbosity verbosity = Verbosity.NORMAL;
- /** The newline used when calling println. */
+ /** The newline separator used when calling println. */
private final String lineSeparator;
+ /** Constructs a new terminal with the given line separator.
+ * @param lineSeparator the line separator to use when calling println
+ * */
protected Terminal(String lineSeparator) {
this.lineSeparator = lineSeparator;
}
- /** Sets the verbosity of the terminal. */
+ /** Sets the {@link Terminal#verbosity} of the terminal. (Default is {@link Verbosity#NORMAL})
+ * @param verbosity the {@link Verbosity} level that will be used for printing
+ * */
public void setVerbosity(Verbosity verbosity) {
this.verbosity = verbosity;
}
- /** Reads clear text from the terminal input. See {@link Console#readLine()}. */
+ /** Reads clear text from the terminal input.
+ * @see Console#readLine()
+ * @param prompt message to display to the user
+ * @return the text entered by the user
+ * */
public abstract String readText(String prompt);
- /** Reads password text from the terminal input. See {@link Console#readPassword()}}. */
+ /** Reads secret text from the terminal input with echoing disabled.
+ * @see Console#readPassword()
+ * @param prompt message to display to the user
+ * @return the secret as a character array
+ * */
public abstract char[] readSecret(String prompt);
- /** Read password text form terminal input up to a maximum length. */
+ /** Read secret text from terminal input with echoing disabled, up to a maximum length.
+ * @see Console#readPassword()
+ * @param prompt message to display to the user
+ * @param maxLength the maximum length of the secret
+ * @return the secret as a character array
+ * @throws IllegalStateException if the secret exceeds the maximum length
+ * */
public char[] readSecret(String prompt, int maxLength) {
char[] result = readSecret(prompt);
if (result.length > maxLength) {
@@ -103,30 +127,48 @@ public char[] readSecret(String prompt, int maxLength) {
return result;
}
- /** Returns a Writer which can be used to write to the terminal directly using standard output. */
+ /** Returns a Writer which can be used to write to the terminal directly using standard output.
+ * @return a writer to {@link Terminal#DEFAULT} output
+ * @see Terminal.ConsoleTerminal
+ * @see Terminal.SystemTerminal
+ * */
public abstract PrintWriter getWriter();
- /** Returns a Writer which can be used to write to the terminal directly using standard error. */
+ /** Returns a Writer which can be used to write to the terminal directly using standard error.
+ * @return a writer to stderr
+ * */
public PrintWriter getErrorWriter() {
return ERROR_WRITER;
}
- /** Prints a line to the terminal at {@link Verbosity#NORMAL} verbosity level. */
+ /** Prints a line to the terminal at {@link Verbosity#NORMAL} verbosity level, with a {@link Terminal#lineSeparator}
+ * @param msg the message to print
+ * */
public final void println(String msg) {
println(Verbosity.NORMAL, msg);
}
- /** Prints a line to the terminal at {@code verbosity} level. */
+ /** Prints message to the terminal's standard output at {@link Verbosity} level, with a {@link Terminal#lineSeparator}.
+ * @param verbosity the {@link Verbosity} level at which to print
+ * @param msg the message to print
+ * */
public final void println(Verbosity verbosity, String msg) {
print(verbosity, msg + lineSeparator);
}
- /** Prints message to the terminal's standard output at {@code verbosity} level, without a newline. */
+ /** Prints message to the terminal's standard output at {@link Verbosity} level, without adding a {@link Terminal#lineSeparator}.
+ * @param verbosity the {@link Verbosity} level at which to print
+ * @param msg the message to print
+ * */
public final void print(Verbosity verbosity, String msg) {
print(verbosity, msg, false);
}
- /** Prints message to the terminal at {@code verbosity} level, without a newline. */
+ /** Prints message to either standard or error output at {@link Verbosity} level, without adding a {@link Terminal#lineSeparator}.
+ * @param verbosity the {@link Verbosity} level at which to print.
+ * @param msg the message to print
+ * @param isError if true, prints to standard error instead of standard output
+ * */
private void print(Verbosity verbosity, String msg, boolean isError) {
if (isPrintable(verbosity)) {
PrintWriter writer = isError ? getErrorWriter() : getWriter();
@@ -135,29 +177,44 @@ private void print(Verbosity verbosity, String msg, boolean isError) {
}
}
- /** Prints a line to the terminal's standard error at {@link Verbosity#NORMAL} verbosity level, without a newline. */
+ /** Prints a line to the terminal's standard error at {@link Verbosity} level, without adding a {@link Terminal#lineSeparator}.
+ * @param verbosity the {@link Verbosity} level at which to print.
+ * @param msg the message to print
+ * */
public final void errorPrint(Verbosity verbosity, String msg) {
print(verbosity, msg, true);
}
- /** Prints a line to the terminal's standard error at {@link Verbosity#NORMAL} verbosity level. */
+ /** Prints a line to the terminal's standard error at {@link Verbosity#NORMAL} verbosity level, with a {@link Terminal#lineSeparator}
+ * @param msg the message to print
+ * */
public final void errorPrintln(String msg) {
errorPrintln(Verbosity.NORMAL, msg);
}
- /** Prints a line to the terminal's standard error at {@code verbosity} level. */
+ /** Prints a line to the terminal's standard error at {@link Verbosity} level, with a {@link Terminal#lineSeparator}.
+ * @param verbosity the {@link Verbosity} level at which to print.
+ * @param msg the message to print
+ * */
public final void errorPrintln(Verbosity verbosity, String msg) {
errorPrint(verbosity, msg + lineSeparator);
}
- /** Checks if is enough {@code verbosity} level to be printed */
+ /** Checks if given {@link Verbosity} level is high enough to be printed at the level defined by {@link Terminal#verbosity}
+ * @param verbosity the {@link Verbosity} level to check
+ * @return true if the {@link Verbosity} level is high enough to be printed
+ * @see Terminal#setVerbosity(Verbosity)
+ * */
public final boolean isPrintable(Verbosity verbosity) {
return this.verbosity.ordinal() >= verbosity.ordinal();
}
/**
- * Prompt for a yes or no answer from the user. This method will loop until 'y' or 'n'
+ * Prompt for a yes or no answer from the user. This method will loop until 'y', 'n'
* (or the default empty value) is entered.
+ * @param prompt the prompt to display to the user
+ * @param defaultYes if true, the default answer is 'y', otherwise it is 'n'
+ * @return true if the user answered 'y', false if the user answered 'n' or the defaultYes value if the user entered nothing
*/
public final boolean promptYesNo(String prompt, boolean defaultYes) {
String answerPrompt = defaultYes ? " [Y/n]" : " [y/N]";
@@ -181,6 +238,11 @@ public final boolean promptYesNo(String prompt, boolean defaultYes) {
* character is immediately preceded by a carriage return, we have
* a Windows-style newline, so we discard the carriage return as well
* as the newline.
+ * @param reader the reader to read from
+ * @param maxLength the maximum length of the line to read
+ * @return the line read from the reader
+ * @throws RuntimeException if the line read exceeds the maximum length
+ * @throws RuntimeException if an IOException occurs while reading
*/
public static char[] readLineToCharArray(Reader reader, int maxLength) {
char[] buf = new char[maxLength + 2];
@@ -215,6 +277,7 @@ public static char[] readLineToCharArray(Reader reader, int maxLength) {
}
}
+ /** Flushes the terminal's standard output and standard error. */
public void flush() {
this.getWriter().flush();
this.getErrorWriter().flush();
diff --git a/libs/common/build.gradle b/libs/common/build.gradle
index 973fe30d09842..60bf488833393 100644
--- a/libs/common/build.gradle
+++ b/libs/common/build.gradle
@@ -14,7 +14,7 @@ import org.opensearch.gradle.info.BuildParams
apply plugin: 'opensearch.publish'
base {
- archivesBaseName = 'opensearch-common'
+ archivesName = 'opensearch-common'
}
dependencies {
@@ -43,3 +43,64 @@ tasks.named('forbiddenApisMain').configure {
// TODO: Need to decide how we want to handle for forbidden signatures with the changes to server
replaceSignatureFiles 'jdk-signatures'
}
+
+// Add support for incubator modules on supported Java versions.
+if (BuildParams.runtimeJavaVersion >= JavaVersion.VERSION_20) {
+ sourceSets {
+ java20 {
+ java {
+ srcDirs = ['src/main/java20']
+ }
+ }
+ }
+
+ configurations {
+ java20Implementation.extendsFrom(implementation)
+ }
+
+ dependencies {
+ java20Implementation sourceSets.main.output
+ }
+
+ compileJava20Java {
+ targetCompatibility = JavaVersion.VERSION_20
+ options.compilerArgs += ['--add-modules', 'jdk.incubator.vector']
+ options.compilerArgs -= '-Werror' // use of incubator modules is reported as a warning
+ }
+
+ jar {
+ metaInf {
+ into 'versions/20'
+ from sourceSets.java20.output
+ }
+ manifest.attributes('Multi-Release': 'true')
+ }
+
+ tasks.withType(Test).configureEach {
+ // Relying on the convention for Test.classpath in custom Test tasks has been deprecated
+ // and scheduled to be removed in Gradle 9.0. Below lines are added from the migration guide:
+ // https://docs.gradle.org/8.5/userguide/upgrading_version_8.html#test_task_default_classpath
+ testClassesDirs = testing.suites.test.sources.output.classesDirs
+ classpath = testing.suites.test.sources.runtimeClasspath
+
+ // Adds the multi-release JAR to the classpath when executing tests.
+ // This allows newer sources to be picked up at test runtime (if supported).
+ classpath += files(jar.archiveFile)
+ // Removes the "main" sources from the classpath to avoid JarHell problems as
+ // the multi-release JAR already contains those classes.
+ classpath -= sourceSets.main.output
+ }
+
+ tasks.register('roundableSimdTest', Test) {
+ group 'verification'
+ include '**/RoundableTests.class'
+ systemProperty 'opensearch.experimental.feature.simd.rounding.enabled', 'forced'
+ }
+
+ check.dependsOn(roundableSimdTest)
+
+ forbiddenApisJava20 {
+ failOnMissingClasses = false
+ ignoreSignaturesOfMissingClasses = true
+ }
+}
diff --git a/libs/common/src/main/java/org/opensearch/bootstrap/JarHell.java b/libs/common/src/main/java/org/opensearch/bootstrap/JarHell.java
index c4ba778e7db86..fc5e364241d12 100644
--- a/libs/common/src/main/java/org/opensearch/bootstrap/JarHell.java
+++ b/libs/common/src/main/java/org/opensearch/bootstrap/JarHell.java
@@ -104,7 +104,7 @@ public static void checkJarHell(Consumer output) throws IOException, URI
/**
* Parses the classpath into an array of URLs
- * @return array of URLs
+ * @return collection of URLs
* @throws IllegalStateException if the classpath contains empty elements
*/
public static Set parseClassPath() {
@@ -114,7 +114,7 @@ public static Set parseClassPath() {
/**
* Parses the classpath into a set of URLs. For testing.
* @param classPath classpath to parse (typically the system property {@code java.class.path})
- * @return array of URLs
+ * @return collection of URLs
* @throws IllegalStateException if the classpath contains empty elements
*/
@SuppressForbidden(reason = "resolves against CWD because that is how classpaths work")
diff --git a/libs/common/src/main/java/org/opensearch/common/Booleans.java b/libs/common/src/main/java/org/opensearch/common/Booleans.java
index 2ca061820b2eb..ab7ad37e92612 100644
--- a/libs/common/src/main/java/org/opensearch/common/Booleans.java
+++ b/libs/common/src/main/java/org/opensearch/common/Booleans.java
@@ -45,30 +45,72 @@ private Booleans() {
/**
* Parses a char[] representation of a boolean value to boolean
.
*
- * @return true
iff the sequence of chars is "true", false
iff the sequence of chars is "false" or the
- * provided default value iff either text is null
or length == 0.
+ * @return true
iff the sequence of chars is "true", false
iff the sequence of
+ * chars is "false" or the provided default value iff either text is null
or length == 0.
* @throws IllegalArgumentException if the string cannot be parsed to boolean.
*/
public static boolean parseBoolean(char[] text, int offset, int length, boolean defaultValue) {
- if (text == null || length == 0) {
+ if (text == null) {
return defaultValue;
- } else {
- return parseBoolean(new String(text, offset, length));
}
+
+ switch (length) {
+ case 0:
+ return defaultValue;
+ case 1:
+ case 2:
+ case 3:
+ default:
+ break;
+ case 4:
+ if (text[offset] == 't' && text[offset + 1] == 'r' && text[offset + 2] == 'u' && text[offset + 3] == 'e') {
+ return true;
+ }
+ break;
+ case 5:
+ if (text[offset] == 'f'
+ && text[offset + 1] == 'a'
+ && text[offset + 2] == 'l'
+ && text[offset + 3] == 's'
+ && text[offset + 4] == 'e') {
+ return false;
+ }
+ break;
+ }
+
+ throw new IllegalArgumentException(
+ "Failed to parse value [" + new String(text, offset, length) + "] as only [true] or [false] are allowed."
+ );
}
/**
- * returns true iff the sequence of chars is one of "true","false".
+ * Returns true iff the sequence of chars is one of "true", "false".
*
* @param text sequence to check
* @param offset offset to start
* @param length length to check
*/
public static boolean isBoolean(char[] text, int offset, int length) {
- if (text == null || length == 0) {
+ if (text == null) {
return false;
}
- return isBoolean(new String(text, offset, length));
+
+ switch (length) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ default:
+ return false;
+ case 4:
+ return text[offset] == 't' && text[offset + 1] == 'r' && text[offset + 2] == 'u' && text[offset + 3] == 'e';
+ case 5:
+ return text[offset] == 'f'
+ && text[offset + 1] == 'a'
+ && text[offset + 2] == 'l'
+ && text[offset + 3] == 's'
+ && text[offset + 4] == 'e';
+ }
}
public static boolean isBoolean(String value) {
@@ -91,63 +133,45 @@ public static boolean parseBoolean(String value) {
throw new IllegalArgumentException("Failed to parse value [" + value + "] as only [true] or [false] are allowed.");
}
- private static boolean hasText(CharSequence str) {
- if (str == null || str.length() == 0) {
- return false;
- }
- int strLen = str.length();
- for (int i = 0; i < strLen; i++) {
- if (!Character.isWhitespace(str.charAt(i))) {
- return true;
- }
- }
- return false;
- }
-
/**
+ * Parses a string representation of a boolean value to boolean
.
+ * Note the subtle difference between this and {@link #parseBoolean(char[], int, int, boolean)}; this returns the
+ * default value even when the value is non-zero length containing all whitespaces (possibly overlooked, but
+ * preserving this behavior for compatibility reasons). Use {@link #parseBooleanStrict(String, boolean)} instead.
*
* @param value text to parse.
- * @param defaultValue The default value to return if the provided value is null
.
+ * @param defaultValue The default value to return if the provided value is null
or blank.
* @return see {@link #parseBoolean(String)}
*/
+ @Deprecated
public static boolean parseBoolean(String value, boolean defaultValue) {
- if (hasText(value)) {
- return parseBoolean(value);
- }
- return defaultValue;
- }
-
- public static Boolean parseBoolean(String value, Boolean defaultValue) {
- if (hasText(value)) {
- return parseBoolean(value);
+ if (value == null || value.isBlank()) {
+ return defaultValue;
}
- return defaultValue;
+ return parseBoolean(value);
}
- /**
- * Returns {@code false} if text is in "false", "0", "off", "no"; else, {@code true}.
- *
- * @deprecated Only kept to provide automatic upgrades for pre 6.0 indices. Use {@link #parseBoolean(String, Boolean)} instead.
- */
@Deprecated
- public static Boolean parseBooleanLenient(String value, Boolean defaultValue) {
- if (value == null) { // only for the null case we do that here!
+ public static Boolean parseBoolean(String value, Boolean defaultValue) {
+ if (value == null || value.isBlank()) {
return defaultValue;
}
- return parseBooleanLenient(value, false);
+ return parseBoolean(value);
}
/**
- * Returns {@code false} if text is in "false", "0", "off", "no"; else, {@code true}.
+ * Parses a string representation of a boolean value to boolean
.
+ * Analogous to {@link #parseBoolean(char[], int, int, boolean)}.
*
- * @deprecated Only kept to provide automatic upgrades for pre 6.0 indices. Use {@link #parseBoolean(String, boolean)} instead.
+ * @return true
iff the sequence of chars is "true", false
iff the sequence of
+ * chars is "false", or the provided default value iff either text is null
or length == 0.
+ * @throws IllegalArgumentException if the string cannot be parsed to boolean.
*/
- @Deprecated
- public static boolean parseBooleanLenient(String value, boolean defaultValue) {
- if (value == null) {
+ public static boolean parseBooleanStrict(String value, boolean defaultValue) {
+ if (value == null || value.length() == 0) {
return defaultValue;
}
- return !(value.equals("false") || value.equals("0") || value.equals("off") || value.equals("no"));
+ return parseBoolean(value);
}
/**
@@ -163,71 +187,4 @@ public static boolean isFalse(String value) {
public static boolean isTrue(String value) {
return "true".equals(value);
}
-
- /**
- * Returns {@code false} if text is in "false", "0", "off", "no"; else, {@code true}.
- *
- * @deprecated Only kept to provide automatic upgrades for pre 6.0 indices. Use {@link #parseBoolean(char[], int, int, boolean)} instead
- */
- @Deprecated
- public static boolean parseBooleanLenient(char[] text, int offset, int length, boolean defaultValue) {
- if (text == null || length == 0) {
- return defaultValue;
- }
- if (length == 1) {
- return text[offset] != '0';
- }
- if (length == 2) {
- return !(text[offset] == 'n' && text[offset + 1] == 'o');
- }
- if (length == 3) {
- return !(text[offset] == 'o' && text[offset + 1] == 'f' && text[offset + 2] == 'f');
- }
- if (length == 5) {
- return !(text[offset] == 'f'
- && text[offset + 1] == 'a'
- && text[offset + 2] == 'l'
- && text[offset + 3] == 's'
- && text[offset + 4] == 'e');
- }
- return true;
- }
-
- /**
- * returns true if the a sequence of chars is one of "true","false","on","off","yes","no","0","1"
- *
- * @param text sequence to check
- * @param offset offset to start
- * @param length length to check
- *
- * @deprecated Only kept to provide automatic upgrades for pre 6.0 indices. Use {@link #isBoolean(char[], int, int)} instead.
- */
- @Deprecated
- public static boolean isBooleanLenient(char[] text, int offset, int length) {
- if (text == null || length == 0) {
- return false;
- }
- if (length == 1) {
- return text[offset] == '0' || text[offset] == '1';
- }
- if (length == 2) {
- return (text[offset] == 'n' && text[offset + 1] == 'o') || (text[offset] == 'o' && text[offset + 1] == 'n');
- }
- if (length == 3) {
- return (text[offset] == 'o' && text[offset + 1] == 'f' && text[offset + 2] == 'f')
- || (text[offset] == 'y' && text[offset + 1] == 'e' && text[offset + 2] == 's');
- }
- if (length == 4) {
- return (text[offset] == 't' && text[offset + 1] == 'r' && text[offset + 2] == 'u' && text[offset + 3] == 'e');
- }
- if (length == 5) {
- return (text[offset] == 'f'
- && text[offset + 1] == 'a'
- && text[offset + 2] == 'l'
- && text[offset + 3] == 's'
- && text[offset + 4] == 'e');
- }
- return false;
- }
-
}
diff --git a/libs/common/src/main/java/org/opensearch/common/CheckedBiConsumer.java b/libs/common/src/main/java/org/opensearch/common/CheckedBiConsumer.java
index 50c15bb7a95a8..c2ef08e288346 100644
--- a/libs/common/src/main/java/org/opensearch/common/CheckedBiConsumer.java
+++ b/libs/common/src/main/java/org/opensearch/common/CheckedBiConsumer.java
@@ -32,13 +32,16 @@
package org.opensearch.common;
+import org.opensearch.common.annotation.PublicApi;
+
import java.util.function.BiConsumer;
/**
* A {@link BiConsumer}-like interface which allows throwing checked exceptions.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
@FunctionalInterface
public interface CheckedBiConsumer {
void accept(T t, U u) throws E;
diff --git a/libs/common/src/main/java/org/opensearch/common/CheckedConsumer.java b/libs/common/src/main/java/org/opensearch/common/CheckedConsumer.java
index dede06d0e207d..07b4973c3a340 100644
--- a/libs/common/src/main/java/org/opensearch/common/CheckedConsumer.java
+++ b/libs/common/src/main/java/org/opensearch/common/CheckedConsumer.java
@@ -32,6 +32,8 @@
package org.opensearch.common;
+import org.opensearch.common.annotation.PublicApi;
+
import java.util.function.Consumer;
/**
@@ -39,6 +41,7 @@
*
* @opensearch.api
*/
+@PublicApi(since = "1.0.0")
@FunctionalInterface
public interface CheckedConsumer {
void accept(T t) throws E;
diff --git a/libs/common/src/main/java/org/opensearch/common/CheckedFunction.java b/libs/common/src/main/java/org/opensearch/common/CheckedFunction.java
index 9c17ad4b4ee3f..927edd1b9905a 100644
--- a/libs/common/src/main/java/org/opensearch/common/CheckedFunction.java
+++ b/libs/common/src/main/java/org/opensearch/common/CheckedFunction.java
@@ -32,6 +32,8 @@
package org.opensearch.common;
+import org.opensearch.common.annotation.PublicApi;
+
import java.util.function.Function;
/**
@@ -39,6 +41,7 @@
*
* @opensearch.api
*/
+@PublicApi(since = "1.0.0")
@FunctionalInterface
public interface CheckedFunction {
R apply(T t) throws E;
diff --git a/libs/common/src/main/java/org/opensearch/common/Explicit.java b/libs/common/src/main/java/org/opensearch/common/Explicit.java
index 66e079c461e75..da44c6fd4dcef 100644
--- a/libs/common/src/main/java/org/opensearch/common/Explicit.java
+++ b/libs/common/src/main/java/org/opensearch/common/Explicit.java
@@ -32,19 +32,22 @@
package org.opensearch.common;
+import org.opensearch.common.annotation.PublicApi;
+
import java.util.Objects;
/**
* Holds a value that is either:
* a) set implicitly e.g. through some default value
* b) set explicitly e.g. from a user selection
- *
+ *
* When merging conflicting configuration settings such as
* field mapping settings it is preferable to preserve an explicit
* choice rather than a choice made only made implicitly by defaults.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class Explicit {
private final T value;
diff --git a/libs/common/src/main/java/org/opensearch/common/LocalTimeOffset.java b/libs/common/src/main/java/org/opensearch/common/LocalTimeOffset.java
index 7e89641927ed5..eb7b331c9aa24 100644
--- a/libs/common/src/main/java/org/opensearch/common/LocalTimeOffset.java
+++ b/libs/common/src/main/java/org/opensearch/common/LocalTimeOffset.java
@@ -514,7 +514,7 @@ public boolean anyMoveBackToPreviousDay() {
* Builds an array that can be {@link Arrays#binarySearch(long[], long)}ed
* for the daylight savings time transitions.
*
- * @openearch.internal
+ * @opensearch.internal
*/
private static class TransitionArrayLookup extends AbstractManyTransitionsLookup {
private final LocalTimeOffset[] offsets;
diff --git a/libs/common/src/main/java/org/opensearch/common/Nullable.java b/libs/common/src/main/java/org/opensearch/common/Nullable.java
index 804b339449147..70db2a3755eba 100644
--- a/libs/common/src/main/java/org/opensearch/common/Nullable.java
+++ b/libs/common/src/main/java/org/opensearch/common/Nullable.java
@@ -32,8 +32,11 @@
package org.opensearch.common;
+import org.opensearch.common.annotation.PublicApi;
+
import javax.annotation.CheckForNull;
import javax.annotation.meta.TypeQualifierNickname;
+
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
@@ -52,5 +55,6 @@
@CheckForNull
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.PARAMETER, ElementType.FIELD, ElementType.METHOD })
+@PublicApi(since = "1.0.0")
public @interface Nullable {
}
diff --git a/libs/common/src/main/java/org/opensearch/common/Numbers.java b/libs/common/src/main/java/org/opensearch/common/Numbers.java
index 084e52a41f8b1..d5a364a4a934e 100644
--- a/libs/common/src/main/java/org/opensearch/common/Numbers.java
+++ b/libs/common/src/main/java/org/opensearch/common/Numbers.java
@@ -260,4 +260,12 @@ public static double unsignedLongToDouble(long value) {
// want to replace that with 1 in the shifted value for correct rounding.
return (double) ((value >>> 1) | (value & 1)) * 2.0;
}
+
+ /**
+ * Return the strictly greater next power of two for the given value.
+ * For zero and negative numbers, it returns 1.
+ */
+ public static long nextPowerOfTwo(long value) {
+ return 1L << (Long.SIZE - Long.numberOfLeadingZeros(value));
+ }
}
diff --git a/libs/common/src/main/java/org/opensearch/common/SetOnce.java b/libs/common/src/main/java/org/opensearch/common/SetOnce.java
index a596b5fcdb61d..778926ce108b7 100644
--- a/libs/common/src/main/java/org/opensearch/common/SetOnce.java
+++ b/libs/common/src/main/java/org/opensearch/common/SetOnce.java
@@ -35,7 +35,7 @@
* A convenient class which offers a semi-immutable object wrapper implementation which allows one
* to set the value of an object exactly once, and retrieve it many times. If {@link #set(Object)}
* is called more than once, {@link AlreadySetException} is thrown and the operation will fail.
- *
+ *
* This is borrowed from lucene's experimental API. It is not reused to eliminate the dependency
* on lucene core for such a simple (standalone) utility class that may change beyond OpenSearch needs.
*
diff --git a/libs/common/src/main/java/org/opensearch/common/SuppressForbidden.java b/libs/common/src/main/java/org/opensearch/common/SuppressForbidden.java
index 1f1b28bcf6759..c479d7bd98e8a 100644
--- a/libs/common/src/main/java/org/opensearch/common/SuppressForbidden.java
+++ b/libs/common/src/main/java/org/opensearch/common/SuppressForbidden.java
@@ -31,6 +31,8 @@
package org.opensearch.common;
+import org.opensearch.common.annotation.PublicApi;
+
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@@ -43,6 +45,7 @@
*/
@Retention(RetentionPolicy.CLASS)
@Target({ ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE })
+@PublicApi(since = "1.0.0")
public @interface SuppressForbidden {
String reason();
}
diff --git a/libs/common/src/main/java/org/opensearch/common/TriFunction.java b/libs/common/src/main/java/org/opensearch/common/TriFunction.java
index 7b1bbece68680..8594e8e2cd0c9 100644
--- a/libs/common/src/main/java/org/opensearch/common/TriFunction.java
+++ b/libs/common/src/main/java/org/opensearch/common/TriFunction.java
@@ -32,6 +32,8 @@
package org.opensearch.common;
+import org.opensearch.common.annotation.PublicApi;
+
/**
* Represents a function that accepts three arguments and produces a result.
*
@@ -40,8 +42,9 @@
* @param the type of the third argument
* @param the return type
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
@FunctionalInterface
public interface TriFunction {
/**
diff --git a/server/src/main/java/org/opensearch/action/ActionFuture.java b/libs/common/src/main/java/org/opensearch/common/action/ActionFuture.java
similarity index 96%
rename from server/src/main/java/org/opensearch/action/ActionFuture.java
rename to libs/common/src/main/java/org/opensearch/common/action/ActionFuture.java
index d796180eda021..7f9dd096667e9 100644
--- a/server/src/main/java/org/opensearch/action/ActionFuture.java
+++ b/libs/common/src/main/java/org/opensearch/common/action/ActionFuture.java
@@ -30,8 +30,9 @@
* GitHub history for details.
*/
-package org.opensearch.action;
+package org.opensearch.common.action;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.common.unit.TimeValue;
import java.util.concurrent.Future;
@@ -42,6 +43,7 @@
*
* @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface ActionFuture extends Future {
/**
diff --git a/libs/common/src/main/java/org/opensearch/common/action/package-info.java b/libs/common/src/main/java/org/opensearch/common/action/package-info.java
new file mode 100644
index 0000000000000..4ed2687c80cc9
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/action/package-info.java
@@ -0,0 +1,10 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/** foundation action classes used across the code base */
+package org.opensearch.common.action;
diff --git a/libs/common/src/main/java/org/opensearch/common/annotation/DeprecatedApi.java b/libs/common/src/main/java/org/opensearch/common/annotation/DeprecatedApi.java
new file mode 100644
index 0000000000000..964380e1a26ce
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/annotation/DeprecatedApi.java
@@ -0,0 +1,42 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+
+/**
+ * Marks the public APIs as deprecated and scheduled for removal in one of the upcoming
+ * major releases. The types marked with this annotations could only be other {@link PublicApi}s.
+ *
+ * @opensearch.api
+ */
+@Documented
+@Target({
+ ElementType.TYPE,
+ ElementType.PACKAGE,
+ ElementType.METHOD,
+ ElementType.CONSTRUCTOR,
+ ElementType.PARAMETER,
+ ElementType.FIELD,
+ ElementType.ANNOTATION_TYPE,
+ ElementType.MODULE })
+@PublicApi(since = "2.10.0")
+public @interface DeprecatedApi {
+ /**
+ * Version since this API is deprecated
+ */
+ String since();
+
+ /**
+ * Next major version when this API is scheduled for removal
+ */
+ String forRemoval() default "";
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/annotation/ExperimentalApi.java b/libs/common/src/main/java/org/opensearch/common/annotation/ExperimentalApi.java
new file mode 100644
index 0000000000000..001ffd6eb720a
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/annotation/ExperimentalApi.java
@@ -0,0 +1,35 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+
+/**
+ * Experimental APIs that may not retain source and binary compatibility within major,
+ * minor or patch releases. The types marked with this annotations could only expose
+ * other {@link PublicApi} or {@link ExperimentalApi} types as public members.
+ *
+ * @opensearch.api
+ */
+@Documented
+@Target({
+ ElementType.TYPE,
+ ElementType.PACKAGE,
+ ElementType.METHOD,
+ ElementType.CONSTRUCTOR,
+ ElementType.PARAMETER,
+ ElementType.FIELD,
+ ElementType.ANNOTATION_TYPE,
+ ElementType.MODULE })
+@PublicApi(since = "2.10.0")
+public @interface ExperimentalApi {
+
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/annotation/InternalApi.java b/libs/common/src/main/java/org/opensearch/common/annotation/InternalApi.java
new file mode 100644
index 0000000000000..ae58c49e58c5e
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/annotation/InternalApi.java
@@ -0,0 +1,34 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+
+/**
+ * Internal APIs that have no compatibility guarantees and should be not used outside
+ * of OpenSearch core components.
+ *
+ * @opensearch.api
+ */
+@Documented
+@Target({
+ ElementType.TYPE,
+ ElementType.PACKAGE,
+ ElementType.METHOD,
+ ElementType.CONSTRUCTOR,
+ ElementType.PARAMETER,
+ ElementType.FIELD,
+ ElementType.ANNOTATION_TYPE,
+ ElementType.MODULE })
+@PublicApi(since = "2.10.0")
+public @interface InternalApi {
+
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/annotation/PublicApi.java b/libs/common/src/main/java/org/opensearch/common/annotation/PublicApi.java
new file mode 100644
index 0000000000000..33862446d6442
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/annotation/PublicApi.java
@@ -0,0 +1,39 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+
+/**
+ * Stable public APIs that retain source and binary compatibility within a major release.
+ * These interfaces can change from one major release to another major release
+ * (e.g. from 1.0 to 2.0). The types marked with this annotations could only expose
+ * other {@link PublicApi} or {@link ExperimentalApi} types as public members.
+ *
+ * @opensearch.api
+ */
+@Documented
+@Target({
+ ElementType.TYPE,
+ ElementType.PACKAGE,
+ ElementType.METHOD,
+ ElementType.CONSTRUCTOR,
+ ElementType.PARAMETER,
+ ElementType.FIELD,
+ ElementType.ANNOTATION_TYPE,
+ ElementType.MODULE })
+@PublicApi(since = "2.10.0")
+public @interface PublicApi {
+ /**
+ * Version when this API was released
+ */
+ String since();
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/annotation/package-info.java b/libs/common/src/main/java/org/opensearch/common/annotation/package-info.java
new file mode 100644
index 0000000000000..7bb79d7579747
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/annotation/package-info.java
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * The OpenSearch API related annotations
+ *
+ * @opensearch.api
+ */
+@PublicApi(since = "2.10.0")
+package org.opensearch.common.annotation;
diff --git a/libs/common/src/main/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessor.java b/libs/common/src/main/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessor.java
new file mode 100644
index 0000000000000..569f48a8465f3
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessor.java
@@ -0,0 +1,369 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.Nullable;
+import org.opensearch.common.annotation.DeprecatedApi;
+import org.opensearch.common.annotation.ExperimentalApi;
+import org.opensearch.common.annotation.InternalApi;
+import org.opensearch.common.annotation.PublicApi;
+
+import javax.annotation.processing.AbstractProcessor;
+import javax.annotation.processing.RoundEnvironment;
+import javax.annotation.processing.SupportedAnnotationTypes;
+import javax.lang.model.AnnotatedConstruct;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.AnnotationMirror;
+import javax.lang.model.element.Element;
+import javax.lang.model.element.ElementKind;
+import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.Modifier;
+import javax.lang.model.element.PackageElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.element.TypeParameterElement;
+import javax.lang.model.element.VariableElement;
+import javax.lang.model.type.ArrayType;
+import javax.lang.model.type.DeclaredType;
+import javax.lang.model.type.ReferenceType;
+import javax.lang.model.type.TypeMirror;
+import javax.lang.model.type.TypeVariable;
+import javax.lang.model.type.WildcardType;
+import javax.tools.Diagnostic.Kind;
+
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * The annotation processor for API related annotations: {@link DeprecatedApi}, {@link ExperimentalApi},
+ * {@link InternalApi} and {@link PublicApi}.
+ *
+ * The checks are built on top of the following rules:
+ *
+ * introspect each type annotated with {@link PublicApi}, {@link DeprecatedApi} or {@link ExperimentalApi},
+ * filtering out package-private declarations
+ * make sure those leak only {@link PublicApi}, {@link DeprecatedApi} or {@link ExperimentalApi} types as well (exceptions,
+ * method return values, method arguments, method generic type arguments, class generic type arguments, annotations)
+ * recursively follow the type introspection chains to enforce the rules down the line
+ *
+ */
+@InternalApi
+@SupportedAnnotationTypes("org.opensearch.common.annotation.*")
+public class ApiAnnotationProcessor extends AbstractProcessor {
+ private static final String OPTION_CONTINUE_ON_FAILING_CHECKS = "continueOnFailingChecks";
+ private static final String OPENSEARCH_PACKAGE = "org.opensearch";
+
+ private final Set reported = new HashSet<>();
+ private final Set processed = new HashSet<>();
+ private Kind reportFailureAs = Kind.ERROR;
+
+ @Override
+ public SourceVersion getSupportedSourceVersion() {
+ return SourceVersion.latest();
+ }
+
+ @Override
+ public Set getSupportedOptions() {
+ return Set.of(OPTION_CONTINUE_ON_FAILING_CHECKS);
+ }
+
+ @Override
+ public boolean process(Set extends TypeElement> annotations, RoundEnvironment round) {
+ processingEnv.getMessager().printMessage(Kind.NOTE, "Processing OpenSearch Api annotations");
+
+ if (processingEnv.getOptions().containsKey(OPTION_CONTINUE_ON_FAILING_CHECKS) == true) {
+ reportFailureAs = Kind.NOTE;
+ }
+
+ final Set extends Element> elements = round.getElementsAnnotatedWithAny(
+ Set.of(PublicApi.class, ExperimentalApi.class, DeprecatedApi.class)
+ );
+
+ for (var element : elements) {
+ if (!checkPackage(element)) {
+ continue;
+ }
+
+ // Skip all not-public elements
+ checkPublicVisibility(null, element);
+
+ if (element instanceof TypeElement) {
+ process((TypeElement) element);
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Check top level executable element
+ * @param executable top level executable element
+ * @param enclosing enclosing element
+ */
+ private void process(ExecutableElement executable, Element enclosing) {
+ if (!inspectable(executable)) {
+ return;
+ }
+
+ // The executable element should not be internal (unless constructor for injectable core component)
+ checkNotInternal(enclosing, executable);
+
+ // Check this element's annotations
+ for (final AnnotationMirror annotation : executable.getAnnotationMirrors()) {
+ final Element element = annotation.getAnnotationType().asElement();
+ if (inspectable(element)) {
+ checkNotInternal(executable.getEnclosingElement(), element);
+ checkPublic(executable.getEnclosingElement(), element);
+ }
+ }
+
+ // Process method return types
+ final TypeMirror returnType = executable.getReturnType();
+ if (returnType instanceof ReferenceType) {
+ process(executable, (ReferenceType) returnType);
+ }
+
+ // Process method thrown types
+ for (final TypeMirror thrownType : executable.getThrownTypes()) {
+ if (thrownType instanceof ReferenceType) {
+ process(executable, (ReferenceType) thrownType);
+ }
+ }
+
+ // Process method type parameters
+ for (final TypeParameterElement typeParameter : executable.getTypeParameters()) {
+ for (final TypeMirror boundType : typeParameter.getBounds()) {
+ if (boundType instanceof ReferenceType) {
+ process(executable, (ReferenceType) boundType);
+ }
+ }
+ }
+
+ // Process method arguments
+ for (final VariableElement parameter : executable.getParameters()) {
+ final TypeMirror parameterType = parameter.asType();
+ if (parameterType instanceof ReferenceType) {
+ process(executable, (ReferenceType) parameterType);
+ }
+ }
+ }
+
+ /**
+ * Check wildcard type bounds referred by an element
+ * @param executable element
+ * @param type wildcard type
+ */
+ private void process(ExecutableElement executable, WildcardType type) {
+ if (type.getExtendsBound() instanceof ReferenceType) {
+ process(executable, (ReferenceType) type.getExtendsBound());
+ }
+
+ if (type.getSuperBound() instanceof ReferenceType) {
+ process(executable, (ReferenceType) type.getSuperBound());
+ }
+ }
+
+ /**
+ * Check reference type bounds referred by an executable element
+ * @param executable executable element
+ * @param ref reference type
+ */
+ private void process(ExecutableElement executable, ReferenceType ref) {
+ // The element has been processed already
+ if (processed.add(ref) == false) {
+ return;
+ }
+
+ if (ref instanceof DeclaredType) {
+ final DeclaredType declaredType = (DeclaredType) ref;
+
+ final Element element = declaredType.asElement();
+ if (inspectable(element)) {
+ checkNotInternal(executable.getEnclosingElement(), element);
+ checkPublic(executable.getEnclosingElement(), element);
+ }
+
+ for (final TypeMirror type : declaredType.getTypeArguments()) {
+ if (type instanceof ReferenceType) {
+ process(executable, (ReferenceType) type);
+ } else if (type instanceof WildcardType) {
+ process(executable, (WildcardType) type);
+ }
+ }
+ } else if (ref instanceof ArrayType) {
+ final TypeMirror componentType = ((ArrayType) ref).getComponentType();
+ if (componentType instanceof ReferenceType) {
+ process(executable, (ReferenceType) componentType);
+ }
+ } else if (ref instanceof TypeVariable) {
+ final TypeVariable typeVariable = (TypeVariable) ref;
+ if (typeVariable.getUpperBound() instanceof ReferenceType) {
+ process(executable, (ReferenceType) typeVariable.getUpperBound());
+ }
+ if (typeVariable.getLowerBound() instanceof ReferenceType) {
+ process(executable, (ReferenceType) typeVariable.getLowerBound());
+ }
+ }
+
+ // Check this element's annotations
+ for (final AnnotationMirror annotation : ref.getAnnotationMirrors()) {
+ final Element element = annotation.getAnnotationType().asElement();
+ if (inspectable(element)) {
+ checkNotInternal(executable.getEnclosingElement(), element);
+ checkPublic(executable.getEnclosingElement(), element);
+ }
+ }
+ }
+
+ /**
+ * Check if a particular executable element should be inspected or not
+ * @param executable executable element to inspect
+ * @return {@code true} if a particular executable element should be inspected, {@code false} otherwise
+ */
+ private boolean inspectable(ExecutableElement executable) {
+ // The constructors for public APIs could use non-public APIs when those are supposed to be only
+ // consumed (not instantiated) by external consumers.
+ return executable.getKind() != ElementKind.CONSTRUCTOR && executable.getModifiers().contains(Modifier.PUBLIC);
+ }
+
+ /**
+ * Check if a particular element should be inspected or not
+ * @param element element to inspect
+ * @return {@code true} if a particular element should be inspected, {@code false} otherwise
+ */
+ private boolean inspectable(Element element) {
+ final PackageElement pckg = processingEnv.getElementUtils().getPackageOf(element);
+ return pckg.getQualifiedName().toString().startsWith(OPENSEARCH_PACKAGE);
+ }
+
+ /**
+ * Check if a particular element belongs to OpenSeach managed packages
+ * @param element element to inspect
+ * @return {@code true} if a particular element belongs to OpenSeach managed packages, {@code false} otherwise
+ */
+ private boolean checkPackage(Element element) {
+ // The element was reported already
+ if (reported.contains(element)) {
+ return false;
+ }
+
+ final PackageElement pckg = processingEnv.getElementUtils().getPackageOf(element);
+ final boolean belongsToOpenSearch = pckg.getQualifiedName().toString().startsWith(OPENSEARCH_PACKAGE);
+
+ if (!belongsToOpenSearch) {
+ reported.add(element);
+
+ processingEnv.getMessager()
+ .printMessage(
+ reportFailureAs,
+ "The type "
+ + element
+ + " is not residing in "
+ + OPENSEARCH_PACKAGE
+ + ".* package "
+ + "and should not be annotated as OpenSearch APIs."
+ );
+ }
+
+ return belongsToOpenSearch;
+ }
+
+ /**
+ * Check the fields, methods, constructors, and member types that are directly
+ * declared in this class or interface.
+ * @param element class or interface
+ */
+ private void process(Element element) {
+ // Check the fields, methods, constructors, and member types that are directly
+ // declared in this class or interface.
+ for (final Element enclosed : element.getEnclosedElements()) {
+ // Skip all not-public elements
+ if (!enclosed.getModifiers().contains(Modifier.PUBLIC)) {
+ continue;
+ }
+
+ if (enclosed instanceof ExecutableElement) {
+ process((ExecutableElement) enclosed, element);
+ }
+ }
+ }
+
+ /**
+ * Check if element is public and annotated with {@link PublicApi}, {@link DeprecatedApi} or {@link ExperimentalApi}
+ * @param referencedBy the referrer for the element
+ * @param element element to check
+ */
+ private void checkPublic(@Nullable Element referencedBy, final Element element) {
+ // The element was reported already
+ if (reported.contains(element)) {
+ return;
+ }
+
+ checkPublicVisibility(referencedBy, element);
+
+ if (element.getAnnotation(PublicApi.class) == null
+ && element.getAnnotation(ExperimentalApi.class) == null
+ && element.getAnnotation(DeprecatedApi.class) == null) {
+ reported.add(element);
+
+ processingEnv.getMessager()
+ .printMessage(
+ reportFailureAs,
+ "The element "
+ + element
+ + " is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi"
+ + ((referencedBy != null) ? " (referenced by " + referencedBy + ") " : "")
+ );
+ }
+ }
+
+ /**
+ * Check if element has public visibility (following Java visibility rules)
+ * @param referencedBy the referrer for the element
+ * @param element element to check
+ */
+ private void checkPublicVisibility(Element referencedBy, final Element element) {
+ if (!element.getModifiers().contains(Modifier.PUBLIC) && !element.getModifiers().contains(Modifier.PROTECTED)) {
+ reported.add(element);
+
+ processingEnv.getMessager()
+ .printMessage(
+ reportFailureAs,
+ "The element "
+ + element
+ + " is part of the public APIs but does not have public or protected visibility"
+ + ((referencedBy != null) ? " (referenced by " + referencedBy + ") " : "")
+ );
+ }
+ }
+
+ /**
+ * Check if element is not annotated with {@link InternalApi}
+ * @param referencedBy the referrer for the element
+ * @param element element to check
+ */
+ private void checkNotInternal(@Nullable Element referencedBy, final Element element) {
+ // The element was reported already
+ if (reported.contains(element)) {
+ return;
+ }
+
+ if (element.getAnnotation(InternalApi.class) != null) {
+ reported.add(element);
+
+ processingEnv.getMessager()
+ .printMessage(
+ reportFailureAs,
+ "The element "
+ + element
+ + " is part of the public APIs but is marked as @InternalApi"
+ + ((referencedBy != null) ? " (referenced by " + referencedBy + ") " : "")
+ );
+ }
+ }
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/annotation/processor/package-info.java b/libs/common/src/main/java/org/opensearch/common/annotation/processor/package-info.java
new file mode 100644
index 0000000000000..fa23e4a7addce
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/annotation/processor/package-info.java
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Classes related yo OpenSearch API annotation processing
+ *
+ * @opensearch.internal
+ */
+@org.opensearch.common.annotation.InternalApi
+package org.opensearch.common.annotation.processor;
diff --git a/server/src/main/java/org/opensearch/common/collect/Iterators.java b/libs/common/src/main/java/org/opensearch/common/collect/Iterators.java
similarity index 78%
rename from server/src/main/java/org/opensearch/common/collect/Iterators.java
rename to libs/common/src/main/java/org/opensearch/common/collect/Iterators.java
index c7e7ae6a44a21..9b64932356c10 100644
--- a/server/src/main/java/org/opensearch/common/collect/Iterators.java
+++ b/libs/common/src/main/java/org/opensearch/common/collect/Iterators.java
@@ -41,6 +41,15 @@
* @opensearch.internal
*/
public class Iterators {
+
+ /**
+ * Concat iterators
+ *
+ * @param iterators the iterators to concat
+ * @param the type of iterator
+ * @return a new {@link ConcatenatedIterator}
+ * @throws NullPointerException if iterators is null
+ */
public static Iterator concat(Iterator extends T>... iterators) {
if (iterators == null) {
throw new NullPointerException("iterators");
@@ -71,6 +80,11 @@ static class ConcatenatedIterator implements Iterator {
this.iterators = iterators;
}
+ /**
+ * Returns {@code true} if the iteration has more elements. (In other words, returns {@code true} if {@link #next} would return an
+ * element rather than throwing an exception.)
+ * @return {@code true} if the iteration has more elements
+ */
@Override
public boolean hasNext() {
boolean hasNext = false;
@@ -81,6 +95,11 @@ public boolean hasNext() {
return hasNext;
}
+ /**
+ * Returns the next element in the iteration.
+ * @return the next element in the iteration
+ * @throws NoSuchElementException if the iteration has no more elements
+ */
@Override
public T next() {
if (!hasNext()) {
diff --git a/libs/common/src/main/java/org/opensearch/common/collect/Tuple.java b/libs/common/src/main/java/org/opensearch/common/collect/Tuple.java
index 36bc5504061f5..a5d97dcd85ef7 100644
--- a/libs/common/src/main/java/org/opensearch/common/collect/Tuple.java
+++ b/libs/common/src/main/java/org/opensearch/common/collect/Tuple.java
@@ -32,13 +32,15 @@
package org.opensearch.common.collect;
+import org.opensearch.common.annotation.PublicApi;
+
/**
* Java 9 Tuple
- *
* todo: deprecate and remove w/ min jdk upgrade to 11?
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class Tuple {
public static Tuple tuple(V1 v1, V2 v2) {
@@ -61,6 +63,20 @@ public V2 v2() {
return v2;
}
+ /**
+ * Returns {@code true} if the given object is also a tuple and the two tuples
+ * have equal {@link #v1()} and {@link #v2()} values.
+ *
+ * Returns {@code false} otherwise, including for {@code null} values or
+ * objects of different types.
+ *
+ * Note: {@code Tuple} instances are equal if the underlying values are
+ * equal, even if the types are different.
+ *
+ * @param o the object to compare to
+ * @return {@code true} if the given object is also a tuple and the two tuples
+ * have equal {@link #v1()} and {@link #v2()} values.
+ */
@Override
public boolean equals(Object o) {
if (this == o) return true;
@@ -74,6 +90,10 @@ public boolean equals(Object o) {
return true;
}
+ /**
+ * Returns the hash code value for this Tuple.
+ * @return the hash code value for this Tuple.
+ */
@Override
public int hashCode() {
int result = v1 != null ? v1.hashCode() : 0;
@@ -81,6 +101,10 @@ public int hashCode() {
return result;
}
+ /**
+ * Returns a string representation of a Tuple
+ * @return {@code "Tuple [v1=value1, v2=value2]"}
+ */
@Override
public String toString() {
return "Tuple [v1=" + v1 + ", v2=" + v2 + "]";
diff --git a/libs/common/src/main/java/org/opensearch/common/crypto/CryptoHandler.java b/libs/common/src/main/java/org/opensearch/common/crypto/CryptoHandler.java
new file mode 100644
index 0000000000000..9572b5b9054b2
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/crypto/CryptoHandler.java
@@ -0,0 +1,118 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.crypto;
+
+import org.opensearch.common.annotation.ExperimentalApi;
+import org.opensearch.common.io.InputStreamContainer;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Crypto provider abstractions for encryption and decryption of data. Allows registering multiple providers
+ * for defining different ways of encrypting or decrypting data.
+ *
+ * @param Encryption Metadata / CryptoContext
+ * @param Parsed Encryption Metadata / CryptoContext
+ */
+@ExperimentalApi
+public interface CryptoHandler extends Closeable {
+
+ /**
+ * To initialise or create a new crypto metadata to be used in encryption. This is needed to set the context before
+ * beginning encryption.
+ *
+ * @return crypto metadata instance
+ */
+ T initEncryptionMetadata();
+
+ /**
+ * To load crypto metadata to be used in encryption from content header.
+ * Note that underlying information in the loaded metadata object is same as present in the object created during
+ * encryption but object type may differ.
+ *
+ * @param encryptedHeaderContentSupplier supplier for encrypted header content.
+ * @return crypto metadata instance used in decryption.
+ */
+ U loadEncryptionMetadata(EncryptedHeaderContentSupplier encryptedHeaderContentSupplier) throws IOException;
+
+ /**
+ * Few encryption algorithms have certain conditions on the unit of content to be encrypted. This requires the
+ * content size to be re adjusted in order to fulfil these conditions for partial writes. If write requests for
+ * encryption of a part of content do not fulfil these conditions then encryption fails or can result in corrupted
+ * content depending on the algorithm used. This method exposes a means to re-adjust sizes of such writes.
+ *
+ * @param cryptoContext crypto metadata instance
+ * @param contentSize Size of the raw content
+ * @return Adjusted size of the content.
+ */
+ long adjustContentSizeForPartialEncryption(T cryptoContext, long contentSize);
+
+ /**
+ * Estimate length of the encrypted content. It should only be used to determine length of entire content after
+ * encryption.
+ *
+ * @param cryptoContext crypto metadata instance consisting of encryption metadata used in encryption.
+ * @param contentLength Size of the raw content
+ * @return Calculated size of the encrypted content.
+ */
+ long estimateEncryptedLengthOfEntireContent(T cryptoContext, long contentLength);
+
+ /**
+ * For given encrypted content length, estimate the length of the decrypted content.
+ * @param cryptoContext crypto metadata instance consisting of encryption metadata used in encryption.
+ * @param contentLength Size of the encrypted content
+ * @return Calculated size of the decrypted content.
+ */
+ long estimateDecryptedLength(U cryptoContext, long contentLength);
+
+ /**
+ * Wraps a raw InputStream with encrypting stream
+ *
+ * @param encryptionMetadata created earlier to set the crypto metadata.
+ * @param stream Raw InputStream to encrypt
+ * @return encrypting stream wrapped around raw InputStream.
+ */
+ InputStreamContainer createEncryptingStream(T encryptionMetadata, InputStreamContainer stream);
+
+ /**
+ * Provides encrypted stream for a raw stream emitted for a part of content.
+ *
+ * @param cryptoContext crypto metadata instance.
+ * @param stream raw stream for which encrypted stream has to be created.
+ * @param totalStreams Number of streams being used for the entire content.
+ * @param streamIdx Index of the current stream.
+ * @return Encrypted stream for the provided raw stream.
+ */
+ InputStreamContainer createEncryptingStreamOfPart(T cryptoContext, InputStreamContainer stream, int totalStreams, int streamIdx);
+
+ /**
+ * This method accepts an encrypted stream and provides a decrypting wrapper.
+ * @param encryptingStream to be decrypted.
+ * @return Decrypting wrapper stream
+ */
+ InputStream createDecryptingStream(InputStream encryptingStream);
+
+ /**
+ * This method creates a {@link DecryptedRangedStreamProvider} which provides a wrapped stream to decrypt the
+ * underlying stream. This also provides adjusted range against the actual range which should be used for fetching
+ * and supplying the encrypted content for decryption. Extra content outside the range is trimmed down and returned
+ * by the decrypted stream.
+ * For partial reads of encrypted content, few algorithms require the range of content to be adjusted for
+ * successful decryption. Adjusted range may or may not be same as the provided range. If range is adjusted then
+ * starting offset of resultant range can be lesser than the starting offset of provided range and end
+ * offset can be greater than the ending offset of the provided range.
+ *
+ * @param cryptoContext crypto metadata instance.
+ * @param startPosOfRawContent starting position in the raw/decrypted content
+ * @param endPosOfRawContent ending position in the raw/decrypted content
+ */
+ DecryptedRangedStreamProvider createDecryptingStreamOfRange(U cryptoContext, long startPosOfRawContent, long endPosOfRawContent);
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/crypto/DataKeyPair.java b/libs/common/src/main/java/org/opensearch/common/crypto/DataKeyPair.java
new file mode 100644
index 0000000000000..711c0d314ecef
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/crypto/DataKeyPair.java
@@ -0,0 +1,45 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+package org.opensearch.common.crypto;
+
+/**
+ * Key pair generated by {@link MasterKeyProvider}
+ */
+public class DataKeyPair {
+
+ /** Unencrypted data key used for encryption and decryption */
+ private final byte[] rawKey;
+ /** Encrypted version of rawKey */
+ private final byte[] encryptedKey;
+
+ /**
+ * Constructor to initialize key-pair values
+ * @param rawKey Unencrypted data key used for encryption and decryption
+ * @param encryptedKey Encrypted version of rawKey
+ */
+ public DataKeyPair(byte[] rawKey, byte[] encryptedKey) {
+ this.rawKey = rawKey;
+ this.encryptedKey = encryptedKey;
+ }
+
+ /**
+ * Returns Unencrypted data key
+ * @return raw/decrypted key
+ */
+ public byte[] getRawKey() {
+ return rawKey;
+ }
+
+ /**
+ * Returns encrypted key
+ * @return encrypted key
+ */
+ public byte[] getEncryptedKey() {
+ return encryptedKey;
+ }
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/crypto/DecryptedRangedStreamProvider.java b/libs/common/src/main/java/org/opensearch/common/crypto/DecryptedRangedStreamProvider.java
new file mode 100644
index 0000000000000..2cda3c1f8bdb4
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/crypto/DecryptedRangedStreamProvider.java
@@ -0,0 +1,51 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.crypto;
+
+import java.io.InputStream;
+import java.util.function.UnaryOperator;
+
+/**
+ * Contains adjusted range of partial encrypted content which needs to be used for decryption.
+ */
+public class DecryptedRangedStreamProvider {
+
+ /** Adjusted range of partial encrypted content which needs to be used for decryption. */
+ private final long[] adjustedRange;
+ /** Stream provider for decryption and range re-adjustment. */
+ private final UnaryOperator decryptedStreamProvider;
+
+ /**
+ * To construct adjusted encrypted range.
+ * @param adjustedRange range of partial encrypted content which needs to be used for decryption.
+ * @param decryptedStreamProvider stream provider for decryption and range re-adjustment.
+ */
+ public DecryptedRangedStreamProvider(long[] adjustedRange, UnaryOperator decryptedStreamProvider) {
+ this.adjustedRange = adjustedRange;
+ this.decryptedStreamProvider = decryptedStreamProvider;
+ }
+
+ /**
+ * Adjusted range of partial encrypted content which needs to be used for decryption.
+ * @return adjusted range
+ */
+ public long[] getAdjustedRange() {
+ return adjustedRange;
+ }
+
+ /**
+ * A utility stream provider which supplies the stream responsible for decrypting the content and reading the
+ * desired range of decrypted content by skipping extra content which got decrypted as a result of range adjustment.
+ * @return stream provider for decryption and supplying the desired range of content.
+ */
+ public UnaryOperator getDecryptedStreamProvider() {
+ return decryptedStreamProvider;
+ }
+
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/crypto/EncryptedHeaderContentSupplier.java b/libs/common/src/main/java/org/opensearch/common/crypto/EncryptedHeaderContentSupplier.java
new file mode 100644
index 0000000000000..49a037f05f185
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/crypto/EncryptedHeaderContentSupplier.java
@@ -0,0 +1,25 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+package org.opensearch.common.crypto;
+
+import java.io.IOException;
+
+/**
+ * This is used in partial decryption. Header information is required for decryption of actual encrypted content.
+ * Implementation of this supplier only requires first few bytes of encrypted content to be supplied.
+ */
+public interface EncryptedHeaderContentSupplier {
+
+ /**
+ * @param start Start position of the encrypted content (Generally supplied as 0 during usage)
+ * @param end End position of the header.
+ * @return Encrypted header content (May contain additional content which is later discarded)
+ * @throws IOException In case content fetch fails.
+ */
+ byte[] supply(long start, long end) throws IOException;
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/crypto/MasterKeyProvider.java b/libs/common/src/main/java/org/opensearch/common/crypto/MasterKeyProvider.java
new file mode 100644
index 0000000000000..31d2dcd0dba3d
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/crypto/MasterKeyProvider.java
@@ -0,0 +1,47 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+package org.opensearch.common.crypto;
+
+import org.opensearch.common.annotation.ExperimentalApi;
+
+import java.io.Closeable;
+import java.util.Map;
+
+/**
+ * Master key provider responsible for management of master keys.
+ *
+ * @opensearch.experimental
+ */
+@ExperimentalApi
+public interface MasterKeyProvider extends Closeable {
+
+ /**
+ * Returns data key pair
+ * @return data key pair generated by master key.
+ */
+ DataKeyPair generateDataPair();
+
+ /**
+ * Returns decrypted key against the encrypted key.
+ * @param encryptedKey Key to decrypt
+ * @return Decrypted version of key.
+ */
+ byte[] decryptKey(byte[] encryptedKey);
+
+ /**
+ * Returns key id.
+ * @return key id
+ */
+ String getKeyId();
+
+ /**
+ * Returns encryption context associated with this master key.
+ * @return encryption context associated with this master key.
+ */
+ Map getEncryptionContext();
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/crypto/package-info.java b/libs/common/src/main/java/org/opensearch/common/crypto/package-info.java
new file mode 100644
index 0000000000000..c744689ebf532
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/crypto/package-info.java
@@ -0,0 +1,10 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/** Common crypto utilities used across opensearch. */
+package org.opensearch.common.crypto;
diff --git a/libs/common/src/main/java/org/opensearch/common/hash/T1ha1.java b/libs/common/src/main/java/org/opensearch/common/hash/T1ha1.java
new file mode 100644
index 0000000000000..07b2306eda4e5
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/hash/T1ha1.java
@@ -0,0 +1,277 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.hash;
+
+import org.opensearch.common.annotation.InternalApi;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.lang.invoke.VarHandle;
+import java.nio.ByteOrder;
+
+import static java.lang.Long.rotateRight;
+
+/**
+ * t1ha: Fast Positive Hash
+ *
+ *
+ * Implements t1ha1 ;
+ * a fast portable hash function with reasonable quality for checksums, hash tables, and thin fingerprinting.
+ *
+ *
+ * To overcome language and performance limitations, this implementation differs slightly from the
+ * reference implementation in C++,
+ * so the returned values may vary before JDK 18.
+ *
+ *
+ * Intended for little-endian systems but returns the same result on big-endian, albeit marginally slower.
+ *
+ * @opensearch.internal
+ */
+@InternalApi
+public final class T1ha1 {
+ private static final long SEED = System.nanoTime();
+ private static final Mux64 MUX_64_IMPL = fastestMux64Impl();
+
+ private static final VarHandle LONG_HANDLE = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.LITTLE_ENDIAN);
+ private static final VarHandle INT_HANDLE = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN);
+ private static final VarHandle SHORT_HANDLE = MethodHandles.byteArrayViewVarHandle(short[].class, ByteOrder.LITTLE_ENDIAN);
+
+ // "Magic" primes:
+ private static final long p0 = 0xEC99BF0D8372CAABL;
+ private static final long p1 = 0x82434FE90EDCEF39L;
+ private static final long p2 = 0xD4F06DB99D67BE4BL;
+ private static final long p3 = 0xBD9CACC22C6E9571L;
+ private static final long p4 = 0x9C06FAF4D023E3ABL;
+ private static final long p5 = 0xC060724A8424F345L;
+ private static final long p6 = 0xCB5AF53AE3AAAC31L;
+
+ // Rotations:
+ private static final int s0 = 41;
+ private static final int s1 = 17;
+ private static final int s2 = 31;
+
+ /**
+ * No public constructor.
+ */
+ private T1ha1() {}
+
+ /**
+ * Returns the hash code for the specified range of the given {@code byte} array.
+ * @param input the input byte array
+ * @param offset the starting offset
+ * @param length the length of the range
+ * @return hash code
+ */
+ public static long hash(byte[] input, int offset, int length) {
+ return hash(input, offset, length, SEED);
+ }
+
+ /**
+ * Returns the hash code for the specified range of the given {@code byte} array.
+ * @param input the input byte array
+ * @param offset the starting offset
+ * @param length the length of the range
+ * @param seed customized seed
+ * @return hash code
+ */
+ public static long hash(byte[] input, int offset, int length, long seed) {
+ long a = seed;
+ long b = length;
+
+ if (length > 32) {
+ long c = rotateRight(length, s1) + seed;
+ long d = length ^ rotateRight(seed, s1);
+
+ do {
+ long w0 = fetch64(input, offset);
+ long w1 = fetch64(input, offset + 8);
+ long w2 = fetch64(input, offset + 16);
+ long w3 = fetch64(input, offset + 24);
+
+ long d02 = w0 ^ rotateRight(w2 + d, s1);
+ long c13 = w1 ^ rotateRight(w3 + c, s1);
+ c += a ^ rotateRight(w0, s0);
+ d -= b ^ rotateRight(w1, s2);
+ a ^= p1 * (d02 + w3);
+ b ^= p0 * (c13 + w2);
+
+ offset += 32;
+ length -= 32;
+ } while (length >= 32);
+
+ a ^= p6 * (rotateRight(c, s1) + d);
+ b ^= p5 * (rotateRight(d, s1) + c);
+ }
+
+ return h32(input, offset, length, a, b);
+ }
+
+ /**
+ * Computes the hash of up to 32 bytes.
+ * Constants in the switch expression are dense; JVM will use them as indices into a table of
+ * instruction pointers (tableswitch instruction), making lookups really fast.
+ */
+ @SuppressWarnings("fallthrough")
+ private static long h32(byte[] input, int offset, int length, long a, long b) {
+ switch (length) {
+ default:
+ b += mux64(fetch64(input, offset), p4);
+ offset += 8;
+ length -= 8;
+ case 24:
+ case 23:
+ case 22:
+ case 21:
+ case 20:
+ case 19:
+ case 18:
+ case 17:
+ a += mux64(fetch64(input, offset), p3);
+ offset += 8;
+ length -= 8;
+ case 16:
+ case 15:
+ case 14:
+ case 13:
+ case 12:
+ case 11:
+ case 10:
+ case 9:
+ b += mux64(fetch64(input, offset), p2);
+ offset += 8;
+ length -= 8;
+ case 8:
+ case 7:
+ case 6:
+ case 5:
+ case 4:
+ case 3:
+ case 2:
+ case 1:
+ a += mux64(tail64(input, offset, length), p1);
+ case 0:
+ // Final weak avalanche
+ return mux64(rotateRight(a + b, s1), p4) + mix64(a ^ b, p0);
+ }
+ }
+
+ /**
+ * XOR the high and low parts of the full 128-bit product.
+ */
+ private static long mux64(long a, long b) {
+ return MUX_64_IMPL.mux64(a, b);
+ }
+
+ /**
+ * XOR-MUL-XOR bit-mixer.
+ */
+ private static long mix64(long a, long b) {
+ a *= b;
+ return a ^ rotateRight(a, s0);
+ }
+
+ /**
+ * Reads "length" bytes starting at "offset" in little-endian order; returned as long.
+ * It is assumed that the length is between 1 and 8 (inclusive); but no defensive checks are made as such.
+ */
+ private static long tail64(byte[] input, int offset, int length) {
+ switch (length) {
+ case 1:
+ return fetch8(input, offset);
+ case 2:
+ return fetch16(input, offset);
+ case 3:
+ return fetch16(input, offset) | (fetch8(input, offset + 2) << 16);
+ case 4:
+ return fetch32(input, offset);
+ case 5:
+ return fetch32(input, offset) | (fetch8(input, offset + 4) << 32);
+ case 6:
+ return fetch32(input, offset) | (fetch16(input, offset + 4) << 32);
+ case 7:
+ // This is equivalent to:
+ // return fetch32(input, offset) | (fetch16(input, offset + 4) << 32) | (fetch8(input, offset + 6) << 48);
+ // But reading two ints overlapping by one byte is faster due to lesser instructions.
+ return fetch32(input, offset) | (fetch32(input, offset + 3) << 24);
+ default:
+ return fetch64(input, offset);
+ }
+ }
+
+ /**
+ * Reads a 64-bit long.
+ */
+ private static long fetch64(byte[] input, int offset) {
+ return (long) LONG_HANDLE.get(input, offset);
+ }
+
+ /**
+ * Reads a 32-bit unsigned integer, returned as long.
+ */
+ private static long fetch32(byte[] input, int offset) {
+ return (int) INT_HANDLE.get(input, offset) & 0xFFFFFFFFL;
+ }
+
+ /**
+ * Reads a 16-bit unsigned short, returned as long.
+ */
+ private static long fetch16(byte[] input, int offset) {
+ return (short) SHORT_HANDLE.get(input, offset) & 0xFFFFL;
+ }
+
+ /**
+ * Reads an 8-bit unsigned byte, returned as long.
+ */
+ private static long fetch8(byte[] input, int offset) {
+ return input[offset] & 0xFFL;
+ }
+
+ /**
+ * The implementation of mux64.
+ */
+ @FunctionalInterface
+ private interface Mux64 {
+ long mux64(long a, long b);
+ }
+
+ /**
+ * Provides the fastest available implementation of mux64 on this platform.
+ *
+ *
+ * Ideally, the following should be returned to match the reference implementation:
+ * {@code Math.unsignedMultiplyHigh(a, b) ^ (a * b)}
+ *
+ *
+ * Since unsignedMultiplyHigh isn't available before JDK 18, and calculating it without intrinsics is quite slow,
+ * the multiplyHigh method is used instead. Slight loss in quality is imperceptible for our use-case: a hash table.
+ * {@code Math.multiplyHigh(a, b) ^ (a * b)}
+ *
+ *
+ * This indirection can be removed once we stop supporting older JDKs.
+ */
+ private static Mux64 fastestMux64Impl() {
+ try {
+ final MethodHandle unsignedMultiplyHigh = MethodHandles.publicLookup()
+ .findStatic(Math.class, "unsignedMultiplyHigh", MethodType.methodType(long.class, long.class, long.class));
+ return (a, b) -> {
+ try {
+ return (long) unsignedMultiplyHigh.invokeExact(a, b) ^ (a * b);
+ } catch (Throwable e) {
+ throw new RuntimeException(e);
+ }
+ };
+ } catch (NoSuchMethodException e) {
+ return (a, b) -> Math.multiplyHigh(a, b) ^ (a * b);
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/hash/package-info.java b/libs/common/src/main/java/org/opensearch/common/hash/package-info.java
new file mode 100644
index 0000000000000..bd393b8b921ed
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/hash/package-info.java
@@ -0,0 +1,12 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Common hashing utilities.
+ */
+package org.opensearch.common.hash;
diff --git a/libs/common/src/main/java/org/opensearch/common/io/InputStreamContainer.java b/libs/common/src/main/java/org/opensearch/common/io/InputStreamContainer.java
index eb8a4e1382497..3095336338f7f 100644
--- a/libs/common/src/main/java/org/opensearch/common/io/InputStreamContainer.java
+++ b/libs/common/src/main/java/org/opensearch/common/io/InputStreamContainer.java
@@ -8,13 +8,16 @@
package org.opensearch.common.io;
+import org.opensearch.common.annotation.ExperimentalApi;
+
import java.io.InputStream;
/**
* Model composed of an input stream and the total content length of the stream
*
- * @opensearch.internal
+ * @opensearch.experimental
*/
+@ExperimentalApi
public class InputStreamContainer {
private final InputStream inputStream;
diff --git a/libs/common/src/main/java/org/opensearch/common/io/PathUtils.java b/libs/common/src/main/java/org/opensearch/common/io/PathUtils.java
index b3526859933ec..ed8d50892b74a 100644
--- a/libs/common/src/main/java/org/opensearch/common/io/PathUtils.java
+++ b/libs/common/src/main/java/org/opensearch/common/io/PathUtils.java
@@ -93,7 +93,7 @@ public static Path get(URI uri) {
/**
* Tries to resolve the given path against the list of available roots.
- *
+ *
* If path starts with one of the listed roots, it returned back by this method, otherwise null is returned.
*/
public static Path get(Path[] roots, String path) {
@@ -109,7 +109,7 @@ public static Path get(Path[] roots, String path) {
/**
* Tries to resolve the given file uri against the list of available roots.
- *
+ *
* If uri starts with one of the listed roots, it returned back by this method, otherwise null is returned.
*/
public static Path get(Path[] roots, URI uri) {
diff --git a/libs/common/src/main/java/org/opensearch/common/lease/Releasable.java b/libs/common/src/main/java/org/opensearch/common/lease/Releasable.java
index 30bea6185febc..dfc4fefb9ee55 100644
--- a/libs/common/src/main/java/org/opensearch/common/lease/Releasable.java
+++ b/libs/common/src/main/java/org/opensearch/common/lease/Releasable.java
@@ -32,13 +32,16 @@
package org.opensearch.common.lease;
+import org.opensearch.common.annotation.PublicApi;
+
import java.io.Closeable;
/**
* Specialization of {@link AutoCloseable} for calls that might not throw a checked exception.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface Releasable extends Closeable {
@Override
diff --git a/server/src/main/java/org/opensearch/common/component/AbstractLifecycleComponent.java b/libs/common/src/main/java/org/opensearch/common/lifecycle/AbstractLifecycleComponent.java
similarity index 98%
rename from server/src/main/java/org/opensearch/common/component/AbstractLifecycleComponent.java
rename to libs/common/src/main/java/org/opensearch/common/lifecycle/AbstractLifecycleComponent.java
index 837f8af44bf13..111556fbe43cf 100644
--- a/server/src/main/java/org/opensearch/common/component/AbstractLifecycleComponent.java
+++ b/libs/common/src/main/java/org/opensearch/common/lifecycle/AbstractLifecycleComponent.java
@@ -30,7 +30,7 @@
* GitHub history for details.
*/
-package org.opensearch.common.component;
+package org.opensearch.common.lifecycle;
import java.io.IOException;
import java.io.UncheckedIOException;
diff --git a/server/src/main/java/org/opensearch/common/component/Lifecycle.java b/libs/common/src/main/java/org/opensearch/common/lifecycle/Lifecycle.java
similarity index 97%
rename from server/src/main/java/org/opensearch/common/component/Lifecycle.java
rename to libs/common/src/main/java/org/opensearch/common/lifecycle/Lifecycle.java
index fb12c1fc9ac4b..c1cf9b2998a13 100644
--- a/server/src/main/java/org/opensearch/common/component/Lifecycle.java
+++ b/libs/common/src/main/java/org/opensearch/common/lifecycle/Lifecycle.java
@@ -30,7 +30,9 @@
* GitHub history for details.
*/
-package org.opensearch.common.component;
+package org.opensearch.common.lifecycle;
+
+import org.opensearch.common.annotation.PublicApi;
/**
* Lifecycle state. Allows the following transitions:
@@ -73,15 +75,17 @@
* }
*
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class Lifecycle {
/**
* State in the lifecycle
*
- * @opensearch.internal
+ * @opensearch.api
*/
+ @PublicApi(since = "1.0.0")
public enum State {
INITIALIZED,
STOPPED,
diff --git a/server/src/main/java/org/opensearch/common/component/LifecycleComponent.java b/libs/common/src/main/java/org/opensearch/common/lifecycle/LifecycleComponent.java
similarity index 91%
rename from server/src/main/java/org/opensearch/common/component/LifecycleComponent.java
rename to libs/common/src/main/java/org/opensearch/common/lifecycle/LifecycleComponent.java
index 984d55df1bdfa..781c276fefe13 100644
--- a/server/src/main/java/org/opensearch/common/component/LifecycleComponent.java
+++ b/libs/common/src/main/java/org/opensearch/common/lifecycle/LifecycleComponent.java
@@ -30,15 +30,17 @@
* GitHub history for details.
*/
-package org.opensearch.common.component;
+package org.opensearch.common.lifecycle;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.common.lease.Releasable;
/**
* Base interface for a lifecycle component.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface LifecycleComponent extends Releasable {
Lifecycle.State lifecycleState();
diff --git a/server/src/main/java/org/opensearch/common/component/LifecycleListener.java b/libs/common/src/main/java/org/opensearch/common/lifecycle/LifecycleListener.java
similarity index 97%
rename from server/src/main/java/org/opensearch/common/component/LifecycleListener.java
rename to libs/common/src/main/java/org/opensearch/common/lifecycle/LifecycleListener.java
index 89c344b955bc9..7ac41a5eb0df0 100644
--- a/server/src/main/java/org/opensearch/common/component/LifecycleListener.java
+++ b/libs/common/src/main/java/org/opensearch/common/lifecycle/LifecycleListener.java
@@ -30,7 +30,7 @@
* GitHub history for details.
*/
-package org.opensearch.common.component;
+package org.opensearch.common.lifecycle;
/**
* Base lifecycle listener.
diff --git a/libs/common/src/main/java/org/opensearch/common/lifecycle/package-info.java b/libs/common/src/main/java/org/opensearch/common/lifecycle/package-info.java
new file mode 100644
index 0000000000000..1bedde5585e36
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/lifecycle/package-info.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Foundation implementation for a object lifecycle.
+ *
+ * See {@link org.opensearch.common.lifecycle.Lifecycle} for example usage
+ *
+ * @opensearch.internal
+ */
+package org.opensearch.common.lifecycle;
diff --git a/server/src/main/java/org/opensearch/common/network/Cidrs.java b/libs/common/src/main/java/org/opensearch/common/network/Cidrs.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/network/Cidrs.java
rename to libs/common/src/main/java/org/opensearch/common/network/Cidrs.java
diff --git a/server/src/main/java/org/opensearch/common/network/InetAddresses.java b/libs/common/src/main/java/org/opensearch/common/network/InetAddresses.java
similarity index 99%
rename from server/src/main/java/org/opensearch/common/network/InetAddresses.java
rename to libs/common/src/main/java/org/opensearch/common/network/InetAddresses.java
index a4fbc6cb65b0d..60c0717a28f05 100644
--- a/server/src/main/java/org/opensearch/common/network/InetAddresses.java
+++ b/libs/common/src/main/java/org/opensearch/common/network/InetAddresses.java
@@ -52,7 +52,7 @@ public static boolean isInetAddress(String ipString) {
return ipStringToBytes(ipString) != null;
}
- private static byte[] ipStringToBytes(String ipString) {
+ public static byte[] ipStringToBytes(String ipString) {
// Make a first pass to categorize the characters in this string.
boolean hasColon = false;
boolean hasDot = false;
@@ -368,7 +368,7 @@ public static InetAddress forString(String ipString) {
/**
* Convert a byte array into an InetAddress.
- *
+ *
* {@link InetAddress#getByAddress} is documented as throwing a checked
* exception "if IP address is of illegal length." We replace it with
* an unchecked exception, for use by callers who already know that addr
@@ -423,7 +423,7 @@ public static Tuple parseCidr(String maskedAddress) {
/**
* Given an address and prefix length, returns the string representation of the range in CIDR notation.
- *
+ *
* See {@link #toAddrString} for details on how the address is represented.
*/
public static String toCidrString(InetAddress address, int prefixLength) {
diff --git a/server/src/main/java/org/opensearch/common/network/NetworkAddress.java b/libs/common/src/main/java/org/opensearch/common/network/NetworkAddress.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/network/NetworkAddress.java
rename to libs/common/src/main/java/org/opensearch/common/network/NetworkAddress.java
diff --git a/libs/common/src/main/java/org/opensearch/common/network/package-info.java b/libs/common/src/main/java/org/opensearch/common/network/package-info.java
new file mode 100644
index 0000000000000..92e4eac5bde42
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/network/package-info.java
@@ -0,0 +1,10 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/** common network layer classes used across the code base */
+package org.opensearch.common.network;
diff --git a/server/src/main/java/org/opensearch/common/recycler/AbstractRecycler.java b/libs/common/src/main/java/org/opensearch/common/recycler/AbstractRecycler.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/recycler/AbstractRecycler.java
rename to libs/common/src/main/java/org/opensearch/common/recycler/AbstractRecycler.java
diff --git a/server/src/main/java/org/opensearch/common/recycler/AbstractRecyclerC.java b/libs/common/src/main/java/org/opensearch/common/recycler/AbstractRecyclerC.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/recycler/AbstractRecyclerC.java
rename to libs/common/src/main/java/org/opensearch/common/recycler/AbstractRecyclerC.java
diff --git a/server/src/main/java/org/opensearch/common/recycler/ConcurrentDequeRecycler.java b/libs/common/src/main/java/org/opensearch/common/recycler/ConcurrentDequeRecycler.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/recycler/ConcurrentDequeRecycler.java
rename to libs/common/src/main/java/org/opensearch/common/recycler/ConcurrentDequeRecycler.java
diff --git a/server/src/main/java/org/opensearch/common/recycler/DequeRecycler.java b/libs/common/src/main/java/org/opensearch/common/recycler/DequeRecycler.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/recycler/DequeRecycler.java
rename to libs/common/src/main/java/org/opensearch/common/recycler/DequeRecycler.java
diff --git a/server/src/main/java/org/opensearch/common/recycler/FilterRecycler.java b/libs/common/src/main/java/org/opensearch/common/recycler/FilterRecycler.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/recycler/FilterRecycler.java
rename to libs/common/src/main/java/org/opensearch/common/recycler/FilterRecycler.java
diff --git a/server/src/main/java/org/opensearch/common/recycler/NoneRecycler.java b/libs/common/src/main/java/org/opensearch/common/recycler/NoneRecycler.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/recycler/NoneRecycler.java
rename to libs/common/src/main/java/org/opensearch/common/recycler/NoneRecycler.java
diff --git a/server/src/main/java/org/opensearch/common/recycler/Recycler.java b/libs/common/src/main/java/org/opensearch/common/recycler/Recycler.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/recycler/Recycler.java
rename to libs/common/src/main/java/org/opensearch/common/recycler/Recycler.java
diff --git a/server/src/main/java/org/opensearch/common/recycler/Recyclers.java b/libs/common/src/main/java/org/opensearch/common/recycler/Recyclers.java
similarity index 98%
rename from server/src/main/java/org/opensearch/common/recycler/Recyclers.java
rename to libs/common/src/main/java/org/opensearch/common/recycler/Recyclers.java
index 4cbb80509d6a1..52587144369f1 100644
--- a/server/src/main/java/org/opensearch/common/recycler/Recyclers.java
+++ b/libs/common/src/main/java/org/opensearch/common/recycler/Recyclers.java
@@ -75,6 +75,8 @@ public static Recycler.Factory dequeFactory(final Recycler.C c, final
/**
* Wrap the provided recycler so that calls to {@link Recycler#obtain()} and {@link Recycler.V#close()} are protected by
* a lock.
+ *
+ * @opensearch.internal
*/
public static Recycler locked(final Recycler recycler) {
return new FilterRecycler() {
@@ -140,7 +142,7 @@ public static Recycler concurrent(final Recycler.Factory factory, fina
private final Recycler[] recyclers;
{
- @SuppressWarnings("unchecked")
+ @SuppressWarnings({ "rawtypes", "unchecked" })
final Recycler[] recyclers = new Recycler[concurrencyLevel];
this.recyclers = recyclers;
for (int i = 0; i < concurrencyLevel; ++i) {
diff --git a/libs/common/src/main/java/org/opensearch/common/recycler/package-info.java b/libs/common/src/main/java/org/opensearch/common/recycler/package-info.java
new file mode 100644
index 0000000000000..fec3c5d5e52d3
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/recycler/package-info.java
@@ -0,0 +1,10 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/** Common Recycler functionality for recycling objects */
+package org.opensearch.common.recycler;
diff --git a/libs/common/src/main/java/org/opensearch/common/round/BidirectionalLinearSearcher.java b/libs/common/src/main/java/org/opensearch/common/round/BidirectionalLinearSearcher.java
new file mode 100644
index 0000000000000..5c3dcf2bd4708
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/round/BidirectionalLinearSearcher.java
@@ -0,0 +1,59 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.round;
+
+import org.opensearch.common.annotation.InternalApi;
+
+/**
+ * It uses linear search on a sorted array of pre-computed round-down points.
+ * For small inputs (≤ 64 elements), this can be much faster than binary search as it avoids the penalty of
+ * branch mispredictions and pipeline stalls, and accesses memory sequentially.
+ *
+ *
+ * It uses "meet in the middle" linear search to avoid the worst case scenario when the desired element is present
+ * at either side of the array. This is helpful for time-series data where velocity increases over time, so more
+ * documents are likely to find a greater timestamp which is likely to be present on the right end of the array.
+ *
+ * @opensearch.internal
+ */
+@InternalApi
+class BidirectionalLinearSearcher implements Roundable {
+ private final long[] ascending;
+ private final long[] descending;
+
+ BidirectionalLinearSearcher(long[] values, int size) {
+ if (size <= 0) {
+ throw new IllegalArgumentException("at least one value must be present");
+ }
+
+ int len = (size + 1) >>> 1; // rounded-up to handle odd number of values
+ ascending = new long[len];
+ descending = new long[len];
+
+ for (int i = 0; i < len; i++) {
+ ascending[i] = values[i];
+ descending[i] = values[size - i - 1];
+ }
+ }
+
+ @Override
+ public long floor(long key) {
+ int i = 0;
+ for (; i < ascending.length; i++) {
+ if (descending[i] <= key) {
+ return descending[i];
+ }
+ if (ascending[i] > key) {
+ assert i > 0 : "key must be greater than or equal to " + ascending[0];
+ return ascending[i - 1];
+ }
+ }
+ return ascending[i - 1];
+ }
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/round/BinarySearcher.java b/libs/common/src/main/java/org/opensearch/common/round/BinarySearcher.java
new file mode 100644
index 0000000000000..b9d76945115ed
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/round/BinarySearcher.java
@@ -0,0 +1,43 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.round;
+
+import org.opensearch.common.annotation.InternalApi;
+
+import java.util.Arrays;
+
+/**
+ * It uses binary search on a sorted array of pre-computed round-down points.
+ *
+ * @opensearch.internal
+ */
+@InternalApi
+class BinarySearcher implements Roundable {
+ private final long[] values;
+ private final int size;
+
+ BinarySearcher(long[] values, int size) {
+ if (size <= 0) {
+ throw new IllegalArgumentException("at least one value must be present");
+ }
+
+ this.values = values;
+ this.size = size;
+ }
+
+ @Override
+ public long floor(long key) {
+ int idx = Arrays.binarySearch(values, 0, size, key);
+ assert idx != -1 : "key must be greater than or equal to " + values[0];
+ if (idx < 0) {
+ idx = -2 - idx;
+ }
+ return values[idx];
+ }
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/round/Roundable.java b/libs/common/src/main/java/org/opensearch/common/round/Roundable.java
new file mode 100644
index 0000000000000..ae6f9b787c1e9
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/round/Roundable.java
@@ -0,0 +1,28 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.round;
+
+import org.opensearch.common.annotation.InternalApi;
+
+/**
+ * Interface to round-off values.
+ *
+ * @opensearch.internal
+ */
+@InternalApi
+@FunctionalInterface
+public interface Roundable {
+ /**
+ * Returns the greatest lower bound of the given key.
+ * In other words, it returns the largest value such that {@code value <= key}.
+ * @param key to floor
+ * @return the floored value
+ */
+ long floor(long key);
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/round/RoundableFactory.java b/libs/common/src/main/java/org/opensearch/common/round/RoundableFactory.java
new file mode 100644
index 0000000000000..b7422694c3013
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/round/RoundableFactory.java
@@ -0,0 +1,39 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.round;
+
+import org.opensearch.common.annotation.InternalApi;
+
+/**
+ * Factory class to create and return the fastest implementation of {@link Roundable}.
+ *
+ * @opensearch.internal
+ */
+@InternalApi
+public final class RoundableFactory {
+ /**
+ * The maximum limit up to which linear search is used, otherwise binary search is used.
+ * This is because linear search is much faster on small arrays.
+ * Benchmark results: PR #9727
+ */
+ private static final int LINEAR_SEARCH_MAX_SIZE = 64;
+
+ private RoundableFactory() {}
+
+ /**
+ * Creates and returns the fastest implementation of {@link Roundable}.
+ */
+ public static Roundable create(long[] values, int size) {
+ if (size <= LINEAR_SEARCH_MAX_SIZE) {
+ return new BidirectionalLinearSearcher(values, size);
+ } else {
+ return new BinarySearcher(values, size);
+ }
+ }
+}
diff --git a/libs/common/src/main/java/org/opensearch/common/round/package-info.java b/libs/common/src/main/java/org/opensearch/common/round/package-info.java
new file mode 100644
index 0000000000000..e79c4017de31b
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/round/package-info.java
@@ -0,0 +1,12 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Contains classes to round-off values.
+ */
+package org.opensearch.common.round;
diff --git a/server/src/main/java/org/opensearch/common/transport/NetworkExceptionHelper.java b/libs/common/src/main/java/org/opensearch/common/transport/NetworkExceptionHelper.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/transport/NetworkExceptionHelper.java
rename to libs/common/src/main/java/org/opensearch/common/transport/NetworkExceptionHelper.java
diff --git a/server/src/main/java/org/opensearch/common/transport/PortsRange.java b/libs/common/src/main/java/org/opensearch/common/transport/PortsRange.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/transport/PortsRange.java
rename to libs/common/src/main/java/org/opensearch/common/transport/PortsRange.java
diff --git a/libs/common/src/main/java/org/opensearch/common/transport/package-info.java b/libs/common/src/main/java/org/opensearch/common/transport/package-info.java
new file mode 100644
index 0000000000000..7d28ac6c60a14
--- /dev/null
+++ b/libs/common/src/main/java/org/opensearch/common/transport/package-info.java
@@ -0,0 +1,10 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/** common transport layer classes used across the code base */
+package org.opensearch.common.transport;
diff --git a/libs/common/src/main/java/org/opensearch/common/unit/TimeValue.java b/libs/common/src/main/java/org/opensearch/common/unit/TimeValue.java
index 670275397893c..30ed5bf63a748 100644
--- a/libs/common/src/main/java/org/opensearch/common/unit/TimeValue.java
+++ b/libs/common/src/main/java/org/opensearch/common/unit/TimeValue.java
@@ -32,6 +32,8 @@
package org.opensearch.common.unit;
+import org.opensearch.common.annotation.PublicApi;
+
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
@@ -41,6 +43,7 @@
*
* @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class TimeValue implements Comparable {
/** How many nano-seconds in one milli-second */
@@ -221,10 +224,10 @@ public double getDaysFrac() {
/**
* Returns a {@link String} representation of the current {@link TimeValue}.
- *
+ *
* Note that this method might produce fractional time values (ex 1.6m) which cannot be
* parsed by method like {@link TimeValue#parse(String, String, String, String)}.
- *
+ *
* Also note that the maximum string value that will be generated is
* {@code 106751.9d} due to the way that values are internally converted
* to nanoseconds (106751.9 days is Long.MAX_VALUE nanoseconds)
@@ -236,12 +239,12 @@ public String toString() {
/**
* Returns a {@link String} representation of the current {@link TimeValue}.
- *
+ *
* Note that this method might produce fractional time values (ex 1.6m) which cannot be
* parsed by method like {@link TimeValue#parse(String, String, String, String)}. The number of
* fractional decimals (up to 10 maximum) are truncated to the number of fraction pieces
* specified.
- *
+ *
* Also note that the maximum string value that will be generated is
* {@code 106751.9d} due to the way that values are internally converted
* to nanoseconds (106751.9 days is Long.MAX_VALUE nanoseconds)
diff --git a/libs/common/src/main/java/org/opensearch/common/util/BitMixer.java b/libs/common/src/main/java/org/opensearch/common/util/BitMixer.java
index 8762217916c7a..d6ea4fa359df3 100644
--- a/libs/common/src/main/java/org/opensearch/common/util/BitMixer.java
+++ b/libs/common/src/main/java/org/opensearch/common/util/BitMixer.java
@@ -25,9 +25,9 @@
/**
* Bit mixing utilities from carrotsearch.hppc.
- *
+ *
* Licensed under ALv2. This is pulled in directly to avoid a full hppc dependency.
- *
+ *
* The purpose of these methods is to evenly distribute key space over int32
* range.
*/
@@ -111,7 +111,7 @@ public static int mix32(int k) {
/**
* Computes David Stafford variant 9 of 64bit mix function (MH3 finalization step,
* with different shifts and constants).
- *
+ *
* Variant 9 is picked because it contains two 32-bit shifts which could be possibly
* optimized into better machine code.
*
diff --git a/server/src/main/java/org/opensearch/common/util/concurrent/ConcurrentCollections.java b/libs/common/src/main/java/org/opensearch/common/util/concurrent/ConcurrentCollections.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/util/concurrent/ConcurrentCollections.java
rename to libs/common/src/main/java/org/opensearch/common/util/concurrent/ConcurrentCollections.java
diff --git a/server/src/main/java/org/opensearch/common/util/concurrent/ConcurrentHashMapLong.java b/libs/common/src/main/java/org/opensearch/common/util/concurrent/ConcurrentHashMapLong.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/util/concurrent/ConcurrentHashMapLong.java
rename to libs/common/src/main/java/org/opensearch/common/util/concurrent/ConcurrentHashMapLong.java
diff --git a/server/src/main/java/org/opensearch/common/util/concurrent/ConcurrentMapLong.java b/libs/common/src/main/java/org/opensearch/common/util/concurrent/ConcurrentMapLong.java
similarity index 100%
rename from server/src/main/java/org/opensearch/common/util/concurrent/ConcurrentMapLong.java
rename to libs/common/src/main/java/org/opensearch/common/util/concurrent/ConcurrentMapLong.java
diff --git a/libs/common/src/main/java20/org/opensearch/common/round/BtreeSearcher.java b/libs/common/src/main/java20/org/opensearch/common/round/BtreeSearcher.java
new file mode 100644
index 0000000000000..626fb6e6b810e
--- /dev/null
+++ b/libs/common/src/main/java20/org/opensearch/common/round/BtreeSearcher.java
@@ -0,0 +1,100 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.round;
+
+import org.opensearch.common.annotation.InternalApi;
+
+import jdk.incubator.vector.LongVector;
+import jdk.incubator.vector.Vector;
+import jdk.incubator.vector.VectorOperators;
+import jdk.incubator.vector.VectorSpecies;
+
+/**
+ * It uses vectorized B-tree search to find the round-down point.
+ *
+ * @opensearch.internal
+ */
+@InternalApi
+class BtreeSearcher implements Roundable {
+ private static final VectorSpecies LONG_VECTOR_SPECIES = LongVector.SPECIES_PREFERRED;
+ private static final int LANES = LONG_VECTOR_SPECIES.length();
+ private static final int SHIFT = log2(LANES);
+
+ private final long[] values;
+ private final long minValue;
+
+ BtreeSearcher(long[] values, int size) {
+ if (size <= 0) {
+ throw new IllegalArgumentException("at least one value must be present");
+ }
+
+ int blocks = (size + LANES - 1) / LANES; // number of blocks
+ int length = 1 + blocks * LANES; // size of the backing array (1-indexed)
+
+ this.minValue = values[0];
+ this.values = new long[length];
+ build(values, 0, size, this.values, 1);
+ }
+
+ /**
+ * Builds the B-tree memory layout.
+ * It builds the tree recursively, following an in-order traversal.
+ *
+ *
+ * Each block stores 'lanes' values at indices {@code i, i + 1, ..., i + lanes - 1} where {@code i} is the
+ * starting offset. The starting offset of the root block is 1. The branching factor is (1 + lanes) so each
+ * block can have these many children. Given the starting offset {@code i} of a block, the starting offset
+ * of its k-th child (ranging from {@code 0, 1, ..., k}) can be computed as {@code i + ((i + k) << shift)}.
+ *
+ * @param src is the sorted input array
+ * @param i is the index in the input array to read the value from
+ * @param size the number of values in the input array
+ * @param dst is the output array
+ * @param j is the index in the output array to write the value to
+ * @return the next index 'i'
+ */
+ private static int build(long[] src, int i, int size, long[] dst, int j) {
+ if (j < dst.length) {
+ for (int k = 0; k < LANES; k++) {
+ i = build(src, i, size, dst, j + ((j + k) << SHIFT));
+
+ // Fills the B-tree as a complete tree, i.e., all levels are completely filled,
+ // except the last level which is filled from left to right.
+ // The trick is to fill the destination array between indices 1...size (inclusive / 1-indexed)
+ // and pad the remaining array with +infinity.
+ dst[j + k] = (j + k <= size) ? src[i++] : Long.MAX_VALUE;
+ }
+ i = build(src, i, size, dst, j + ((j + LANES) << SHIFT));
+ }
+ return i;
+ }
+
+ @Override
+ public long floor(long key) {
+ Vector keyVector = LongVector.broadcast(LONG_VECTOR_SPECIES, key);
+ int i = 1, result = 1;
+
+ while (i < values.length) {
+ Vector valuesVector = LongVector.fromArray(LONG_VECTOR_SPECIES, values, i);
+ int j = i + valuesVector.compare(VectorOperators.GT, keyVector).firstTrue();
+ result = (j > i) ? j : result;
+ i += (j << SHIFT);
+ }
+
+ assert result > 1 : "key must be greater than or equal to " + minValue;
+ return values[result - 1];
+ }
+
+ private static int log2(int num) {
+ if ((num <= 0) || ((num & (num - 1)) != 0)) {
+ throw new IllegalArgumentException(num + " is not a positive power of 2");
+ }
+ return 32 - Integer.numberOfLeadingZeros(num - 1);
+ }
+}
diff --git a/libs/common/src/main/java20/org/opensearch/common/round/RoundableFactory.java b/libs/common/src/main/java20/org/opensearch/common/round/RoundableFactory.java
new file mode 100644
index 0000000000000..0709ed4374227
--- /dev/null
+++ b/libs/common/src/main/java20/org/opensearch/common/round/RoundableFactory.java
@@ -0,0 +1,75 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.round;
+
+import org.opensearch.common.annotation.InternalApi;
+
+/**
+ * Factory class to create and return the fastest implementation of {@link Roundable}.
+ *
+ * @opensearch.internal
+ */
+@InternalApi
+public final class RoundableFactory {
+ /**
+ * The maximum limit up to which linear search is used, otherwise binary or B-tree search is used.
+ * This is because linear search is much faster on small arrays.
+ * Benchmark results: PR #9727
+ */
+ private static final int LINEAR_SEARCH_MAX_SIZE = 64;
+
+ /**
+ * Indicates whether the vectorized (SIMD) B-tree search implementation is to be used.
+ * It is true when either:
+ * 1. The feature flag is set to "forced", or
+ * 2. The platform has a minimum of 4 long vector lanes and the feature flag is set to "true".
+ */
+ private static final boolean USE_BTREE_SEARCHER;
+
+ /**
+ * This class is initialized only when:
+ * - JDK-20+
+ * - jdk.incubator.vector.LongVector is available (--add-modules=jdk.incubator.vector is passed)
+ */
+ private static final class VectorCheck {
+ final static int SPECIES_PREFERRED = jdk.incubator.vector.LongVector.SPECIES_PREFERRED.length();
+ }
+
+ static {
+ String simdRoundingFeatureFlag = System.getProperty("opensearch.experimental.feature.simd.rounding.enabled");
+ boolean useBtreeSearcher = false;
+
+ try {
+ final Class> incubator = Class.forName("jdk.incubator.vector.LongVector");
+
+ useBtreeSearcher = "forced".equalsIgnoreCase(simdRoundingFeatureFlag)
+ || (VectorCheck.SPECIES_PREFERRED >= 4 && "true".equalsIgnoreCase(simdRoundingFeatureFlag));
+
+ } catch (final ClassNotFoundException ex) {
+ /* do not use BtreeSearcher */
+ }
+
+ USE_BTREE_SEARCHER = useBtreeSearcher;
+ }
+
+ private RoundableFactory() {}
+
+ /**
+ * Creates and returns the fastest implementation of {@link Roundable}.
+ */
+ public static Roundable create(long[] values, int size) {
+ if (size <= LINEAR_SEARCH_MAX_SIZE) {
+ return new BidirectionalLinearSearcher(values, size);
+ } else if (USE_BTREE_SEARCHER) {
+ return new BtreeSearcher(values, size);
+ } else {
+ return new BinarySearcher(values, size);
+ }
+ }
+}
diff --git a/libs/common/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/libs/common/src/main/resources/META-INF/services/javax.annotation.processing.Processor
new file mode 100644
index 0000000000000..c4e4dfed864f2
--- /dev/null
+++ b/libs/common/src/main/resources/META-INF/services/javax.annotation.processing.Processor
@@ -0,0 +1,12 @@
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+#
+# Modifications Copyright OpenSearch Contributors. See
+# GitHub history for details.
+#
+
+org.opensearch.common.annotation.processor.ApiAnnotationProcessor
\ No newline at end of file
diff --git a/libs/common/src/test/java/org/opensearch/common/BooleansTests.java b/libs/common/src/test/java/org/opensearch/common/BooleansTests.java
new file mode 100644
index 0000000000000..578ec742d126d
--- /dev/null
+++ b/libs/common/src/test/java/org/opensearch/common/BooleansTests.java
@@ -0,0 +1,132 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+package org.opensearch.common;
+
+import org.opensearch.test.OpenSearchTestCase;
+
+import static org.hamcrest.Matchers.is;
+
+public class BooleansTests extends OpenSearchTestCase {
+ private static final String[] NON_BOOLEANS = new String[] {
+ "11",
+ "00",
+ "sdfsdfsf",
+ "F",
+ "T",
+ "on",
+ "off",
+ "yes",
+ "no",
+ "0",
+ "1",
+ "True",
+ "False" };
+ private static final String[] BOOLEANS = new String[] { "true", "false" };
+
+ public void testIsBoolean() {
+ for (String b : BOOLEANS) {
+ String t = "prefix" + b + "suffix";
+ assertTrue("failed to recognize [" + b + "] as boolean", Booleans.isBoolean(t.toCharArray(), "prefix".length(), b.length()));
+ assertTrue("failed to recognize [" + b + "] as boolean", Booleans.isBoolean(b));
+ }
+ }
+
+ public void testIsNonBoolean() {
+ assertThat(Booleans.isBoolean(null, 0, 1), is(false));
+
+ for (String nb : NON_BOOLEANS) {
+ String t = "prefix" + nb + "suffix";
+ assertFalse("recognized [" + nb + "] as boolean", Booleans.isBoolean(t.toCharArray(), "prefix".length(), nb.length()));
+ assertFalse("recognized [" + nb + "] as boolean", Booleans.isBoolean(t));
+ }
+ }
+
+ public void testParseBooleanWithFallback() {
+ assertFalse(Booleans.parseBoolean(null, false));
+ assertTrue(Booleans.parseBoolean(null, true));
+ assertNull(Booleans.parseBoolean(null, null));
+ assertFalse(Booleans.parseBoolean(null, Boolean.FALSE));
+ assertTrue(Booleans.parseBoolean(null, Boolean.TRUE));
+
+ assertFalse(Booleans.parseBoolean("", false));
+ assertTrue(Booleans.parseBoolean("", true));
+ assertNull(Booleans.parseBoolean("", null));
+ assertFalse(Booleans.parseBoolean("", Boolean.FALSE));
+ assertTrue(Booleans.parseBoolean("", Boolean.TRUE));
+
+ assertFalse(Booleans.parseBoolean(" \t\n", false));
+ assertTrue(Booleans.parseBoolean(" \t\n", true));
+ assertNull(Booleans.parseBoolean(" \t\n", null));
+ assertFalse(Booleans.parseBoolean(" \t\n", Boolean.FALSE));
+ assertTrue(Booleans.parseBoolean(" \t\n", Boolean.TRUE));
+
+ assertTrue(Booleans.parseBoolean("true", randomFrom(Boolean.TRUE, Boolean.FALSE, null)));
+ assertFalse(Booleans.parseBoolean("false", randomFrom(Boolean.TRUE, Boolean.FALSE, null)));
+
+ assertTrue(Booleans.parseBoolean(new char[0], 0, 0, true));
+ assertFalse(Booleans.parseBoolean(new char[0], 0, 0, false));
+ }
+
+ public void testParseNonBooleanWithFallback() {
+ for (String nonBoolean : NON_BOOLEANS) {
+ boolean defaultValue = randomFrom(Boolean.TRUE, Boolean.FALSE);
+
+ expectThrows(IllegalArgumentException.class, () -> Booleans.parseBoolean(nonBoolean, defaultValue));
+ expectThrows(
+ IllegalArgumentException.class,
+ () -> Booleans.parseBoolean(nonBoolean.toCharArray(), 0, nonBoolean.length(), defaultValue)
+ );
+ }
+ }
+
+ public void testParseBoolean() {
+ assertTrue(Booleans.parseBoolean("true"));
+ assertFalse(Booleans.parseBoolean("false"));
+ }
+
+ public void testParseNonBoolean() {
+ expectThrows(IllegalArgumentException.class, () -> Booleans.parseBoolean(null));
+ for (String nonBoolean : NON_BOOLEANS) {
+ expectThrows(IllegalArgumentException.class, () -> Booleans.parseBoolean(nonBoolean));
+ }
+ }
+
+ public void testParseBooleanStrict() {
+ assertTrue(Booleans.parseBooleanStrict("true", false));
+ assertFalse(Booleans.parseBooleanStrict("false", true));
+ assertTrue(Booleans.parseBooleanStrict(null, true));
+ assertFalse(Booleans.parseBooleanStrict("", false));
+ expectThrows(IllegalArgumentException.class, () -> Booleans.parseBooleanStrict("foobar", false));
+ expectThrows(IllegalArgumentException.class, () -> Booleans.parseBooleanStrict(" \t\n", false));
+ }
+}
diff --git a/libs/common/src/test/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessorTests.java b/libs/common/src/test/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessorTests.java
new file mode 100644
index 0000000000000..8d8a4c7895339
--- /dev/null
+++ b/libs/common/src/test/java/org/opensearch/common/annotation/processor/ApiAnnotationProcessorTests.java
@@ -0,0 +1,476 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.InternalApi;
+import org.opensearch.test.OpenSearchTestCase;
+
+import javax.tools.Diagnostic;
+
+import static org.opensearch.common.annotation.processor.CompilerSupport.HasDiagnostic.matching;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.hasItem;
+import static org.hamcrest.Matchers.hasSize;
+import static org.hamcrest.Matchers.instanceOf;
+
+@SuppressWarnings("deprecation")
+public class ApiAnnotationProcessorTests extends OpenSearchTestCase implements CompilerSupport {
+ public void testPublicApiMethodArgumentNotAnnotated() {
+ final CompilerResult result = compile("PublicApiMethodArgumentNotAnnotated.java", "NotAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotated is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodArgumentNotAnnotated)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodArgumentNotAnnotatedGenerics() {
+ final CompilerResult result = compile("PublicApiMethodArgumentNotAnnotatedGenerics.java", "NotAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotated is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodArgumentNotAnnotatedGenerics)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodThrowsNotAnnotated() {
+ final CompilerResult result = compile("PublicApiMethodThrowsNotAnnotated.java", "PublicApiAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotatedException is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodThrowsNotAnnotated)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodArgumentNotAnnotatedPackagePrivate() {
+ final CompilerResult result = compile("PublicApiMethodArgumentNotAnnotatedPackagePrivate.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(4));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotatedPackagePrivate is part of the public APIs but does not have public or protected visibility "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodArgumentNotAnnotatedPackagePrivate)"
+ )
+ )
+ )
+ );
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotatedPackagePrivate is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodArgumentNotAnnotatedPackagePrivate)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodArgumentAnnotatedPackagePrivate() {
+ final CompilerResult result = compile("PublicApiMethodArgumentAnnotatedPackagePrivate.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.AnnotatedPackagePrivate is part of the public APIs but does not have public or protected visibility "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodArgumentAnnotatedPackagePrivate)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiWithInternalApiMethod() {
+ final CompilerResult result = compile("PublicApiWithInternalApiMethod.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element method() is part of the public APIs but is marked as @InternalApi (referenced by org.opensearch.common.annotation.processor.PublicApiWithInternalApiMethod)"
+ )
+ )
+ )
+ );
+ }
+
+ /**
+ * The constructor arguments have relaxed semantics at the moment: those could be not annotated or be annotated as {@link InternalApi}
+ */
+ public void testPublicApiConstructorArgumentNotAnnotated() {
+ final CompilerResult result = compile("PublicApiConstructorArgumentNotAnnotated.java", "NotAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ /**
+ * The constructor arguments have relaxed semantics at the moment: those could be not annotated or be annotated as {@link InternalApi}
+ */
+ public void testPublicApiConstructorArgumentAnnotatedInternalApi() {
+ final CompilerResult result = compile("PublicApiConstructorArgumentAnnotatedInternalApi.java", "InternalApiAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ public void testPublicApiWithExperimentalApiMethod() {
+ final CompilerResult result = compile("PublicApiWithExperimentalApiMethod.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ public void testPublicApiMethodReturnNotAnnotated() {
+ final CompilerResult result = compile("PublicApiMethodReturnNotAnnotated.java", "NotAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotated is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodReturnNotAnnotated)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodReturnNotAnnotatedGenerics() {
+ final CompilerResult result = compile("PublicApiMethodReturnNotAnnotatedGenerics.java", "NotAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotated is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodReturnNotAnnotatedGenerics)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodReturnNotAnnotatedArray() {
+ final CompilerResult result = compile("PublicApiMethodReturnNotAnnotatedArray.java", "NotAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotated is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodReturnNotAnnotatedArray)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodReturnNotAnnotatedBoundedGenerics() {
+ final CompilerResult result = compile("PublicApiMethodReturnNotAnnotatedBoundedGenerics.java", "NotAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotated is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodReturnNotAnnotatedBoundedGenerics)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodReturnNotAnnotatedAnnotation() {
+ final CompilerResult result = compile(
+ "PublicApiMethodReturnNotAnnotatedAnnotation.java",
+ "PublicApiAnnotated.java",
+ "NotAnnotatedAnnotation.java"
+ );
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotatedAnnotation is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodReturnNotAnnotatedAnnotation)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodReturnNotAnnotatedWildcardGenerics() {
+ final CompilerResult result = compile("PublicApiMethodReturnNotAnnotatedWildcardGenerics.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ public void testPublicApiWithPackagePrivateMethod() {
+ final CompilerResult result = compile("PublicApiWithPackagePrivateMethod.java", "NotAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ public void testPublicApiMethodReturnSelf() {
+ final CompilerResult result = compile("PublicApiMethodReturnSelf.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ public void testExperimentalApiMethodReturnSelf() {
+ final CompilerResult result = compile("ExperimentalApiMethodReturnSelf.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ public void testDeprecatedApiMethodReturnSelf() {
+ final CompilerResult result = compile("DeprecatedApiMethodReturnSelf.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ public void testPublicApiPackagePrivate() {
+ final CompilerResult result = compile("PublicApiPackagePrivate.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.PublicApiPackagePrivate is part of the public APIs but does not have public or protected visibility"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodGenericsArgumentNotAnnotated() {
+ final CompilerResult result = compile("PublicApiMethodGenericsArgumentNotAnnotated.java", "NotAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotated is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodGenericsArgumentNotAnnotated)"
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodReturnAnnotatedArray() {
+ final CompilerResult result = compile("PublicApiMethodReturnAnnotatedArray.java", "PublicApiAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ public void testPublicApiMethodGenericsArgumentAnnotated() {
+ final CompilerResult result = compile("PublicApiMethodGenericsArgumentAnnotated.java", "PublicApiAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+
+ public void testPublicApiAnnotatedNotOpensearch() {
+ final CompilerResult result = compileWithPackage("org.acme", "PublicApiAnnotated.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The type org.acme.PublicApiAnnotated is not residing in org.opensearch.* package and should not be annotated as OpenSearch APIs."
+ )
+ )
+ )
+ );
+ }
+
+ public void testPublicApiMethodReturnAnnotatedGenerics() {
+ final CompilerResult result = compile(
+ "PublicApiMethodReturnAnnotatedGenerics.java",
+ "PublicApiAnnotated.java",
+ "NotAnnotatedAnnotation.java"
+ );
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(3));
+
+ assertThat(
+ failure.diagnotics(),
+ hasItem(
+ matching(
+ Diagnostic.Kind.ERROR,
+ containsString(
+ "The element org.opensearch.common.annotation.processor.NotAnnotatedAnnotation is part of the public APIs but is not marked as @PublicApi, @ExperimentalApi or @DeprecatedApi "
+ + "(referenced by org.opensearch.common.annotation.processor.PublicApiMethodReturnAnnotatedGenerics)"
+ )
+ )
+ )
+ );
+ }
+
+ /**
+ * The type could expose protected inner types which are still considered to be a public API when used
+ */
+ public void testPublicApiWithProtectedInterface() {
+ final CompilerResult result = compile("PublicApiWithProtectedInterface.java");
+ assertThat(result, instanceOf(Failure.class));
+
+ final Failure failure = (Failure) result;
+ assertThat(failure.diagnotics(), hasSize(2));
+
+ assertThat(failure.diagnotics(), not(hasItem(matching(Diagnostic.Kind.ERROR))));
+ }
+}
diff --git a/libs/common/src/test/java/org/opensearch/common/annotation/processor/CompilerSupport.java b/libs/common/src/test/java/org/opensearch/common/annotation/processor/CompilerSupport.java
new file mode 100644
index 0000000000000..c8fdb3333a714
--- /dev/null
+++ b/libs/common/src/test/java/org/opensearch/common/annotation/processor/CompilerSupport.java
@@ -0,0 +1,140 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.hamcrest.Description;
+import org.hamcrest.Matcher;
+import org.hamcrest.TypeSafeMatcher;
+
+import javax.tools.Diagnostic;
+import javax.tools.DiagnosticCollector;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaCompiler.CompilationTask;
+import javax.tools.JavaFileObject;
+import javax.tools.JavaFileObject.Kind;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.ToolProvider;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Locale;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+interface CompilerSupport {
+ default CompilerResult compile(String name, String... names) {
+ return compileWithPackage(ApiAnnotationProcessorTests.class.getPackageName(), name, names);
+ }
+
+ @SuppressWarnings("removal")
+ default CompilerResult compileWithPackage(String pck, String name, String... names) {
+ final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+ final DiagnosticCollector collector = new DiagnosticCollector<>();
+
+ try (StringWriter out = new StringWriter()) {
+ final StandardJavaFileManager fileManager = compiler.getStandardFileManager(collector, null, null);
+ final List files = Stream.concat(Stream.of(name), Arrays.stream(names))
+ .map(f -> asSource(pck, f))
+ .collect(Collectors.toList());
+
+ final CompilationTask task = compiler.getTask(out, fileManager, collector, null, null, files);
+ task.setProcessors(Collections.singleton(new ApiAnnotationProcessor()));
+
+ if (AccessController.doPrivileged((PrivilegedAction) () -> task.call())) {
+ return new Success();
+ } else {
+ return new Failure(collector.getDiagnostics());
+ }
+ } catch (final IOException ex) {
+ throw new UncheckedIOException(ex);
+ }
+ }
+
+ private static JavaFileObject asSource(String pkg, String name) {
+ final String resource = "/" + pkg.replaceAll("[.]", "/") + "/" + name;
+ final URL source = ApiAnnotationProcessorTests.class.getResource(resource);
+
+ return new SimpleJavaFileObject(URI.create(source.toExternalForm()), Kind.SOURCE) {
+ @Override
+ public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
+ try (final InputStream in = ApiAnnotationProcessorTests.class.getResourceAsStream(resource)) {
+ return new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ }
+ }
+ };
+ }
+
+ class CompilerResult {}
+
+ class Success extends CompilerResult {
+
+ }
+
+ class Failure extends CompilerResult {
+ private final List> diagnotics;
+
+ Failure(List> diagnotics) {
+ this.diagnotics = diagnotics;
+ }
+
+ List> diagnotics() {
+ return diagnotics;
+ }
+ }
+
+ class HasDiagnostic extends TypeSafeMatcher> {
+ private final Diagnostic.Kind kind;
+ private final Matcher matcher;
+
+ HasDiagnostic(final Diagnostic.Kind kind, final Matcher matcher) {
+ this.kind = kind;
+ this.matcher = matcher;
+ }
+
+ @Override
+ public void describeTo(Description description) {
+ description.appendText("diagnostic with kind ").appendValue(kind).appendText(" ");
+
+ if (matcher != null) {
+ description.appendText(" and message ");
+ matcher.describeTo(description);
+ }
+ }
+
+ @Override
+ protected boolean matchesSafely(Diagnostic extends JavaFileObject> item) {
+ if (!kind.equals(item.getKind())) {
+ return false;
+ } else if (matcher != null) {
+ return matcher.matches(item.getMessage(Locale.ROOT));
+ } else {
+ return true;
+ }
+ }
+
+ public static HasDiagnostic matching(final Diagnostic.Kind kind, final Matcher matcher) {
+ return new HasDiagnostic(kind, matcher);
+ }
+
+ public static HasDiagnostic matching(final Diagnostic.Kind kind) {
+ return new HasDiagnostic(kind, null);
+ }
+ }
+}
diff --git a/server/src/test/java/org/opensearch/common/collect/IteratorsTests.java b/libs/common/src/test/java/org/opensearch/common/collect/IteratorsTests.java
similarity index 98%
rename from server/src/test/java/org/opensearch/common/collect/IteratorsTests.java
rename to libs/common/src/test/java/org/opensearch/common/collect/IteratorsTests.java
index 6ad272542dbb1..2578926454c0b 100644
--- a/server/src/test/java/org/opensearch/common/collect/IteratorsTests.java
+++ b/libs/common/src/test/java/org/opensearch/common/collect/IteratorsTests.java
@@ -83,6 +83,7 @@ public void testRandomSingleton() {
int numberOfIterators = randomIntBetween(1, 1000);
int singletonIndex = randomIntBetween(0, numberOfIterators - 1);
int value = randomInt();
+ @SuppressWarnings("rawtypes")
Iterator[] iterators = new Iterator[numberOfIterators];
for (int i = 0; i < numberOfIterators; i++) {
iterators[i] = i != singletonIndex ? empty() : singletonIterator(value);
@@ -92,6 +93,7 @@ public void testRandomSingleton() {
public void testRandomIterators() {
int numberOfIterators = randomIntBetween(1, 1000);
+ @SuppressWarnings("rawtypes")
Iterator[] iterators = new Iterator[numberOfIterators];
List values = new ArrayList<>();
for (int i = 0; i < numberOfIterators; i++) {
diff --git a/libs/common/src/test/java/org/opensearch/common/hash/T1Ha1Tests.java b/libs/common/src/test/java/org/opensearch/common/hash/T1Ha1Tests.java
new file mode 100644
index 0000000000000..e348fbf759bdd
--- /dev/null
+++ b/libs/common/src/test/java/org/opensearch/common/hash/T1Ha1Tests.java
@@ -0,0 +1,312 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.hash;
+
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.lang.invoke.VarHandle;
+import java.nio.ByteOrder;
+
+public class T1Ha1Tests extends HashFunctionTestCase {
+ private static final VarHandle LONG_HANDLE = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.LITTLE_ENDIAN);
+ private final byte[] scratch = new byte[8];
+
+ /**
+ * Inspired from the tests defined in the reference implementation:
+ * t1ha_selfcheck.c
+ */
+ public void testSelfCheck() {
+ byte[] testPattern = {
+ 0,
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 6,
+ 7,
+ (byte) 0xFF,
+ 0x7F,
+ 0x3F,
+ 0x1F,
+ 0xF,
+ 8,
+ 16,
+ 32,
+ 64,
+ (byte) 0x80,
+ (byte) 0xFE,
+ (byte) 0xFC,
+ (byte) 0xF8,
+ (byte) 0xF0,
+ (byte) 0xE0,
+ (byte) 0xC0,
+ (byte) 0xFD,
+ (byte) 0xFB,
+ (byte) 0xF7,
+ (byte) 0xEF,
+ (byte) 0xDF,
+ (byte) 0xBF,
+ 0x55,
+ (byte) 0xAA,
+ 11,
+ 17,
+ 19,
+ 23,
+ 29,
+ 37,
+ 42,
+ 43,
+ 'a',
+ 'b',
+ 'c',
+ 'd',
+ 'e',
+ 'f',
+ 'g',
+ 'h',
+ 'i',
+ 'j',
+ 'k',
+ 'l',
+ 'm',
+ 'n',
+ 'o',
+ 'p',
+ 'q',
+ 'r',
+ 's',
+ 't',
+ 'u',
+ 'v',
+ 'w',
+ 'x' };
+
+ // Reference hashes when using {@link Math::unsignedMultiplyHigh} in the mux64 step.
+ // These values match the ones defined in the reference implementation:
+ // https://github.com/erthink/t1ha/blob/master/src/t1ha1_selfcheck.c#L51-L72
+ long[] referenceUnsignedMultiplyHigh = {
+ 0L,
+ 0x6A580668D6048674L,
+ 0xA2FE904AFF0D0879L,
+ 0xE3AB9C06FAF4D023L,
+ 0x6AF1C60874C95442L,
+ 0xB3557E561A6C5D82L,
+ 0x0AE73C696F3D37C0L,
+ 0x5EF25F7062324941L,
+ 0x9B784F3B4CE6AF33L,
+ 0x6993BB206A74F070L,
+ 0xF1E95DF109076C4CL,
+ 0x4E1EB70C58E48540L,
+ 0x5FDD7649D8EC44E4L,
+ 0x559122C706343421L,
+ 0x380133D58665E93DL,
+ 0x9CE74296C8C55AE4L,
+ 0x3556F9A5757AB6D0L,
+ 0xF62751F7F25C469EL,
+ 0x851EEC67F6516D94L,
+ 0xED463EE3848A8695L,
+ 0xDC8791FEFF8ED3ACL,
+ 0x2569C744E1A282CFL,
+ 0xF90EB7C1D70A80B9L,
+ 0x68DFA6A1B8050A4CL,
+ 0x94CCA5E8210D2134L,
+ 0xF5CC0BEABC259F52L,
+ 0x40DBC1F51618FDA7L,
+ 0x0807945BF0FB52C6L,
+ 0xE5EF7E09DE70848DL,
+ 0x63E1DF35FEBE994AL,
+ 0x2025E73769720D5AL,
+ 0xAD6120B2B8A152E1L,
+ 0x2A71D9F13959F2B7L,
+ 0x8A20849A27C32548L,
+ 0x0BCBC9FE3B57884EL,
+ 0x0E028D255667AEADL,
+ 0xBE66DAD3043AB694L,
+ 0xB00E4C1238F9E2D4L,
+ 0x5C54BDE5AE280E82L,
+ 0x0E22B86754BC3BC4L,
+ 0x016707EBF858B84DL,
+ 0x990015FBC9E095EEL,
+ 0x8B9AF0A3E71F042FL,
+ 0x6AA56E88BD380564L,
+ 0xAACE57113E681A0FL,
+ 0x19F81514AFA9A22DL,
+ 0x80DABA3D62BEAC79L,
+ 0x715210412CABBF46L,
+ 0xD8FA0B9E9D6AA93FL,
+ 0x6C2FC5A4109FD3A2L,
+ 0x5B3E60EEB51DDCD8L,
+ 0x0A7C717017756FE7L,
+ 0xA73773805CA31934L,
+ 0x4DBD6BB7A31E85FDL,
+ 0x24F619D3D5BC2DB4L,
+ 0x3E4AF35A1678D636L,
+ 0x84A1A8DF8D609239L,
+ 0x359C862CD3BE4FCDL,
+ 0xCF3A39F5C27DC125L,
+ 0xC0FF62F8FD5F4C77L,
+ 0x5E9F2493DDAA166CL,
+ 0x17424152BE1CA266L,
+ 0xA78AFA5AB4BBE0CDL,
+ 0x7BFB2E2CEF118346L,
+ 0x647C3E0FF3E3D241L,
+ 0x0352E4055C13242EL,
+ 0x6F42FC70EB660E38L,
+ 0x0BEBAD4FABF523BAL,
+ 0x9269F4214414D61DL,
+ 0x1CA8760277E6006CL,
+ 0x7BAD25A859D87B5DL,
+ 0xAD645ADCF7414F1DL,
+ 0xB07F517E88D7AFB3L,
+ 0xB321C06FB5FFAB5CL,
+ 0xD50F162A1EFDD844L,
+ 0x1DFD3D1924FBE319L,
+ 0xDFAEAB2F09EF7E78L,
+ 0xA7603B5AF07A0B1EL,
+ 0x41CD044C0E5A4EE3L,
+ 0xF64D2F86E813BF33L,
+ 0xFF9FDB99305EB06AL };
+
+ // Reference hashes when using {@link Math::multiplyHigh} in the mux64 step.
+ long[] referenceMultiplyHigh = {
+ 0L,
+ 0xCE510B7405E0A2CAL,
+ 0xC0A2DA74A8271FCBL,
+ 0x1C549C06FAF4D023L,
+ 0x084CDA0ED41CD2D4L,
+ 0xD05BA7AA9FEECE5BL,
+ 0x7D6128AB2CCC4EB1L,
+ 0x62332FA6EC1B50AAL,
+ 0x1B66C81767870EF2L,
+ 0xEC6B92A37AED73B8L,
+ 0x1712987232EF4ED3L,
+ 0xAA503A04AE2450B5L,
+ 0x15D25DE445730A6CL,
+ 0xAB87E38AA8D21746L,
+ 0x18CAE735BBF62D15L,
+ 0x0D56DFF9914CA656L,
+ 0xCB4F5859A9AE5B52L,
+ 0xEE97003F7B1283E1L,
+ 0x50CFB2AF0F54BA6DL,
+ 0x570B4D6AE4C67814L,
+ 0x1ED59274A97497EBL,
+ 0x8608D03D165C59BFL,
+ 0x6CBE0E537BE04C02L,
+ 0xD4C8FCFD4179A874L,
+ 0xFB4E677D876118A1L,
+ 0x6B1A96F1B4765D79L,
+ 0x1075B9B89BDFE5F8L,
+ 0x02771D08F2891CB1L,
+ 0x4BB8E16FF410F19EL,
+ 0x3EB7849C0DFAF566L,
+ 0x173B09359DE422CFL,
+ 0xFE212C6DB7474306L,
+ 0xA74E7C2D632664EFL,
+ 0x56ECDED6546F0914L,
+ 0x08DEF866EF20A94BL,
+ 0x7D0BAC64606521F1L,
+ 0xCA6BA9817A357FA9L,
+ 0x0873B834A6E2AAE4L,
+ 0x45EE02D6DCF8992EL,
+ 0x3EA060225B3E1C1FL,
+ 0x24DBB6D02D5CC531L,
+ 0xE5E91A7340BF9382L,
+ 0x28975F86E2E2177FL,
+ 0x80E48374A6B42E85L,
+ 0xDF40392265BB4A66L,
+ 0x43750475A48C7023L,
+ 0x5648BD3E391C01D3L,
+ 0x9BE9E11AD1A6C369L,
+ 0x2E079CB8C1A11F50L,
+ 0xB2D538403F1020F1L,
+ 0x297518A4EF6AF5F1L,
+ 0xA8CE1B90167A6F8BL,
+ 0xB926B2FA50541BA9L,
+ 0xC46A2D3BD6925A35L,
+ 0x3071BC8E6C400487L,
+ 0x300D3885894BA47FL,
+ 0x840BFF3BEB7EEADDL,
+ 0xDC9E04DF744BDC0CL,
+ 0xBE01CF6841412C77L,
+ 0x6C55B2DC74B816A1L,
+ 0x4D4C63128A344F82L,
+ 0xC6227497E100B463L,
+ 0x53C9987705EA71C0L,
+ 0x3E355394668C3559L,
+ 0x05984B7D358B107AL,
+ 0x4D32FA1D79002A57L,
+ 0x910B0DAD1440EC24L,
+ 0x025BDE6A7BEBF320L,
+ 0x0D33817EF345D999L,
+ 0xBA0DE64B3F4DB34AL,
+ 0x54666461D0EB4FD7L,
+ 0x746ECFA92D1CAF81L,
+ 0x6E6A774ACD266DF2L,
+ 0x1A86161AE8E82A85L,
+ 0xFFF7C351A4CEC13DL,
+ 0xFFF05844F57498B8L,
+ 0x8DB71789127C6C13L,
+ 0x4A52ACF805F370ABL,
+ 0xFE13F90A1ACFBD58L,
+ 0x615730E301ED12E2L,
+ 0x1A2D4AA43B6C0103L };
+
+ long[] reference = hasUnsignedMultiplyHigh() ? referenceUnsignedMultiplyHigh : referenceMultiplyHigh;
+
+ int offset = 0;
+ assertEquals(reference[offset++], T1ha1.hash(null, 0, 0, 0L)); // empty-zero
+ assertEquals(reference[offset++], T1ha1.hash(null, 0, 0, ~0L)); // empty-all1
+ assertEquals(reference[offset++], T1ha1.hash(testPattern, 0, 64, 0L)); // bin64-zero
+
+ long seed = 1;
+ for (int i = 1; i < 64; i++) {
+ assertEquals(reference[offset++], T1ha1.hash(testPattern, 0, i, seed)); // bin%i-1p%i
+ seed <<= 1;
+ }
+
+ seed = ~0L;
+ for (int i = 1; i <= 7; i++) {
+ seed <<= 1;
+ assertEquals(reference[offset++], T1ha1.hash(testPattern, i, 64 - i, seed)); // align%i_F%i
+ }
+
+ byte[] testPatternLong = new byte[512];
+ for (int i = 0; i < testPatternLong.length; i++) {
+ testPatternLong[i] = (byte) i;
+ }
+ for (int i = 0; i <= 7; i++) {
+ assertEquals(reference[offset++], T1ha1.hash(testPatternLong, i, 128 + i * 17, seed)); // long-%05i
+ }
+ }
+
+ @Override
+ public byte[] hash(byte[] input) {
+ long hash = T1ha1.hash(input, 0, input.length);
+ LONG_HANDLE.set(scratch, 0, hash);
+ return scratch;
+ }
+
+ @Override
+ public int outputBits() {
+ return 64;
+ }
+
+ private static boolean hasUnsignedMultiplyHigh() {
+ try {
+ MethodHandles.publicLookup()
+ .findStatic(Math.class, "unsignedMultiplyHigh", MethodType.methodType(long.class, long.class, long.class));
+ return true;
+ } catch (NoSuchMethodException e) {
+ return false;
+ } catch (IllegalAccessException e) {
+ throw new RuntimeException(e);
+ }
+ }
+}
diff --git a/server/src/test/java/org/opensearch/common/network/CidrsTests.java b/libs/common/src/test/java/org/opensearch/common/network/CidrsTests.java
similarity index 100%
rename from server/src/test/java/org/opensearch/common/network/CidrsTests.java
rename to libs/common/src/test/java/org/opensearch/common/network/CidrsTests.java
diff --git a/server/src/test/java/org/opensearch/common/network/InetAddressesTests.java b/libs/common/src/test/java/org/opensearch/common/network/InetAddressesTests.java
similarity index 100%
rename from server/src/test/java/org/opensearch/common/network/InetAddressesTests.java
rename to libs/common/src/test/java/org/opensearch/common/network/InetAddressesTests.java
diff --git a/server/src/test/java/org/opensearch/common/network/NetworkAddressTests.java b/libs/common/src/test/java/org/opensearch/common/network/NetworkAddressTests.java
similarity index 100%
rename from server/src/test/java/org/opensearch/common/network/NetworkAddressTests.java
rename to libs/common/src/test/java/org/opensearch/common/network/NetworkAddressTests.java
diff --git a/server/src/test/java/org/opensearch/common/recycler/AbstractRecyclerTestCase.java b/libs/common/src/test/java/org/opensearch/common/recycler/AbstractRecyclerTestCase.java
similarity index 100%
rename from server/src/test/java/org/opensearch/common/recycler/AbstractRecyclerTestCase.java
rename to libs/common/src/test/java/org/opensearch/common/recycler/AbstractRecyclerTestCase.java
diff --git a/server/src/test/java/org/opensearch/common/recycler/ConcurrentRecyclerTests.java b/libs/common/src/test/java/org/opensearch/common/recycler/ConcurrentRecyclerTests.java
similarity index 100%
rename from server/src/test/java/org/opensearch/common/recycler/ConcurrentRecyclerTests.java
rename to libs/common/src/test/java/org/opensearch/common/recycler/ConcurrentRecyclerTests.java
diff --git a/server/src/test/java/org/opensearch/common/recycler/LockedRecyclerTests.java b/libs/common/src/test/java/org/opensearch/common/recycler/LockedRecyclerTests.java
similarity index 100%
rename from server/src/test/java/org/opensearch/common/recycler/LockedRecyclerTests.java
rename to libs/common/src/test/java/org/opensearch/common/recycler/LockedRecyclerTests.java
diff --git a/server/src/test/java/org/opensearch/common/recycler/NoneRecyclerTests.java b/libs/common/src/test/java/org/opensearch/common/recycler/NoneRecyclerTests.java
similarity index 100%
rename from server/src/test/java/org/opensearch/common/recycler/NoneRecyclerTests.java
rename to libs/common/src/test/java/org/opensearch/common/recycler/NoneRecyclerTests.java
diff --git a/server/src/test/java/org/opensearch/common/recycler/QueueRecyclerTests.java b/libs/common/src/test/java/org/opensearch/common/recycler/QueueRecyclerTests.java
similarity index 100%
rename from server/src/test/java/org/opensearch/common/recycler/QueueRecyclerTests.java
rename to libs/common/src/test/java/org/opensearch/common/recycler/QueueRecyclerTests.java
diff --git a/libs/common/src/test/java/org/opensearch/common/round/RoundableTests.java b/libs/common/src/test/java/org/opensearch/common/round/RoundableTests.java
new file mode 100644
index 0000000000000..ad19f456b0df4
--- /dev/null
+++ b/libs/common/src/test/java/org/opensearch/common/round/RoundableTests.java
@@ -0,0 +1,71 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.round;
+
+import org.opensearch.test.OpenSearchTestCase;
+
+public class RoundableTests extends OpenSearchTestCase {
+
+ public void testRoundingEmptyArray() {
+ Throwable throwable = assertThrows(IllegalArgumentException.class, () -> RoundableFactory.create(new long[0], 0));
+ assertEquals("at least one value must be present", throwable.getMessage());
+ }
+
+ public void testRoundingSmallArray() {
+ int size = randomIntBetween(1, 64);
+ long[] values = randomArrayOfSortedValues(size);
+ Roundable roundable = RoundableFactory.create(values, size);
+
+ assertEquals("BidirectionalLinearSearcher", roundable.getClass().getSimpleName());
+ assertRounding(roundable, values, size);
+ }
+
+ public void testRoundingLargeArray() {
+ int size = randomIntBetween(65, 256);
+ long[] values = randomArrayOfSortedValues(size);
+ Roundable roundable = RoundableFactory.create(values, size);
+
+ boolean useBtreeSearcher = "forced".equalsIgnoreCase(System.getProperty("opensearch.experimental.feature.simd.rounding.enabled"));
+ assertEquals(useBtreeSearcher ? "BtreeSearcher" : "BinarySearcher", roundable.getClass().getSimpleName());
+ assertRounding(roundable, values, size);
+ }
+
+ private void assertRounding(Roundable roundable, long[] values, int size) {
+ for (int i = 0; i < 100000; i++) {
+ // Index of the expected round-down point.
+ int idx = randomIntBetween(0, size - 1);
+
+ // Value of the expected round-down point.
+ long expected = values[idx];
+
+ // Delta between the expected and the next round-down point.
+ long delta = (idx < size - 1) ? (values[idx + 1] - values[idx]) : 200;
+
+ // Adding a random delta between 0 (inclusive) and delta (exclusive) to the expected
+ // round-down point, which will still floor to the same value.
+ long key = expected + (randomNonNegativeLong() % delta);
+
+ assertEquals(expected, roundable.floor(key));
+ }
+
+ Throwable throwable = assertThrows(AssertionError.class, () -> roundable.floor(values[0] - 1));
+ assertEquals("key must be greater than or equal to " + values[0], throwable.getMessage());
+ }
+
+ private static long[] randomArrayOfSortedValues(int size) {
+ int capacity = size + randomInt(20); // May be slightly more than the size.
+ long[] values = new long[capacity];
+
+ for (int i = 1; i < size; i++) {
+ values[i] = values[i - 1] + (randomNonNegativeLong() % 200) + 1;
+ }
+
+ return values;
+ }
+}
diff --git a/libs/common/src/test/resources/org/acme/PublicApiAnnotated.java b/libs/common/src/test/resources/org/acme/PublicApiAnnotated.java
new file mode 100644
index 0000000000000..bc16fd996e69d
--- /dev/null
+++ b/libs/common/src/test/resources/org/acme/PublicApiAnnotated.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.acme;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiAnnotated {
+
+}
diff --git a/libs/common/src/test/resources/org/opensearch/bootstrap/test.policy b/libs/common/src/test/resources/org/opensearch/bootstrap/test.policy
new file mode 100644
index 0000000000000..e0a183b7eac88
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/bootstrap/test.policy
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+grant {
+ // allow to use JVM tooling (Java Compiler) in tests for annotation processing
+ permission java.io.FilePermission "${java.home}/lib/*", "read";
+ permission java.io.FilePermission "${java.home}/lib/modules/*", "read";
+ permission java.lang.RuntimePermission "accessSystemModules";
+ permission java.lang.RuntimePermission "accessDeclaredMembers";
+ permission java.lang.RuntimePermission "accessClassInPackage.*";
+};
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/DeprecatedApiMethodReturnSelf.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/DeprecatedApiMethodReturnSelf.java
new file mode 100644
index 0000000000000..7c5b6f6ea2f51
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/DeprecatedApiMethodReturnSelf.java
@@ -0,0 +1,18 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.DeprecatedApi;
+
+@DeprecatedApi(since = "1.0.0")
+public class DeprecatedApiMethodReturnSelf {
+ public DeprecatedApiMethodReturnSelf method() {
+ return new DeprecatedApiMethodReturnSelf();
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/ExperimentalApiAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/ExperimentalApiAnnotated.java
new file mode 100644
index 0000000000000..5be07e22c811f
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/ExperimentalApiAnnotated.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.ExperimentalApi;
+
+@ExperimentalApi
+public class ExperimentalApiAnnotated {
+
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/ExperimentalApiMethodReturnSelf.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/ExperimentalApiMethodReturnSelf.java
new file mode 100644
index 0000000000000..cde8f4f254faf
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/ExperimentalApiMethodReturnSelf.java
@@ -0,0 +1,18 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.ExperimentalApi;
+
+@ExperimentalApi
+public class ExperimentalApiMethodReturnSelf {
+ public ExperimentalApiMethodReturnSelf method() {
+ return new ExperimentalApiMethodReturnSelf();
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/InternalApiAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/InternalApiAnnotated.java
new file mode 100644
index 0000000000000..9996ba8b736aa
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/InternalApiAnnotated.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class InternalApiAnnotated {
+
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/NotAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/NotAnnotated.java
new file mode 100644
index 0000000000000..ec16ce926ea86
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/NotAnnotated.java
@@ -0,0 +1,13 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+public class NotAnnotated {
+
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/NotAnnotatedAnnotation.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/NotAnnotatedAnnotation.java
new file mode 100644
index 0000000000000..a3e9c4f576d92
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/NotAnnotatedAnnotation.java
@@ -0,0 +1,27 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Target;
+
+@Target({
+ ElementType.TYPE,
+ ElementType.TYPE_PARAMETER,
+ ElementType.TYPE_USE,
+ ElementType.PACKAGE,
+ ElementType.METHOD,
+ ElementType.CONSTRUCTOR,
+ ElementType.PARAMETER,
+ ElementType.FIELD,
+ ElementType.ANNOTATION_TYPE,
+ ElementType.MODULE })
+public @interface NotAnnotatedAnnotation {
+
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/NotAnnotatedException.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/NotAnnotatedException.java
new file mode 100644
index 0000000000000..0aadaf8f9bf31
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/NotAnnotatedException.java
@@ -0,0 +1,13 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+public class NotAnnotatedException extends Exception {
+ private static final long serialVersionUID = 1L;
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiAnnotated.java
new file mode 100644
index 0000000000000..b2a7f03cb2d31
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiAnnotated.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiAnnotated {
+
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiConstructorArgumentAnnotatedInternalApi.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiConstructorArgumentAnnotatedInternalApi.java
new file mode 100644
index 0000000000000..6bea2961a14e6
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiConstructorArgumentAnnotatedInternalApi.java
@@ -0,0 +1,20 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.InternalApi;
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiConstructorArgumentAnnotatedInternalApi {
+ /**
+ * The constructor arguments have relaxed semantics at the moment: those could be not annotated or be annotated as {@link InternalApi}
+ */
+ public PublicApiConstructorArgumentAnnotatedInternalApi(InternalApiAnnotated arg) {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiConstructorArgumentNotAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiConstructorArgumentNotAnnotated.java
new file mode 100644
index 0000000000000..6c7481d9978cd
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiConstructorArgumentNotAnnotated.java
@@ -0,0 +1,20 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.InternalApi;
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiConstructorArgumentNotAnnotated {
+ /**
+ * The constructor arguments have relaxed semantics at the moment: those could be not annotated or be annotated as {@link InternalApi}
+ */
+ public PublicApiConstructorArgumentNotAnnotated(NotAnnotated arg) {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentAnnotatedPackagePrivate.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentAnnotatedPackagePrivate.java
new file mode 100644
index 0000000000000..5dae56a7cd7d3
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentAnnotatedPackagePrivate.java
@@ -0,0 +1,20 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodArgumentAnnotatedPackagePrivate {
+ public void method(AnnotatedPackagePrivate arg) {}
+}
+
+// The public API exposes this class through public method argument, it should be public
+@PublicApi(since = "1.0.0")
+class AnnotatedPackagePrivate {}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentNotAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentNotAnnotated.java
new file mode 100644
index 0000000000000..ddfec939f79e8
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentNotAnnotated.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodArgumentNotAnnotated {
+ public void method(NotAnnotated arg) {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentNotAnnotatedGenerics.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentNotAnnotatedGenerics.java
new file mode 100644
index 0000000000000..d32502831d299
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentNotAnnotatedGenerics.java
@@ -0,0 +1,18 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+import java.util.Collection;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodArgumentNotAnnotatedGenerics {
+ public void method(Collection super NotAnnotated> arg) {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentNotAnnotatedPackagePrivate.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentNotAnnotatedPackagePrivate.java
new file mode 100644
index 0000000000000..d4fb31b172ef2
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodArgumentNotAnnotatedPackagePrivate.java
@@ -0,0 +1,19 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodArgumentNotAnnotatedPackagePrivate {
+ public void method(NotAnnotatedPackagePrivate arg) {}
+}
+
+// The public API exposes this class through public method argument, it should be annotated and be public
+class NotAnnotatedPackagePrivate {}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodGenericsArgumentAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodGenericsArgumentAnnotated.java
new file mode 100644
index 0000000000000..9715748cfa659
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodGenericsArgumentAnnotated.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodGenericsArgumentAnnotated {
+ public void method(T arg) {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodGenericsArgumentNotAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodGenericsArgumentNotAnnotated.java
new file mode 100644
index 0000000000000..f149c1f34b067
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodGenericsArgumentNotAnnotated.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodGenericsArgumentNotAnnotated {
+ public void method(T arg) {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnAnnotatedArray.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnAnnotatedArray.java
new file mode 100644
index 0000000000000..39b7e146fe1e7
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnAnnotatedArray.java
@@ -0,0 +1,18 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodReturnAnnotatedArray {
+ public PublicApiAnnotated[] method() {
+ return new PublicApiAnnotated[0];
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnAnnotatedGenerics.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnAnnotatedGenerics.java
new file mode 100644
index 0000000000000..2171eccee2f31
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnAnnotatedGenerics.java
@@ -0,0 +1,23 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+import java.util.Collection;
+import java.util.Collections;
+
+import org.acme.PublicApiAnnotated;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodReturnAnnotatedGenerics {
+ public Collection<@NotAnnotatedAnnotation PublicApiAnnotated> method() {
+ return Collections.emptyList();
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotated.java
new file mode 100644
index 0000000000000..725d06072d0ea
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotated.java
@@ -0,0 +1,18 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodReturnNotAnnotated {
+ public NotAnnotated method() {
+ return new NotAnnotated();
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedAnnotation.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedAnnotation.java
new file mode 100644
index 0000000000000..b684e36a53da1
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedAnnotation.java
@@ -0,0 +1,18 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodReturnNotAnnotatedAnnotation {
+ public @NotAnnotatedAnnotation PublicApiAnnotated method() {
+ return new PublicApiAnnotated();
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedArray.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedArray.java
new file mode 100644
index 0000000000000..e4c541dcea57f
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedArray.java
@@ -0,0 +1,18 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodReturnNotAnnotatedArray {
+ public NotAnnotated[] method() {
+ return new NotAnnotated[0];
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedBoundedGenerics.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedBoundedGenerics.java
new file mode 100644
index 0000000000000..0646faf152610
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedBoundedGenerics.java
@@ -0,0 +1,21 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+import java.util.Collection;
+import java.util.Collections;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodReturnNotAnnotatedBoundedGenerics {
+ public Collection extends NotAnnotated> method() {
+ return Collections.emptyList();
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedGenerics.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedGenerics.java
new file mode 100644
index 0000000000000..2227883c707d0
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedGenerics.java
@@ -0,0 +1,21 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+import java.util.Collection;
+import java.util.Collections;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodReturnNotAnnotatedGenerics {
+ public Collection method() {
+ return Collections.emptyList();
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedWildcardGenerics.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedWildcardGenerics.java
new file mode 100644
index 0000000000000..f2818ebb23c4a
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnNotAnnotatedWildcardGenerics.java
@@ -0,0 +1,21 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+import java.util.Collection;
+import java.util.Collections;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodReturnNotAnnotatedWildcardGenerics {
+ public Collection> method() {
+ return Collections.emptyList();
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnSelf.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnSelf.java
new file mode 100644
index 0000000000000..883471b23ae0f
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodReturnSelf.java
@@ -0,0 +1,18 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodReturnSelf {
+ public PublicApiMethodReturnSelf method() {
+ return new PublicApiMethodReturnSelf();
+ }
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodThrowsNotAnnotated.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodThrowsNotAnnotated.java
new file mode 100644
index 0000000000000..496b243276565
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiMethodThrowsNotAnnotated.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiMethodThrowsNotAnnotated {
+ public void method(PublicApiAnnotated arg) throws NotAnnotatedException {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiPackagePrivate.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiPackagePrivate.java
new file mode 100644
index 0000000000000..88c20e7f4c8f1
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiPackagePrivate.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+class PublicApiPackagePrivate {
+ void method() {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithExperimentalApiMethod.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithExperimentalApiMethod.java
new file mode 100644
index 0000000000000..faaaa1d9f4051
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithExperimentalApiMethod.java
@@ -0,0 +1,18 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.ExperimentalApi;
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiWithExperimentalApiMethod {
+ @ExperimentalApi
+ public void method() {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithInternalApiMethod.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithInternalApiMethod.java
new file mode 100644
index 0000000000000..5bfa3c9f3e008
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithInternalApiMethod.java
@@ -0,0 +1,19 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.InternalApi;
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiWithInternalApiMethod {
+ // The public API exposes internal API method, it should be public API
+ @InternalApi
+ public void method() {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithPackagePrivateMethod.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithPackagePrivateMethod.java
new file mode 100644
index 0000000000000..1345467423530
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithPackagePrivateMethod.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiWithPackagePrivateMethod {
+ void method(NotAnnotated arg) {}
+}
diff --git a/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithProtectedInterface.java b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithProtectedInterface.java
new file mode 100644
index 0000000000000..222ae01fd15e6
--- /dev/null
+++ b/libs/common/src/test/resources/org/opensearch/common/annotation/processor/PublicApiWithProtectedInterface.java
@@ -0,0 +1,22 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.common.annotation.processor;
+
+import org.opensearch.common.annotation.PublicApi;
+
+@PublicApi(since = "1.0.0")
+public class PublicApiWithProtectedInterface {
+ public void method(ProtectedInterface iface) {}
+
+ /**
+ * The type could expose protected inner types which are still considered to be a public API when used
+ */
+ @PublicApi(since = "1.0.0")
+ protected interface ProtectedInterface {}
+}
diff --git a/libs/compress/build.gradle b/libs/compress/build.gradle
new file mode 100644
index 0000000000000..7a5bc2f573dea
--- /dev/null
+++ b/libs/compress/build.gradle
@@ -0,0 +1,38 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ *
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+apply plugin: 'opensearch.build'
+apply plugin: 'opensearch.publish'
+
+base {
+ archivesName = 'opensearch-compress'
+}
+
+dependencies {
+ api project(':libs:opensearch-common')
+ api project(':libs:opensearch-core')
+
+ //zstd
+ api "com.github.luben:zstd-jni:${versions.zstd}"
+
+ testImplementation(project(":test:framework")) {
+ // tests use the locally compiled version of server
+ exclude group: 'org.opensearch', module: 'opensearch-compress'
+ }
+}
+
+tasks.named('forbiddenApisMain').configure {
+ // :libs:opensearch-compress does not depend on server
+ // TODO: Need to decide how we want to handle for forbidden signatures with the changes to server
+ replaceSignatureFiles 'jdk-signatures'
+}
+
+jarHell.enabled = false
diff --git a/libs/compress/licenses/zstd-jni-1.5.5-5.jar.sha1 b/libs/compress/licenses/zstd-jni-1.5.5-5.jar.sha1
new file mode 100644
index 0000000000000..498c60c34e3da
--- /dev/null
+++ b/libs/compress/licenses/zstd-jni-1.5.5-5.jar.sha1
@@ -0,0 +1 @@
+74ffdc5f140080adacf5278287aadd950179f848
\ No newline at end of file
diff --git a/server/licenses/zstd-jni-LICENSE.txt b/libs/compress/licenses/zstd-jni-LICENSE.txt
similarity index 100%
rename from server/licenses/zstd-jni-LICENSE.txt
rename to libs/compress/licenses/zstd-jni-LICENSE.txt
diff --git a/server/licenses/zstd-jni-NOTICE.txt b/libs/compress/licenses/zstd-jni-NOTICE.txt
similarity index 100%
rename from server/licenses/zstd-jni-NOTICE.txt
rename to libs/compress/licenses/zstd-jni-NOTICE.txt
diff --git a/libs/compress/src/main/java/org/opensearch/compress/ZstdCompressor.java b/libs/compress/src/main/java/org/opensearch/compress/ZstdCompressor.java
new file mode 100644
index 0000000000000..e2a740f72be93
--- /dev/null
+++ b/libs/compress/src/main/java/org/opensearch/compress/ZstdCompressor.java
@@ -0,0 +1,136 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.compress;
+
+import com.github.luben.zstd.RecyclingBufferPool;
+import com.github.luben.zstd.ZstdInputStreamNoFinalizer;
+import com.github.luben.zstd.ZstdOutputStreamNoFinalizer;
+
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.compress.Compressor;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Arrays;
+
+/**
+ * {@link Compressor} implementation based on the ZSTD compression algorithm.
+ *
+ * @opensearch.api - registered name requires BWC support
+ * @opensearch.experimental - class methods might change
+ */
+public class ZstdCompressor implements Compressor {
+
+ /**
+ * An arbitrary header that we use to identify compressed streams
+ * It needs to be different from other compressors and to not be specific
+ * enough so that no stream starting with these bytes could be detected as
+ * a XContent
+ * */
+ private static final byte[] HEADER = new byte[] { 'Z', 'S', 'T', 'D', '\0' };
+
+ /**
+ * The name to register the compressor by
+ *
+ * @opensearch.api - requires BWC support
+ */
+ @PublicApi(since = "2.10.0")
+ public static final String NAME = "ZSTD";
+
+ /**
+ * The compression level for {@link ZstdOutputStreamNoFinalizer}
+ */
+ private static final int LEVEL = 3;
+
+ /** The buffer size for {@link BufferedInputStream} and {@link BufferedOutputStream}
+ */
+ private static final int BUFFER_SIZE = 4096;
+
+ /**
+ * Compares the given bytes with the {@link ZstdCompressor#HEADER} of a compressed stream
+ * @param bytes the bytes to compare to ({@link ZstdCompressor#HEADER})
+ * @return true if the bytes are the {@link ZstdCompressor#HEADER}, false otherwise
+ */
+ @Override
+ public boolean isCompressed(BytesReference bytes) {
+ if (bytes.length() < HEADER.length) {
+ return false;
+ }
+ for (int i = 0; i < HEADER.length; ++i) {
+ if (bytes.get(i) != HEADER[i]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns the length of the {@link ZstdCompressor#HEADER}
+ * @return the {@link ZstdCompressor#HEADER} length
+ */
+ @Override
+ public int headerLength() {
+ return HEADER.length;
+ }
+
+ /**
+ * Returns a new {@link ZstdInputStreamNoFinalizer} from the given compressed {@link InputStream}
+ * @param in the compressed {@link InputStream}
+ * @return a new {@link ZstdInputStreamNoFinalizer} from the given compressed {@link InputStream}
+ * @throws IOException if an I/O error occurs
+ * @throws IllegalArgumentException if the input stream is not compressed with ZSTD
+ */
+ @Override
+ public InputStream threadLocalInputStream(InputStream in) throws IOException {
+ final byte[] header = in.readNBytes(HEADER.length);
+ if (Arrays.equals(header, HEADER) == false) {
+ throw new IllegalArgumentException("Input stream is not compressed with ZSTD!");
+ }
+ return new ZstdInputStreamNoFinalizer(new BufferedInputStream(in, BUFFER_SIZE), RecyclingBufferPool.INSTANCE);
+ }
+
+ /**
+ * Returns a new {@link ZstdOutputStreamNoFinalizer} from the given {@link OutputStream}
+ * @param out the {@link OutputStream}
+ * @return a new {@link ZstdOutputStreamNoFinalizer} from the given {@link OutputStream}
+ * @throws IOException if an I/O error occurs
+ */
+ @Override
+ public OutputStream threadLocalOutputStream(OutputStream out) throws IOException {
+ out.write(HEADER);
+ return new ZstdOutputStreamNoFinalizer(new BufferedOutputStream(out, BUFFER_SIZE), RecyclingBufferPool.INSTANCE, LEVEL);
+ }
+
+ /**
+ * Always throws an {@link UnsupportedOperationException} as ZSTD compression is supported only for snapshotting
+ * @param bytesReference a reference to the bytes to uncompress
+ * @return always throws an exception
+ * @throws UnsupportedOperationException if the method is called
+ * @throws IOException is never thrown
+ */
+ @Override
+ public BytesReference uncompress(BytesReference bytesReference) throws IOException {
+ throw new UnsupportedOperationException("ZSTD compression is supported only for snapshotting");
+ }
+
+ /**
+ * Always throws an {@link UnsupportedOperationException} as ZSTD compression is supported only for snapshotting
+ * @param bytesReference a reference to the bytes to compress
+ * @return always throws an exception
+ * @throws UnsupportedOperationException if the method is called
+ */
+ @Override
+ public BytesReference compress(BytesReference bytesReference) throws IOException {
+ throw new UnsupportedOperationException("ZSTD compression is supported only for snapshotting");
+ }
+}
diff --git a/libs/compress/src/main/java/org/opensearch/compress/package-info.java b/libs/compress/src/main/java/org/opensearch/compress/package-info.java
new file mode 100644
index 0000000000000..3ffa53079fa69
--- /dev/null
+++ b/libs/compress/src/main/java/org/opensearch/compress/package-info.java
@@ -0,0 +1,12 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Concrete {@link org.opensearch.core.compress.Compressor} implementations
+ */
+package org.opensearch.compress;
diff --git a/libs/compress/src/main/java/org/opensearch/compress/spi/CompressionProvider.java b/libs/compress/src/main/java/org/opensearch/compress/spi/CompressionProvider.java
new file mode 100644
index 0000000000000..f0c6969377d78
--- /dev/null
+++ b/libs/compress/src/main/java/org/opensearch/compress/spi/CompressionProvider.java
@@ -0,0 +1,35 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.compress.spi;
+
+import org.opensearch.compress.ZstdCompressor;
+import org.opensearch.core.compress.Compressor;
+import org.opensearch.core.compress.spi.CompressorProvider;
+
+import java.util.AbstractMap.SimpleEntry;
+import java.util.List;
+import java.util.Map.Entry;
+
+/**
+ * Additional "optional" compressor implementations provided by the opensearch compress library
+ *
+ * @opensearch.internal
+ */
+public class CompressionProvider implements CompressorProvider {
+
+ /**
+ * Returns the concrete {@link Compressor}s provided by the compress library
+ * @return a list of {@link Compressor}s
+ * */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Override
+ public List> getCompressors() {
+ return List.of(new SimpleEntry<>(ZstdCompressor.NAME, new ZstdCompressor()));
+ }
+}
diff --git a/libs/compress/src/main/java/org/opensearch/compress/spi/package-info.java b/libs/compress/src/main/java/org/opensearch/compress/spi/package-info.java
new file mode 100644
index 0000000000000..47d982a7ca2f9
--- /dev/null
+++ b/libs/compress/src/main/java/org/opensearch/compress/spi/package-info.java
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Service Provider Interface for registering concrete {@link org.opensearch.core.compress.Compressor}
+ * implementations.
+ *
+ * See {@link org.opensearch.compress.ZstdCompressor}
+ */
+package org.opensearch.compress.spi;
diff --git a/libs/compress/src/main/java/org/opensearch/package-info.java b/libs/compress/src/main/java/org/opensearch/package-info.java
new file mode 100644
index 0000000000000..264680e9cb271
--- /dev/null
+++ b/libs/compress/src/main/java/org/opensearch/package-info.java
@@ -0,0 +1,13 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * This is the compress library for registering optional
+ * {@link org.opensearch.core.compress.Compressor} implementations
+ */
+package org.opensearch;
diff --git a/libs/compress/src/main/resources/META-INF/services/org.opensearch.core.compress.spi.CompressorProvider b/libs/compress/src/main/resources/META-INF/services/org.opensearch.core.compress.spi.CompressorProvider
new file mode 100644
index 0000000000000..a9ea063e24436
--- /dev/null
+++ b/libs/compress/src/main/resources/META-INF/services/org.opensearch.core.compress.spi.CompressorProvider
@@ -0,0 +1,9 @@
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# The OpenSearch Contributors require contributions made to
+# this file be licensed under the Apache-2.0 license or a
+# compatible open source license.
+#
+
+org.opensearch.compress.spi.CompressionProvider
diff --git a/libs/compress/src/test/java/org/opensearch/compress/ZstdCompressTests.java b/libs/compress/src/test/java/org/opensearch/compress/ZstdCompressTests.java
new file mode 100644
index 0000000000000..54864054a0e02
--- /dev/null
+++ b/libs/compress/src/test/java/org/opensearch/compress/ZstdCompressTests.java
@@ -0,0 +1,25 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.compress;
+
+import org.opensearch.core.compress.Compressor;
+import org.opensearch.test.core.compress.AbstractCompressorTestCase;
+
+/**
+ * Test streaming compression
+ */
+public class ZstdCompressTests extends AbstractCompressorTestCase {
+
+ private final Compressor compressor = new ZstdCompressor();
+
+ @Override
+ protected Compressor compressor() {
+ return compressor;
+ }
+}
diff --git a/libs/core/build.gradle b/libs/core/build.gradle
index 46b6f4471731f..0cf2cd0bf92b6 100644
--- a/libs/core/build.gradle
+++ b/libs/core/build.gradle
@@ -33,46 +33,7 @@ import org.opensearch.gradle.info.BuildParams
apply plugin: 'opensearch.publish'
base {
- archivesBaseName = 'opensearch-core'
-}
-
-// we want to keep the JDKs in our IDEs set to JDK 8 until minimum JDK is bumped to 11 so we do not include this source set in our IDEs
-if (!isEclipse) {
- sourceSets {
- java11 {
- java {
- srcDirs = ['src/main/java11']
- }
- }
- }
-
- configurations {
- java11Compile.extendsFrom(compile)
- }
-
- dependencies {
- java11Implementation sourceSets.main.output
- }
-
- compileJava11Java {
- sourceCompatibility = JavaVersion.VERSION_11
- targetCompatibility = JavaVersion.VERSION_11
- }
-
- forbiddenApisJava11 {
- if (BuildParams.runtimeJavaVersion < JavaVersion.VERSION_11) {
- targetCompatibility = JavaVersion.VERSION_11
- }
- replaceSignatureFiles 'jdk-signatures'
- }
-
- jar {
- metaInf {
- into 'versions/11'
- from sourceSets.java11.output
- }
- manifest.attributes('Multi-Release': 'true')
- }
+ archivesName = 'opensearch-core'
}
dependencies {
diff --git a/libs/core/licenses/jackson-core-2.15.2.jar.sha1 b/libs/core/licenses/jackson-core-2.15.2.jar.sha1
deleted file mode 100644
index ec6781b968eed..0000000000000
--- a/libs/core/licenses/jackson-core-2.15.2.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-a6fe1836469a69b3ff66037c324d75fc66ef137c
\ No newline at end of file
diff --git a/libs/core/licenses/jackson-core-2.16.2.jar.sha1 b/libs/core/licenses/jackson-core-2.16.2.jar.sha1
new file mode 100644
index 0000000000000..68646a1e66ffc
--- /dev/null
+++ b/libs/core/licenses/jackson-core-2.16.2.jar.sha1
@@ -0,0 +1 @@
+b4f588bf070f77b604c645a7d60b71eae2e6ea09
\ No newline at end of file
diff --git a/libs/core/licenses/log4j-api-2.20.0.jar.sha1 b/libs/core/licenses/log4j-api-2.20.0.jar.sha1
deleted file mode 100644
index 37154d9861ac0..0000000000000
--- a/libs/core/licenses/log4j-api-2.20.0.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-1fe6082e660daf07c689a89c94dc0f49c26b44bb
\ No newline at end of file
diff --git a/libs/core/licenses/log4j-api-2.21.0.jar.sha1 b/libs/core/licenses/log4j-api-2.21.0.jar.sha1
new file mode 100644
index 0000000000000..51446052594aa
--- /dev/null
+++ b/libs/core/licenses/log4j-api-2.21.0.jar.sha1
@@ -0,0 +1 @@
+760192f2b69eacf4a4afc78e5a1d7a8de054fcbd
\ No newline at end of file
diff --git a/libs/core/licenses/lucene-core-9.11.0-snapshot-8a555eb.jar.sha1 b/libs/core/licenses/lucene-core-9.11.0-snapshot-8a555eb.jar.sha1
new file mode 100644
index 0000000000000..25beb34873c0c
--- /dev/null
+++ b/libs/core/licenses/lucene-core-9.11.0-snapshot-8a555eb.jar.sha1
@@ -0,0 +1 @@
+fe1cf5663be8bdb6aa757fd4101bc551684c90fb
\ No newline at end of file
diff --git a/libs/core/licenses/lucene-core-9.8.0-snapshot-4373c3b.jar.sha1 b/libs/core/licenses/lucene-core-9.8.0-snapshot-4373c3b.jar.sha1
deleted file mode 100644
index dc363f2776429..0000000000000
--- a/libs/core/licenses/lucene-core-9.8.0-snapshot-4373c3b.jar.sha1
+++ /dev/null
@@ -1 +0,0 @@
-30c3afcf058532d3d2b8820375043000e7f34a9b
\ No newline at end of file
diff --git a/libs/core/src/main/java/org/opensearch/Build.java b/libs/core/src/main/java/org/opensearch/Build.java
index 67a50a8a31a0e..b5d67f5501725 100644
--- a/libs/core/src/main/java/org/opensearch/Build.java
+++ b/libs/core/src/main/java/org/opensearch/Build.java
@@ -216,7 +216,7 @@ public String getDistribution() {
/**
* Get the version as considered at build time
- *
+ *
* Offers a way to get the fully qualified version as configured by the build.
* This will be the same as {@link Version} for production releases, but may include on of the qualifier ( e.x alpha1 )
* or -SNAPSHOT for others.
diff --git a/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java b/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java
index a03b2f94b27fe..9692d20a050ff 100644
--- a/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java
+++ b/libs/core/src/main/java/org/opensearch/ExceptionsHelper.java
@@ -33,16 +33,17 @@
package org.opensearch;
import com.fasterxml.jackson.core.JsonParseException;
+
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexFormatTooNewException;
import org.apache.lucene.index.IndexFormatTooOldException;
-import org.opensearch.core.action.ShardOperationFailedException;
import org.opensearch.common.CheckedRunnable;
import org.opensearch.common.CheckedSupplier;
import org.opensearch.common.Nullable;
-import org.opensearch.core.common.compress.NotXContentException;
+import org.opensearch.core.action.ShardOperationFailedException;
+import org.opensearch.core.compress.NotXContentException;
import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException;
import org.opensearch.core.index.Index;
import org.opensearch.core.rest.RestStatus;
diff --git a/libs/core/src/main/java/org/opensearch/LegacyESVersion.java b/libs/core/src/main/java/org/opensearch/LegacyESVersion.java
index 32eae654cf975..5d8e067a8fd8b 100644
--- a/libs/core/src/main/java/org/opensearch/LegacyESVersion.java
+++ b/libs/core/src/main/java/org/opensearch/LegacyESVersion.java
@@ -40,7 +40,7 @@
/**
* The Contents of this file were originally moved from {@link Version}.
- *
+ *
* This class keeps all the supported OpenSearch predecessor versions for
* backward compatibility purpose.
*
diff --git a/libs/core/src/main/java/org/opensearch/OpenSearchException.java b/libs/core/src/main/java/org/opensearch/OpenSearchException.java
index f75a225af1b4d..cce86b452f698 100644
--- a/libs/core/src/main/java/org/opensearch/OpenSearchException.java
+++ b/libs/core/src/main/java/org/opensearch/OpenSearchException.java
@@ -34,20 +34,20 @@
import org.opensearch.common.CheckedFunction;
import org.opensearch.common.Nullable;
import org.opensearch.common.collect.Tuple;
+import org.opensearch.core.ParseField;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.core.ParseField;
-import org.opensearch.core.common.Strings;
import org.opensearch.core.common.logging.LoggerMessageFormat;
+import org.opensearch.core.index.Index;
+import org.opensearch.core.index.shard.ShardId;
+import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ToXContent;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParseException;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.core.index.Index;
-import org.opensearch.core.index.shard.ShardId;
-import org.opensearch.core.rest.RestStatus;
import java.io.IOException;
import java.util.ArrayList;
@@ -61,12 +61,11 @@
import java.util.concurrent.ConcurrentHashMap;
import static java.util.Collections.emptyMap;
+import static java.util.Collections.singletonMap;
import static org.opensearch.OpenSearchException.OpenSearchExceptionHandleRegistry.registerExceptionHandle;
import static org.opensearch.core.xcontent.XContentParserUtils.ensureExpectedToken;
import static org.opensearch.core.xcontent.XContentParserUtils.ensureFieldName;
-import static java.util.Collections.singletonMap;
-
/**
* A core library base class for all opensearch exceptions.
*
@@ -118,6 +117,14 @@ public class OpenSearchException extends RuntimeException implements Writeable,
UNKNOWN_VERSION_ADDED
)
);
+ registerExceptionHandle(
+ new OpenSearchExceptionHandle(
+ org.opensearch.OpenSearchParseException.class,
+ org.opensearch.OpenSearchParseException::new,
+ 35,
+ UNKNOWN_VERSION_ADDED
+ )
+ );
registerExceptionHandle(
new OpenSearchExceptionHandle(
org.opensearch.core.common.ParsingException.class,
@@ -134,6 +141,22 @@ public class OpenSearchException extends RuntimeException implements Writeable,
UNKNOWN_VERSION_ADDED
)
);
+ registerExceptionHandle(
+ new OpenSearchExceptionHandle(
+ org.opensearch.core.common.breaker.CircuitBreakingException.class,
+ org.opensearch.core.common.breaker.CircuitBreakingException::new,
+ 133,
+ UNKNOWN_VERSION_ADDED
+ )
+ );
+ registerExceptionHandle(
+ new OpenSearchExceptionHandle(
+ org.opensearch.core.tasks.TaskCancelledException.class,
+ org.opensearch.core.tasks.TaskCancelledException::new,
+ 146,
+ UNKNOWN_VERSION_ADDED
+ )
+ );
}
/**
@@ -145,7 +168,7 @@ public OpenSearchException(Throwable cause) {
/**
* Construct a OpenSearchException
with the specified detail message.
- *
+ *
* The message can be parameterized using {}
as placeholders for the given
* arguments
*
@@ -159,7 +182,7 @@ public OpenSearchException(String msg, Object... args) {
/**
* Construct a OpenSearchException
with the specified detail message
* and nested exception.
- *
+ *
* The message can be parameterized using {}
as placeholders for the given
* arguments
*
@@ -564,7 +587,7 @@ public static OpenSearchException innerFromXContent(XContentParser parser, boole
* Static toXContent helper method that renders {@link OpenSearchException} or {@link Throwable} instances
* as XContent, delegating the rendering to {@link OpenSearchException#toXContent(XContentBuilder, ToXContent.Params)}
* or {@link #innerToXContent(XContentBuilder, ToXContent.Params, Throwable, String, String, Map, Map, Throwable)}.
- *
+ *
* This method is usually used when the {@link Throwable} is rendered as a part of another XContent object, and its result can
* be parsed back using the {@code OpenSearchException.fromXContent(XContentParser)} method.
*/
@@ -583,7 +606,7 @@ public static void generateThrowableXContent(XContentBuilder builder, ToXContent
* depends on the value of the "detailed" parameter: when it's false only a simple message based on the type and message of the
* exception is rendered. When it's true all detail are provided including guesses root causes, cause and potentially stack
* trace.
- *
+ *
* This method is usually used when the {@link Exception} is rendered as a full XContent object, and its output can be parsed
* by the {@code #OpenSearchException.failureFromXContent(XContentParser)} method.
*/
diff --git a/server/src/main/java/org/opensearch/OpenSearchParseException.java b/libs/core/src/main/java/org/opensearch/OpenSearchParseException.java
similarity index 94%
rename from server/src/main/java/org/opensearch/OpenSearchParseException.java
rename to libs/core/src/main/java/org/opensearch/OpenSearchParseException.java
index c2516402b0d30..26aff04b30a56 100644
--- a/server/src/main/java/org/opensearch/OpenSearchParseException.java
+++ b/libs/core/src/main/java/org/opensearch/OpenSearchParseException.java
@@ -32,6 +32,7 @@
package org.opensearch;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.rest.RestStatus;
@@ -40,8 +41,9 @@
/**
* Unchecked exception that is translated into a {@code 400 BAD REQUEST} error when it bubbles out over HTTP.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class OpenSearchParseException extends OpenSearchException {
public OpenSearchParseException(String msg, Object... args) {
diff --git a/libs/core/src/main/java/org/opensearch/Version.java b/libs/core/src/main/java/org/opensearch/Version.java
index 9329f221922ea..66ba446d4fc54 100644
--- a/libs/core/src/main/java/org/opensearch/Version.java
+++ b/libs/core/src/main/java/org/opensearch/Version.java
@@ -33,6 +33,7 @@
package org.opensearch;
import org.opensearch.common.SuppressForbidden;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
@@ -50,6 +51,7 @@
*
* @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class Version implements Comparable, ToXContentFragment {
/*
* The logic for ID is: XXYYZZAA, where XX is major version, YY is minor version, ZZ is revision, and AA is alpha/beta/rc indicator AA
@@ -90,8 +92,16 @@ public class Version implements Comparable, ToXContentFragment {
public static final Version V_2_8_0 = new Version(2080099, org.apache.lucene.util.Version.LUCENE_9_6_0);
public static final Version V_2_8_1 = new Version(2080199, org.apache.lucene.util.Version.LUCENE_9_6_0);
public static final Version V_2_9_0 = new Version(2090099, org.apache.lucene.util.Version.LUCENE_9_7_0);
+ public static final Version V_2_9_1 = new Version(2090199, org.apache.lucene.util.Version.LUCENE_9_7_0);
public static final Version V_2_10_0 = new Version(2100099, org.apache.lucene.util.Version.LUCENE_9_7_0);
- public static final Version V_3_0_0 = new Version(3000099, org.apache.lucene.util.Version.LUCENE_9_8_0);
+ public static final Version V_2_10_1 = new Version(2100199, org.apache.lucene.util.Version.LUCENE_9_7_0);
+ public static final Version V_2_11_0 = new Version(2110099, org.apache.lucene.util.Version.LUCENE_9_7_0);
+ public static final Version V_2_11_1 = new Version(2110199, org.apache.lucene.util.Version.LUCENE_9_7_0);
+ public static final Version V_2_11_2 = new Version(2110299, org.apache.lucene.util.Version.LUCENE_9_7_0);
+ public static final Version V_2_12_0 = new Version(2120099, org.apache.lucene.util.Version.LUCENE_9_9_2);
+ public static final Version V_2_12_1 = new Version(2120199, org.apache.lucene.util.Version.LUCENE_9_9_2);
+ public static final Version V_2_13_0 = new Version(2130099, org.apache.lucene.util.Version.LUCENE_9_10_0);
+ public static final Version V_3_0_0 = new Version(3000099, org.apache.lucene.util.Version.LUCENE_9_11_0);
public static final Version CURRENT = V_3_0_0;
public static Version fromId(int id) {
diff --git a/libs/core/src/main/java/org/opensearch/core/ParseField.java b/libs/core/src/main/java/org/opensearch/core/ParseField.java
index 5741f97d1d335..171b8eaf5c397 100644
--- a/libs/core/src/main/java/org/opensearch/core/ParseField.java
+++ b/libs/core/src/main/java/org/opensearch/core/ParseField.java
@@ -31,6 +31,7 @@
package org.opensearch.core;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.xcontent.DeprecationHandler;
import org.opensearch.core.xcontent.XContentLocation;
@@ -43,7 +44,11 @@
/**
* Holds a field that can be found in a request while parsing and its different
* variants, which may be deprecated.
+ *
+ * @opensearch.api
+ *
*/
+@PublicApi(since = "1.0.0")
public class ParseField {
private final String name;
private final String[] deprecatedNames;
diff --git a/server/src/main/java/org/opensearch/action/ActionListener.java b/libs/core/src/main/java/org/opensearch/core/action/ActionListener.java
similarity index 98%
rename from server/src/main/java/org/opensearch/action/ActionListener.java
rename to libs/core/src/main/java/org/opensearch/core/action/ActionListener.java
index 645ed4deec006..4fd55898a2cb5 100644
--- a/server/src/main/java/org/opensearch/action/ActionListener.java
+++ b/libs/core/src/main/java/org/opensearch/core/action/ActionListener.java
@@ -30,13 +30,14 @@
* GitHub history for details.
*/
-package org.opensearch.action;
+package org.opensearch.core.action;
import org.opensearch.ExceptionsHelper;
import org.opensearch.common.CheckedConsumer;
import org.opensearch.common.CheckedFunction;
import org.opensearch.common.CheckedRunnable;
import org.opensearch.common.CheckedSupplier;
+import org.opensearch.common.annotation.PublicApi;
import java.util.ArrayList;
import java.util.List;
@@ -48,6 +49,7 @@
*
* @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface ActionListener {
/**
* Handle action response. This response may constitute a failure or a
@@ -152,9 +154,9 @@ static ActionListener wrap(Runnable runnable) {
/**
* Creates a listener that wraps another listener, mapping response values via the given mapping function and passing along
* exceptions to the delegate.
- *
+ *
* Notice that it is considered a bug if the listener's onResponse or onFailure fails. onResponse failures will not call onFailure.
- *
+ *
* If the function fails, the listener's onFailure handler will be called. The principle is that the mapped listener will handle
* exceptions from the mapping function {@code fn} but it is the responsibility of {@code delegate} to handle its own exceptions
* inside `onResponse` and `onFailure`.
@@ -332,7 +334,7 @@ protected void innerOnFailure(Exception e) {
/**
* Completes the given listener with the result from the provided supplier accordingly.
* This method is mainly used to complete a listener with a block of synchronous code.
- *
+ *
* If the supplier fails, the listener's onFailure handler will be called.
* It is the responsibility of {@code delegate} to handle its own exceptions inside `onResponse` and `onFailure`.
*/
diff --git a/server/src/main/java/org/opensearch/action/ActionResponse.java b/libs/core/src/main/java/org/opensearch/core/action/ActionResponse.java
similarity index 89%
rename from server/src/main/java/org/opensearch/action/ActionResponse.java
rename to libs/core/src/main/java/org/opensearch/core/action/ActionResponse.java
index fd13971433d8b..7525bfb243aae 100644
--- a/server/src/main/java/org/opensearch/action/ActionResponse.java
+++ b/libs/core/src/main/java/org/opensearch/core/action/ActionResponse.java
@@ -30,10 +30,11 @@
* GitHub history for details.
*/
-package org.opensearch.action;
+package org.opensearch.core.action;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.common.io.stream.StreamInput;
-import org.opensearch.transport.TransportResponse;
+import org.opensearch.core.transport.TransportResponse;
import java.io.IOException;
@@ -42,6 +43,7 @@
*
* @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public abstract class ActionResponse extends TransportResponse {
public ActionResponse() {}
diff --git a/server/src/main/java/org/opensearch/action/NotifyOnceListener.java b/libs/core/src/main/java/org/opensearch/core/action/NotifyOnceListener.java
similarity index 93%
rename from server/src/main/java/org/opensearch/action/NotifyOnceListener.java
rename to libs/core/src/main/java/org/opensearch/core/action/NotifyOnceListener.java
index cc625962e54f6..f087322e0024c 100644
--- a/server/src/main/java/org/opensearch/action/NotifyOnceListener.java
+++ b/libs/core/src/main/java/org/opensearch/core/action/NotifyOnceListener.java
@@ -30,7 +30,9 @@
* GitHub history for details.
*/
-package org.opensearch.action;
+package org.opensearch.core.action;
+
+import org.opensearch.common.annotation.PublicApi;
import java.util.concurrent.atomic.AtomicBoolean;
@@ -39,8 +41,9 @@
* the is called is only called once. Subclasses should implement notification logic with
* innerOnResponse and innerOnFailure.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public abstract class NotifyOnceListener implements ActionListener {
private final AtomicBoolean hasBeenCalled = new AtomicBoolean(false);
diff --git a/libs/core/src/main/java/org/opensearch/core/action/ShardOperationFailedException.java b/libs/core/src/main/java/org/opensearch/core/action/ShardOperationFailedException.java
index 9fdd4ae273a8b..7456dcd335f72 100644
--- a/libs/core/src/main/java/org/opensearch/core/action/ShardOperationFailedException.java
+++ b/libs/core/src/main/java/org/opensearch/core/action/ShardOperationFailedException.java
@@ -34,8 +34,8 @@
import org.opensearch.common.Nullable;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.ToXContentObject;
import java.util.Objects;
diff --git a/libs/core/src/main/java/org/opensearch/core/action/support/DefaultShardOperationFailedException.java b/libs/core/src/main/java/org/opensearch/core/action/support/DefaultShardOperationFailedException.java
index ccb35ad5c6c6f..777f8d04758d0 100644
--- a/libs/core/src/main/java/org/opensearch/core/action/support/DefaultShardOperationFailedException.java
+++ b/libs/core/src/main/java/org/opensearch/core/action/support/DefaultShardOperationFailedException.java
@@ -34,15 +34,15 @@
import org.opensearch.ExceptionsHelper;
import org.opensearch.OpenSearchException;
-import org.opensearch.core.action.ShardOperationFailedException;
import org.opensearch.core.ParseField;
+import org.opensearch.core.action.ShardOperationFailedException;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
+import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.ConstructingObjectParser;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.core.rest.RestStatus;
import java.io.IOException;
diff --git a/libs/core/src/main/java/org/opensearch/core/common/ParsingException.java b/libs/core/src/main/java/org/opensearch/core/common/ParsingException.java
index d2cd7a3170792..b6dc7dc928b3e 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/ParsingException.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/ParsingException.java
@@ -35,10 +35,10 @@
import org.opensearch.OpenSearchException;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
+import org.opensearch.core.rest.RestStatus;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentLocation;
import org.opensearch.core.xcontent.XContentParser;
-import org.opensearch.core.rest.RestStatus;
import java.io.IOException;
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 d6c484e5e4746..8fdec670bd9f2 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
@@ -8,9 +8,18 @@
package org.opensearch.core.common;
+import org.apache.lucene.util.BytesRefBuilder;
+import org.opensearch.ExceptionsHelper;
+import org.opensearch.OpenSearchException;
import org.opensearch.common.Nullable;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.common.util.CollectionUtils;
+import org.opensearch.core.xcontent.MediaType;
+import org.opensearch.core.xcontent.ToXContent;
+import org.opensearch.core.xcontent.XContentBuilder;
import java.io.BufferedReader;
+import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
@@ -24,9 +33,12 @@
import java.util.TreeSet;
import java.util.function.Supplier;
+import static java.util.Collections.unmodifiableSet;
+import static org.opensearch.common.util.set.Sets.newHashSet;
+
/**
* String utility class.
- *
+ *
* TODO replace Strings in :server
*
* @opensearch.internal
@@ -34,115 +46,29 @@
public class Strings {
public static final String UNKNOWN_UUID_VALUE = "_na_";
public static final String[] EMPTY_ARRAY = new String[0];
+ public static final Set INVALID_FILENAME_CHARS = unmodifiableSet(
+ newHashSet('\\', '/', '*', '?', '"', '<', '>', '|', ' ', ',')
+ );
- /**
- * Split the specified string by commas to an array.
- *
- * @param s the string to split
- * @return the array of split values
- * @see String#split(String)
- */
- public static String[] splitStringByCommaToArray(final String s) {
- if (s == null || s.isEmpty()) return Strings.EMPTY_ARRAY;
- else return s.split(",");
- }
-
- /**
- * Convenience method to return a Collection as a delimited (e.g. CSV)
- * String. E.g. useful for toString()
implementations.
- *
- * @param coll the Collection to display
- * @param delim the delimiter to use (probably a ",")
- * @param prefix the String to start each element with
- * @param suffix the String to end each element with
- * @return the delimited String
- */
- public static String collectionToDelimitedString(Iterable> coll, String delim, String prefix, String suffix) {
- StringBuilder sb = new StringBuilder();
- collectionToDelimitedString(coll, delim, prefix, suffix, sb);
- return sb.toString();
- }
-
- public static void collectionToDelimitedString(Iterable> coll, String delim, String prefix, String suffix, StringBuilder sb) {
- Iterator> it = coll.iterator();
- while (it.hasNext()) {
- sb.append(prefix).append(it.next()).append(suffix);
- if (it.hasNext()) {
- sb.append(delim);
- }
- }
- }
-
- /**
- * Convenience method to return a Collection as a delimited (e.g. CSV)
- * String. E.g. useful for toString()
implementations.
- *
- * @param coll the Collection to display
- * @param delim the delimiter to use (probably a ",")
- * @return the delimited String
- */
- public static String collectionToDelimitedString(Iterable> coll, String delim) {
- return collectionToDelimitedString(coll, delim, "", "");
- }
+ // no instance:
+ private Strings() {}
- /**
- * Convenience method to return a Collection as a CSV String.
- * E.g. useful for toString()
implementations.
- *
- * @param coll the Collection to display
- * @return the delimited String
- */
- public static String collectionToCommaDelimitedString(Iterable> coll) {
- return collectionToDelimitedString(coll, ",");
- }
+ // ---------------------------------------------------------------------
+ // General convenience methods for working with Strings
+ // ---------------------------------------------------------------------
- /**
- * Convenience method to return a String array as a delimited (e.g. CSV)
- * String. E.g. useful for toString()
implementations.
- *
- * @param arr the array to display
- * @param delim the delimiter to use (probably a ",")
- * @return the delimited String
- */
- public static String arrayToDelimitedString(Object[] arr, String delim) {
- StringBuilder sb = new StringBuilder();
- arrayToDelimitedString(arr, delim, sb);
- return sb.toString();
- }
-
- public static void arrayToDelimitedString(Object[] arr, String delim, StringBuilder sb) {
- if (isEmpty(arr)) {
- return;
- }
- for (int i = 0; i < arr.length; i++) {
- if (i > 0) {
- sb.append(delim);
+ public static void spaceify(int spaces, String from, StringBuilder to) throws Exception {
+ try (BufferedReader reader = new BufferedReader(new StringReader(from))) {
+ String line;
+ while ((line = reader.readLine()) != null) {
+ for (int i = 0; i < spaces; i++) {
+ to.append(' ');
+ }
+ to.append(line).append('\n');
}
- sb.append(arr[i]);
}
}
- /**
- * Convenience method to return a String array as a CSV String.
- * E.g. useful for toString()
implementations.
- *
- * @param arr the array to display
- * @return the delimited String
- */
- public static String arrayToCommaDelimitedString(Object[] arr) {
- return arrayToDelimitedString(arr, ",");
- }
-
- /**
- * Determine whether the given array is empty:
- * i.e. null
or of zero length.
- *
- * @param array the array to check
- */
- private static boolean isEmpty(Object[] array) {
- return (array == null || array.length == 0);
- }
-
/**
* Check that the given CharSequence is neither null
nor of length 0.
* Note: Will return true
for a CharSequence that purely consists of whitespace.
@@ -161,6 +87,18 @@ public static boolean hasLength(CharSequence str) {
return (str != null && str.length() > 0);
}
+ /**
+ * Check that the given BytesReference is neither null
nor of length 0
+ * Note: Will return true
for a BytesReference that purely consists of whitespace.
+ *
+ * @param bytesReference the BytesReference to check (may be null
)
+ * @return true
if the BytesReference is not null and has length
+ * @see Strings#hasLength(CharSequence)
+ */
+ public static boolean hasLength(final BytesReference bytesReference) {
+ return (bytesReference != null && bytesReference.length() > 0);
+ }
+
/**
* Check that the given String is neither null
nor of length 0.
* Note: Will return true
for a String that purely consists of whitespace.
@@ -169,7 +107,7 @@ public static boolean hasLength(CharSequence str) {
* @return true
if the String is not null and has length
* @see Strings#hasLength(CharSequence)
*/
- public static boolean hasLength(String str) {
+ public static boolean hasLength(final String str) {
return hasLength((CharSequence) str);
}
@@ -186,7 +124,7 @@ public static boolean hasLength(String str) {
* @param str the CharSequence to check (may be null
)
* @return true
if the CharSequence is either null or has a zero length
*/
- public static boolean isEmpty(CharSequence str) {
+ public static boolean isEmpty(final CharSequence str) {
return hasLength(str) == false;
}
@@ -234,6 +172,42 @@ public static boolean hasText(String str) {
return hasText((CharSequence) str);
}
+ /**
+ * Trim all occurrences of the supplied leading character from the given String.
+ *
+ * @param str the String to check
+ * @param leadingCharacter the leading character to be trimmed
+ * @return the trimmed String
+ */
+ public static String trimLeadingCharacter(String str, char leadingCharacter) {
+ if (hasLength(str) == false) {
+ return str;
+ }
+ StringBuilder sb = new StringBuilder(str);
+ while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
+ sb.deleteCharAt(0);
+ }
+ return sb.toString();
+ }
+
+ /**
+ * Test whether the given string matches the given substring
+ * at the given index.
+ *
+ * @param str the original string (or StringBuilder)
+ * @param index the index in the original string to start matching against
+ * @param substring the substring to match at the given index
+ */
+ public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
+ for (int j = 0; j < substring.length(); j++) {
+ int i = index + j;
+ if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
/**
* Replace all occurrences of a substring within a string with
* another string.
@@ -263,24 +237,6 @@ public static String replace(String inString, String oldPattern, String newPatte
return sb.toString();
}
- /**
- * Trim all occurrences of the supplied leading character from the given String.
- *
- * @param str the String to check
- * @param leadingCharacter the leading character to be trimmed
- * @return the trimmed String
- */
- public static String trimLeadingCharacter(String str, char leadingCharacter) {
- if (hasLength(str) == false) {
- return str;
- }
- StringBuilder sb = new StringBuilder(str);
- while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
- sb.deleteCharAt(0);
- }
- return sb.toString();
- }
-
/**
* Delete all occurrences of the given substring.
*
@@ -314,16 +270,65 @@ public static String deleteAny(String inString, String charsToDelete) {
return sb.toString();
}
- public static void spaceify(int spaces, String from, StringBuilder to) throws Exception {
- try (BufferedReader reader = new BufferedReader(new StringReader(from))) {
- String line;
- while ((line = reader.readLine()) != null) {
- for (int i = 0; i < spaces; i++) {
- to.append(' ');
- }
- to.append(line).append('\n');
+ // ---------------------------------------------------------------------
+ // Convenience methods for working with formatted Strings
+ // ---------------------------------------------------------------------
+
+ /**
+ * Quote the given String with single quotes.
+ *
+ * @param str the input String (e.g. "myString")
+ * @return the quoted String (e.g. "'myString'"),
+ * or null
if the input was null
+ */
+ public static String quote(String str) {
+ return (str != null ? "'" + str + "'" : null);
+ }
+
+ /**
+ * Capitalize a String
, changing the first letter to
+ * upper case as per {@link Character#toUpperCase(char)}.
+ * No other letters are changed.
+ *
+ * @param str the String to capitalize, may be null
+ * @return the capitalized String, null
if null
+ */
+ public static String capitalize(String str) {
+ return changeFirstCharacterCase(str, true);
+ }
+
+ private static String changeFirstCharacterCase(String str, boolean capitalize) {
+ if (str == null || str.length() == 0) {
+ return str;
+ }
+ StringBuilder sb = new StringBuilder(str.length());
+ if (capitalize) {
+ sb.append(Character.toUpperCase(str.charAt(0)));
+ } else {
+ sb.append(Character.toLowerCase(str.charAt(0)));
+ }
+ sb.append(str.substring(1));
+ return sb.toString();
+ }
+
+ public static boolean validFileName(String fileName) {
+ for (int i = 0; i < fileName.length(); i++) {
+ char c = fileName.charAt(i);
+ if (INVALID_FILENAME_CHARS.contains(c)) {
+ return false;
}
}
+ return true;
+ }
+
+ public static boolean validFileNameExcludingAstrix(String fileName) {
+ for (int i = 0; i < fileName.length(); i++) {
+ char c = fileName.charAt(i);
+ if (c != '*' && INVALID_FILENAME_CHARS.contains(c)) {
+ return false;
+ }
+ }
+ return true;
}
/**
@@ -341,47 +346,6 @@ public static String[] toStringArray(final Collection collection) {
return collection.toArray(new String[0]);
}
- /**
- * Take a String which is a delimited list and convert it to a String array.
- * A single delimiter can consists of more than one character: It will still
- * be considered as single delimiter string, rather than as bunch of potential
- * delimiter characters - in contrast to tokenizeToStringArray
.
- *
- * @param str the input String
- * @param delimiter the delimiter between elements (this is a single delimiter,
- * rather than a bunch individual delimiter characters)
- * @param charsToDelete a set of characters to delete. Useful for deleting unwanted
- * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.
- * @return an array of the tokens in the list
- * @see #tokenizeToStringArray
- */
- public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {
- if (str == null) {
- return Strings.EMPTY_ARRAY;
- }
- if (delimiter == null) {
- return new String[] { str };
- }
- List result = new ArrayList<>();
- if ("".equals(delimiter)) {
- for (int i = 0; i < str.length(); i++) {
- result.add(deleteAny(str.substring(i, i + 1), charsToDelete));
- }
- } else {
- int pos = 0;
- int delPos;
- while ((delPos = str.indexOf(delimiter, pos)) != -1) {
- result.add(deleteAny(str.substring(pos, delPos), charsToDelete));
- pos = delPos + delimiter.length();
- }
- if (str.length() > 0 && pos <= str.length()) {
- // Add rest of String, but not in case of empty input.
- result.add(deleteAny(str.substring(pos), charsToDelete));
- }
- }
- return toStringArray(result);
- }
-
/**
* Tokenize the specified string by commas to a set, trimming whitespace and ignoring empty tokens.
*
@@ -393,6 +357,41 @@ public static Set tokenizeByCommaToSet(final String s) {
return tokenizeToCollection(s, ",", HashSet::new);
}
+ /**
+ * Split the specified string by commas to an array.
+ *
+ * @param s the string to split
+ * @return the array of split values
+ * @see String#split(String)
+ */
+ public static String[] splitStringByCommaToArray(final String s) {
+ if (s == null || s.isEmpty()) return Strings.EMPTY_ARRAY;
+ else return s.split(",");
+ }
+
+ /**
+ * Split a String at the first occurrence of the delimiter.
+ * Does not include the delimiter in the result.
+ *
+ * @param toSplit the string to split
+ * @param delimiter to split the string up with
+ * @return a two element array with index 0 being before the delimiter, and
+ * index 1 being after the delimiter (neither element includes the delimiter);
+ * or null
if the delimiter wasn't found in the given input String
+ */
+ public static String[] split(String toSplit, String delimiter) {
+ if (hasLength(toSplit) == false || hasLength(delimiter) == false) {
+ return null;
+ }
+ int offset = toSplit.indexOf(delimiter);
+ if (offset < 0) {
+ return null;
+ }
+ String beforeDelimiter = toSplit.substring(0, offset);
+ String afterDelimiter = toSplit.substring(offset + delimiter.length());
+ return new String[] { beforeDelimiter, afterDelimiter };
+ }
+
/**
* Tokenize the given String into a String array via a StringTokenizer.
* Trims tokens and omits empty tokens.
@@ -446,6 +445,47 @@ private static > T tokenizeToCollection(
return tokens;
}
+ /**
+ * Take a String which is a delimited list and convert it to a String array.
+ * A single delimiter can consists of more than one character: It will still
+ * be considered as single delimiter string, rather than as bunch of potential
+ * delimiter characters - in contrast to tokenizeToStringArray
.
+ *
+ * @param str the input String
+ * @param delimiter the delimiter between elements (this is a single delimiter,
+ * rather than a bunch individual delimiter characters)
+ * @param charsToDelete a set of characters to delete. Useful for deleting unwanted
+ * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a String.
+ * @return an array of the tokens in the list
+ * @see #tokenizeToStringArray
+ */
+ public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {
+ if (str == null) {
+ return Strings.EMPTY_ARRAY;
+ }
+ if (delimiter == null) {
+ return new String[] { str };
+ }
+ List result = new ArrayList<>();
+ if ("".equals(delimiter)) {
+ for (int i = 0; i < str.length(); i++) {
+ result.add(deleteAny(str.substring(i, i + 1), charsToDelete));
+ }
+ } else {
+ int pos = 0;
+ int delPos;
+ while ((delPos = str.indexOf(delimiter, pos)) != -1) {
+ result.add(deleteAny(str.substring(pos, delPos), charsToDelete));
+ pos = delPos + delimiter.length();
+ }
+ if (str.length() > 0 && pos <= str.length()) {
+ // Add rest of String, but not in case of empty input.
+ result.add(deleteAny(str.substring(pos), charsToDelete));
+ }
+ }
+ return toStringArray(result);
+ }
+
/**
* Take a String which is a delimited list and convert it to a String array.
* A single delimiter can consists of more than one character: It will still
@@ -486,33 +526,293 @@ public static Set commaDelimitedListToSet(String str) {
return set;
}
- public static boolean isNullOrEmpty(@Nullable String s) {
- return s == null || s.isEmpty();
+ /**
+ * Convenience method to return a Collection as a delimited (e.g. CSV)
+ * String. E.g. useful for toString()
implementations.
+ *
+ * @param coll the Collection to display
+ * @param delim the delimiter to use (probably a ",")
+ * @param prefix the String to start each element with
+ * @param suffix the String to end each element with
+ * @return the delimited String
+ */
+ public static String collectionToDelimitedString(Iterable> coll, String delim, String prefix, String suffix) {
+ StringBuilder sb = new StringBuilder();
+ collectionToDelimitedString(coll, delim, prefix, suffix, sb);
+ return sb.toString();
+ }
+
+ public static void collectionToDelimitedString(Iterable> coll, String delim, String prefix, String suffix, StringBuilder sb) {
+ Iterator> it = coll.iterator();
+ while (it.hasNext()) {
+ sb.append(prefix).append(it.next()).append(suffix);
+ if (it.hasNext()) {
+ sb.append(delim);
+ }
+ }
}
/**
- * Capitalize a String
, changing the first letter to
- * upper case as per {@link Character#toUpperCase(char)}.
- * No other letters are changed.
+ * Convenience method to return a Collection as a delimited (e.g. CSV)
+ * String. E.g. useful for toString()
implementations.
*
- * @param str the String to capitalize, may be null
- * @return the capitalized String, null
if null
+ * @param coll the Collection to display
+ * @param delim the delimiter to use (probably a ",")
+ * @return the delimited String
*/
- public static String capitalize(String str) {
- return changeFirstCharacterCase(str, true);
+ public static String collectionToDelimitedString(Iterable> coll, String delim) {
+ return collectionToDelimitedString(coll, delim, "", "");
}
- private static String changeFirstCharacterCase(String str, boolean capitalize) {
- if (str == null || str.length() == 0) {
- return str;
+ /**
+ * Convenience method to return a Collection as a CSV String.
+ * E.g. useful for toString()
implementations.
+ *
+ * @param coll the Collection to display
+ * @return the delimited String
+ */
+ public static String collectionToCommaDelimitedString(Iterable> coll) {
+ return collectionToDelimitedString(coll, ",");
+ }
+
+ /**
+ * Convenience method to return a String array as a delimited (e.g. CSV)
+ * String. E.g. useful for toString()
implementations.
+ *
+ * @param arr the array to display
+ * @param delim the delimiter to use (probably a ",")
+ * @return the delimited String
+ */
+ public static String arrayToDelimitedString(Object[] arr, String delim) {
+ StringBuilder sb = new StringBuilder();
+ arrayToDelimitedString(arr, delim, sb);
+ return sb.toString();
+ }
+
+ public static void arrayToDelimitedString(Object[] arr, String delim, StringBuilder sb) {
+ if (isEmpty(arr)) {
+ return;
}
- StringBuilder sb = new StringBuilder(str.length());
- if (capitalize) {
- sb.append(Character.toUpperCase(str.charAt(0)));
+ for (int i = 0; i < arr.length; i++) {
+ if (i > 0) {
+ sb.append(delim);
+ }
+ sb.append(arr[i]);
+ }
+ }
+
+ /**
+ * Convenience method to return a String array as a CSV String.
+ * E.g. useful for toString()
implementations.
+ *
+ * @param arr the array to display
+ * @return the delimited String
+ */
+ public static String arrayToCommaDelimitedString(Object[] arr) {
+ return arrayToDelimitedString(arr, ",");
+ }
+
+ /**
+ * Format the double value with a single decimal points, trimming trailing '.0'.
+ */
+ public static String format1Decimals(double value, String suffix) {
+ String p = String.valueOf(value);
+ int ix = p.indexOf('.') + 1;
+ int ex = p.indexOf('E');
+ char fraction = p.charAt(ix);
+ if (fraction == '0') {
+ if (ex != -1) {
+ return p.substring(0, ix - 1) + p.substring(ex) + suffix;
+ } else {
+ return p.substring(0, ix - 1) + suffix;
+ }
} else {
- sb.append(Character.toLowerCase(str.charAt(0)));
+ if (ex != -1) {
+ return p.substring(0, ix) + fraction + p.substring(ex) + suffix;
+ } else {
+ return p.substring(0, ix) + fraction + suffix;
+ }
}
- sb.append(str.substring(1));
- return sb.toString();
+ }
+
+ /**
+ * Determine whether the given array is empty:
+ * i.e. null
or of zero length.
+ *
+ * @param array the array to check
+ */
+ private static boolean isEmpty(final Object[] array) {
+ return (array == null || array.length == 0);
+ }
+
+ public static byte[] toUTF8Bytes(CharSequence charSequence) {
+ return toUTF8Bytes(charSequence, new BytesRefBuilder());
+ }
+
+ public static byte[] toUTF8Bytes(CharSequence charSequence, BytesRefBuilder spare) {
+ spare.copyChars(charSequence);
+ return Arrays.copyOf(spare.bytes(), spare.length());
+ }
+
+ /**
+ * Return substring(beginIndex, endIndex) that is impervious to string length.
+ */
+ public static String substring(String s, int beginIndex, int endIndex) {
+ if (s == null) {
+ return s;
+ }
+
+ int realEndIndex = s.length() > 0 ? s.length() - 1 : 0;
+
+ if (endIndex > realEndIndex) {
+ return s.substring(beginIndex);
+ } else {
+ return s.substring(beginIndex, endIndex);
+ }
+ }
+
+ /**
+ * If an array only consists of zero or one element, which is "*" or "_all" return an empty array
+ * which is usually used as everything
+ */
+ public static boolean isAllOrWildcard(String[] data) {
+ return CollectionUtils.isEmpty(data) || data.length == 1 && isAllOrWildcard(data[0]);
+ }
+
+ /**
+ * Returns `true` if the string is `_all` or `*`.
+ */
+ public static boolean isAllOrWildcard(String data) {
+ return "_all".equals(data) || "*".equals(data);
+ }
+
+ /**
+ * Return a {@link String} that is the json representation of the provided {@link ToXContent}.
+ * Wraps the output into an anonymous object if needed. The content is not pretty-printed
+ * nor human readable.
+ */
+ public static String toString(MediaType mediaType, ToXContent toXContent) {
+ return toString(mediaType, toXContent, false, false);
+ }
+
+ /**
+ * Return a {@link String} that is the json representation of the provided {@link ToXContent}.
+ * Wraps the output into an anonymous object if needed.
+ * Allows to configure the params.
+ * The content is not pretty-printed nor human readable.
+ */
+ public static String toString(MediaType mediaType, ToXContent toXContent, ToXContent.Params params) {
+ return toString(mediaType, toXContent, params, false, false);
+ }
+
+ /**
+ * Return a {@link String} that is the json representation of the provided {@link ToXContent}.
+ * Wraps the output into an anonymous object if needed. Allows to control whether the outputted
+ * json needs to be pretty printed and human readable.
+ *
+ */
+ public static String toString(MediaType mediaType, ToXContent toXContent, boolean pretty, boolean human) {
+ return toString(mediaType, toXContent, ToXContent.EMPTY_PARAMS, pretty, human);
+ }
+
+ /**
+ * Return a {@link String} that is the json representation of the provided {@link ToXContent}.
+ * Wraps the output into an anonymous object if needed.
+ * Allows to configure the params.
+ * Allows to control whether the outputted json needs to be pretty printed and human readable.
+ */
+ private static String toString(MediaType mediaType, ToXContent toXContent, ToXContent.Params params, boolean pretty, boolean human) {
+ try {
+ XContentBuilder builder = createBuilder(mediaType, pretty, human);
+ if (toXContent.isFragment()) {
+ builder.startObject();
+ }
+ toXContent.toXContent(builder, params);
+ if (toXContent.isFragment()) {
+ builder.endObject();
+ }
+ return builder.toString();
+ } catch (IOException e) {
+ try {
+ XContentBuilder builder = createBuilder(mediaType, pretty, human);
+ builder.startObject();
+ builder.field("error", "error building toString out of XContent: " + e.getMessage());
+ builder.field("stack_trace", ExceptionsHelper.stackTrace(e));
+ builder.endObject();
+ return builder.toString();
+ } catch (IOException e2) {
+ throw new OpenSearchException("cannot generate error message for deserialization", e);
+ }
+ }
+ }
+
+ private static XContentBuilder createBuilder(MediaType mediaType, boolean pretty, boolean human) throws IOException {
+ XContentBuilder builder = XContentBuilder.builder(mediaType.xContent());
+ if (pretty) {
+ builder.prettyPrint();
+ }
+ if (human) {
+ builder.humanReadable(true);
+ }
+ return builder;
+ }
+
+ /**
+ * Truncates string to a length less than length. Backtracks to throw out
+ * high surrogates.
+ */
+ public static String cleanTruncate(String s, int length) {
+ if (s == null) {
+ return s;
+ }
+ /*
+ * Its pretty silly for you to truncate to 0 length but just in case
+ * someone does this shouldn't break.
+ */
+ if (length == 0) {
+ return "";
+ }
+ if (length >= s.length()) {
+ return s;
+ }
+ if (Character.isHighSurrogate(s.charAt(length - 1))) {
+ length--;
+ }
+ return s.substring(0, length);
+ }
+
+ public static boolean isNullOrEmpty(@Nullable String s) {
+ return s == null || s.isEmpty();
+ }
+
+ public static String padStart(String s, int minimumLength, char c) {
+ if (s == null) {
+ throw new NullPointerException("s");
+ }
+ if (s.length() >= minimumLength) {
+ return s;
+ } else {
+ StringBuilder sb = new StringBuilder(minimumLength);
+ for (int i = s.length(); i < minimumLength; i++) {
+ sb.append(c);
+ }
+
+ sb.append(s);
+ return sb.toString();
+ }
+ }
+
+ public static String toLowercaseAscii(String in) {
+ StringBuilder out = new StringBuilder();
+ Iterator iter = in.codePoints().iterator();
+ while (iter.hasNext()) {
+ int codepoint = iter.next();
+ if (codepoint > 128) {
+ out.appendCodePoint(codepoint);
+ } else {
+ out.appendCodePoint(Character.toLowerCase(codepoint));
+ }
+ }
+ return out.toString();
}
}
diff --git a/server/src/main/java/org/opensearch/common/breaker/CircuitBreaker.java b/libs/core/src/main/java/org/opensearch/core/common/breaker/CircuitBreaker.java
similarity index 79%
rename from server/src/main/java/org/opensearch/common/breaker/CircuitBreaker.java
rename to libs/core/src/main/java/org/opensearch/core/common/breaker/CircuitBreaker.java
index 4cbd375e8c1ff..846950ff17c63 100644
--- a/server/src/main/java/org/opensearch/common/breaker/CircuitBreaker.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/breaker/CircuitBreaker.java
@@ -30,7 +30,7 @@
* GitHub history for details.
*/
-package org.opensearch.common.breaker;
+package org.opensearch.core.common.breaker;
import java.util.Locale;
@@ -71,17 +71,23 @@ public interface CircuitBreaker {
/**
* The type of breaker
- *
+ * can be {@link #MEMORY}, {@link #PARENT}, or {@link #NOOP}
* @opensearch.internal
*/
enum Type {
- // A regular or ChildMemoryCircuitBreaker
+ /** A regular or ChildMemoryCircuitBreaker */
MEMORY,
- // A special parent-type for the hierarchy breaker service
+ /** A special parent-type for the hierarchy breaker service */
PARENT,
- // A breaker where every action is a noop, it never breaks
+ /** A breaker where every action is a noop, it never breaks */
NOOP;
+ /**
+ * Converts string (case-insensitive) to breaker {@link Type}
+ * @param value "noop", "parent", or "memory" (case-insensitive)
+ * @return the breaker {@link Type}
+ * @throws IllegalArgumentException if value is not "noop", "parent", or "memory"
+ */
public static Type parseValue(String value) {
switch (value.toLowerCase(Locale.ROOT)) {
case "noop":
@@ -98,13 +104,13 @@ public static Type parseValue(String value) {
/**
* The breaker durability
- *
+ * can be {@link #TRANSIENT} or {@link #PERMANENT}
* @opensearch.internal
*/
enum Durability {
- // The condition that tripped the circuit breaker fixes itself eventually.
+ /** The condition that tripped the circuit breaker fixes itself eventually. */
TRANSIENT,
- // The condition that tripped the circuit breaker requires manual intervention.
+ /** The condition that tripped the circuit breaker requires manual intervention. */
PERMANENT
}
@@ -120,11 +126,14 @@ enum Durability {
* @param bytes number of bytes to add
* @param label string label describing the bytes being added
* @return the number of "used" bytes for the circuit breaker
+ * @throws CircuitBreakingException if the breaker tripped
*/
double addEstimateBytesAndMaybeBreak(long bytes, String label) throws CircuitBreakingException;
/**
* Adjust the circuit breaker without tripping
+ * @param bytes number of bytes to add
+ * @return the number of "used" bytes for the circuit breaker
*/
long addWithoutBreaking(long bytes);
@@ -154,7 +163,10 @@ enum Durability {
String getName();
/**
- * @return whether a tripped circuit breaker will reset itself (transient) or requires manual intervention (permanent).
+ * Returns the {@link Durability} of this breaker
+ * @return whether a tripped circuit breaker will
+ * reset itself ({@link Durability#TRANSIENT})
+ * or requires manual intervention ({@link Durability#PERMANENT}).
*/
Durability getDurability();
diff --git a/server/src/main/java/org/opensearch/common/breaker/CircuitBreakingException.java b/libs/core/src/main/java/org/opensearch/core/common/breaker/CircuitBreakingException.java
similarity index 92%
rename from server/src/main/java/org/opensearch/common/breaker/CircuitBreakingException.java
rename to libs/core/src/main/java/org/opensearch/core/common/breaker/CircuitBreakingException.java
index 4cab014912970..2df116dcad076 100644
--- a/server/src/main/java/org/opensearch/common/breaker/CircuitBreakingException.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/breaker/CircuitBreakingException.java
@@ -29,13 +29,13 @@
* GitHub history for details.
*/
-package org.opensearch.common.breaker;
+package org.opensearch.core.common.breaker;
import org.opensearch.OpenSearchException;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
-import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.rest.RestStatus;
+import org.opensearch.core.xcontent.XContentBuilder;
import java.io.IOException;
@@ -46,8 +46,11 @@
*/
public class CircuitBreakingException extends OpenSearchException {
+ /** The number of bytes wanted */
private final long bytesWanted;
+ /** The circuit breaker limit */
private final long byteLimit;
+ /** The {@link CircuitBreaker.Durability} of the circuit breaker */
private final CircuitBreaker.Durability durability;
public CircuitBreakingException(StreamInput in) throws IOException {
@@ -88,6 +91,7 @@ public CircuitBreaker.Durability getDurability() {
return durability;
}
+ /** Always returns {@link RestStatus#TOO_MANY_REQUESTS} */
@Override
public RestStatus status() {
return RestStatus.TOO_MANY_REQUESTS;
diff --git a/libs/core/src/main/java/org/opensearch/core/common/breaker/NoopCircuitBreaker.java b/libs/core/src/main/java/org/opensearch/core/common/breaker/NoopCircuitBreaker.java
new file mode 100644
index 0000000000000..17b9fefd27c99
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/common/breaker/NoopCircuitBreaker.java
@@ -0,0 +1,152 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+package org.opensearch.core.common.breaker;
+
+/**
+ * A {@link CircuitBreaker} that doesn't increment or adjust, and all operations are
+ * basically noops.
+ * It never trips, limit is always -1, always returns 0 for all metrics.
+ * @opensearch.internal
+ */
+public class NoopCircuitBreaker implements CircuitBreaker {
+
+ /** The limit of this breaker is always -1 */
+ public static final int LIMIT = -1;
+ /** Name of this breaker */
+ private final String name;
+
+ /**
+ * Creates a new NoopCircuitBreaker (that never trip) with the given name
+ * @param name the name of this breaker
+ */
+ public NoopCircuitBreaker(String name) {
+ this.name = name;
+ }
+
+ /**
+ * This is a noop, a noop breaker never trip
+ * @param fieldName name of this noop breaker
+ * @param bytesNeeded bytes needed
+ */
+ @Override
+ public void circuitBreak(String fieldName, long bytesNeeded) {
+ // noop
+ }
+
+ /**
+ * This is a noop, always return 0 and never throw/trip
+ * @param bytes number of bytes to add
+ * @param label string label describing the bytes being added
+ * @return always return 0
+ * @throws CircuitBreakingException never thrown
+ */
+ @Override
+ public double addEstimateBytesAndMaybeBreak(long bytes, String label) throws CircuitBreakingException {
+ return 0;
+ }
+
+ /**
+ * This is a noop, nothing is added, always return 0
+ * @param bytes number of bytes to add (ignored)
+ * @return always return 0
+ */
+ @Override
+ public long addWithoutBreaking(long bytes) {
+ return 0;
+ }
+
+ /**
+ * This is a noop, always return 0
+ * @return always return 0
+ */
+ @Override
+ public long getUsed() {
+ return 0;
+ }
+
+ /**
+ * A noop breaker have a constant limit of -1
+ * @return always return -1
+ */
+ @Override
+ public long getLimit() {
+ return LIMIT;
+ }
+
+ /**
+ * A noop breaker have no overhead, always return 0
+ * @return always return 0
+ */
+ @Override
+ public double getOverhead() {
+ return 0;
+ }
+
+ /**
+ * A noop breaker never trip, always return 0
+ * @return always return 0
+ */
+ @Override
+ public long getTrippedCount() {
+ return 0;
+ }
+
+ /**
+ * return the name of this breaker
+ * @return the name of this breaker
+ */
+ @Override
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ * A noop breaker {@link Durability} is always {@link Durability#PERMANENT}
+ * @return always return {@link Durability#PERMANENT }
+ */
+ @Override
+ public Durability getDurability() {
+ return Durability.PERMANENT;
+ }
+
+ /**
+ * Limit and overhead are constant for a noop breaker.
+ * this is a noop.
+ * @param limit the desired limit (ignored)
+ * @param overhead the desired overhead (ignored)
+ */
+ @Override
+ public void setLimitAndOverhead(long limit, double overhead) {
+ // noop
+ }
+}
diff --git a/libs/core/src/main/java/org/opensearch/core/common/breaker/package-info.java b/libs/core/src/main/java/org/opensearch/core/common/breaker/package-info.java
new file mode 100644
index 0000000000000..f9fb83d2207e1
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/common/breaker/package-info.java
@@ -0,0 +1,12 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Foundation classes for the Circuit Breaker
+ */
+package org.opensearch.core.common.breaker;
diff --git a/libs/core/src/main/java/org/opensearch/core/common/bytes/AbstractBytesReference.java b/libs/core/src/main/java/org/opensearch/core/common/bytes/AbstractBytesReference.java
index e054776d67fdc..a2bf7e499dee8 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/bytes/AbstractBytesReference.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/bytes/AbstractBytesReference.java
@@ -49,14 +49,10 @@
*/
public abstract class AbstractBytesReference implements BytesReference {
- private Integer hash = null; // we cache the hash of this reference since it can be quite costly to re-calculated it
+ /** we cache the hash of this reference since it can be quite costly to re-calculated it */
+ private Integer hash = null;
private static final int MAX_UTF16_LENGTH = Integer.MAX_VALUE >> 1;
- @Override
- public int getInt(int index) {
- return (get(index) & 0xFF) << 24 | (get(index + 1) & 0xFF) << 16 | (get(index + 2) & 0xFF) << 8 | get(index + 3) & 0xFF;
- }
-
@Override
public int indexOf(byte marker, int from) {
final int to = length();
diff --git a/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesArray.java b/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesArray.java
index ae04ddcc19eee..d7a8414935143 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesArray.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/bytes/BytesArray.java
@@ -32,6 +32,7 @@
package org.opensearch.core.common.bytes;
+import org.apache.lucene.util.BitUtil;
import org.apache.lucene.util.BytesRef;
import org.opensearch.core.common.io.stream.StreamInput;
@@ -83,6 +84,11 @@ public byte get(int index) {
return bytes[offset + index];
}
+ @Override
+ public int getInt(int index) {
+ return (int) BitUtil.VH_BE_INT.get(bytes, offset + index);
+ }
+
@Override
public int length() {
return length;
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 fc8e62c914e27..8cb65c9feb1ca 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
@@ -35,6 +35,7 @@
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefIterator;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.common.io.stream.BytesStream;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.util.ByteArray;
@@ -50,8 +51,9 @@
/**
* A reference to bytes.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface BytesReference extends Comparable, ToXContentFragment {
/**
@@ -151,9 +153,11 @@ static BytesReference fromByteArray(ByteArray byteArray, int length) {
byte get(int index);
/**
- * Returns the integer read from the 4 bytes (BE) starting at the given index.
+ * Returns the integer read from the 4 bytes (big endian) starting at the given index.
*/
- int getInt(int index);
+ default int getInt(int index) {
+ return ((get(index) & 0xFF) << 24) | ((get(index + 1) & 0xFF) << 16) | ((get(index + 2) & 0xFF) << 8) | (get(index + 3) & 0xFF);
+ }
/**
* Finds the index of the first occurrence of the given marker between within the given bounds.
diff --git a/libs/core/src/main/java/org/opensearch/core/common/bytes/CompositeBytesReference.java b/libs/core/src/main/java/org/opensearch/core/common/bytes/CompositeBytesReference.java
index 53915a3da824c..1a48abee2dbf8 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/bytes/CompositeBytesReference.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/bytes/CompositeBytesReference.java
@@ -45,7 +45,7 @@
/**
* A composite {@link BytesReference} that allows joining multiple bytes references
* into one without copying.
- *
+ *
* Note, {@link #toBytesRef()} will materialize all pages in this BytesReference.
*
* @opensearch.internal
diff --git a/libs/core/src/main/java/org/opensearch/core/common/compress/package-info.java b/libs/core/src/main/java/org/opensearch/core/common/compress/package-info.java
deleted file mode 100644
index 99459f99c42d8..0000000000000
--- a/libs/core/src/main/java/org/opensearch/core/common/compress/package-info.java
+++ /dev/null
@@ -1,10 +0,0 @@
-/*
- * SPDX-License-Identifier: Apache-2.0
- *
- * The OpenSearch Contributors require contributions made to
- * this file be licensed under the Apache-2.0 license or a
- * compatible open source license.
- */
-
-/** Classes for core compress module */
-package org.opensearch.core.common.compress;
diff --git a/libs/core/src/main/java/org/opensearch/core/common/io/stream/BytesStreamInput.java b/libs/core/src/main/java/org/opensearch/core/common/io/stream/BytesStreamInput.java
index a50d1c165ed72..cad43f817faaf 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/io/stream/BytesStreamInput.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/io/stream/BytesStreamInput.java
@@ -8,6 +8,7 @@
package org.opensearch.core.common.io.stream;
+import org.apache.lucene.util.BitUtil;
import org.apache.lucene.util.BytesRef;
import java.io.EOFException;
@@ -17,7 +18,7 @@
* {@link StreamInput} version of Lucene's {@link org.apache.lucene.store.ByteArrayDataInput}
* This is used as a replacement of Lucene ByteArrayDataInput for abstracting byte order changes
* in Lucene's API
- *
+ *
* Attribution given to apache lucene project under ALv2:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -121,4 +122,33 @@ public int read() throws IOException {
return bytes[pos++] & 0xFF;
}
+ @Override
+ public short readShort() throws IOException {
+ if (available() < Short.BYTES) {
+ throw new EOFException();
+ }
+ short value = (short) BitUtil.VH_BE_SHORT.get(bytes, pos);
+ pos += Short.BYTES;
+ return value;
+ }
+
+ @Override
+ public int readInt() throws IOException {
+ if (available() < Integer.BYTES) {
+ throw new EOFException();
+ }
+ int value = (int) BitUtil.VH_BE_INT.get(bytes, pos);
+ pos += Integer.BYTES;
+ return value;
+ }
+
+ @Override
+ public long readLong() throws IOException {
+ if (available() < Long.BYTES) {
+ throw new EOFException();
+ }
+ long value = (long) BitUtil.VH_BE_LONG.get(bytes, pos);
+ pos += Long.BYTES;
+ return value;
+ }
}
diff --git a/libs/core/src/main/java/org/opensearch/core/common/io/stream/NamedWriteableRegistry.java b/libs/core/src/main/java/org/opensearch/core/common/io/stream/NamedWriteableRegistry.java
index ec707f147cade..123b52eb92876 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/io/stream/NamedWriteableRegistry.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/io/stream/NamedWriteableRegistry.java
@@ -32,6 +32,8 @@
package org.opensearch.core.common.io.stream;
+import org.opensearch.common.annotation.PublicApi;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
@@ -41,19 +43,21 @@
/**
* A registry for {@link Writeable.Reader} readers of {@link NamedWriteable}.
- *
+ *
* The registration is keyed by the combination of the category class of {@link NamedWriteable}, and a name unique
* to that category.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class NamedWriteableRegistry {
/**
* An entry in the registry, made up of a category class and name, and a reader for that category class.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+ @PublicApi(since = "1.0.0")
public static class Entry {
/** The superclass of a {@link NamedWriteable} which will be read by {@link #reader}. */
diff --git a/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamInput.java b/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamInput.java
index 1d7321bf2c6de..ea23b3d81a775 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamInput.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamInput.java
@@ -46,15 +46,17 @@
import org.opensearch.Version;
import org.opensearch.common.CharArrays;
import org.opensearch.common.Nullable;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.common.unit.TimeValue;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.common.settings.SecureString;
import org.opensearch.core.common.text.Text;
-import org.opensearch.common.unit.TimeValue;
-import org.opensearch.core.common.Strings;
import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException;
import org.opensearch.core.xcontent.MediaType;
-import org.opensearch.core.xcontent.MediaTypeParserRegistry;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+import org.opensearch.semver.SemverRange;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
@@ -95,7 +97,7 @@
/**
* A stream from this node to another node. Technically, it can also be streamed to a byte array but that is mostly for testing.
- *
+ *
* This class's methods are optimized so you can put the methods that read and write a class next to each other and you can scan them
* visually for differences. That means that most variables should be read and written in a single line so even large objects fit both
* reading and writing on the screen. It also means that the methods on this class are named very similarly to {@link StreamOutput}. Finally
@@ -104,8 +106,9 @@
* lists, either by storing {@code List}s internally or just converting to and from a {@code List} when calling. This comment is repeated
* on {@link StreamInput}.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public abstract class StreamInput extends InputStream {
private Version version = Version.CURRENT;
@@ -347,7 +350,7 @@ public BigInteger readBigInteger() throws IOException {
}
public MediaType readMediaType() throws IOException {
- return MediaTypeParserRegistry.fromMediaType(readString());
+ return MediaTypeRegistry.fromMediaType(readString());
}
@Nullable
@@ -722,6 +725,8 @@ public Object readGenericValue() throws IOException {
return readByte();
case 12:
return readDate();
+ case 13:
+ return readZonedDateTime();
case 14:
return readBytesReference();
case 15:
@@ -746,6 +751,8 @@ public Object readGenericValue() throws IOException {
return readCollection(StreamInput::readGenericValue, HashSet::new, Collections.emptySet());
case 26:
return readBigInteger();
+ case 27:
+ return readSemverRange();
default:
throw new IOException("Can't read unknown type [" + type + "]");
}
@@ -1086,6 +1093,10 @@ public Version readVersion() throws IOException {
return Version.fromId(readVInt());
}
+ public SemverRange readSemverRange() throws IOException {
+ return SemverRange.fromString(readString());
+ }
+
/** Reads the {@link Version} from the input stream */
public Build readBuild() throws IOException {
// the following is new for opensearch: we write the distribution to support any "forks"
@@ -1124,7 +1135,7 @@ public C readNamedWriteable(@SuppressWarnings("unused
* the corresponding entry in the registry by name, so that the proper object can be read and returned.
* Default implementation throws {@link UnsupportedOperationException} as StreamInput doesn't hold a registry.
* Use {@link FilterInputStream} instead which wraps a stream and supports a {@link NamedWriteableRegistry} too.
- *
+ *
* Prefer {@link StreamInput#readNamedWriteable(Class)} and {@link StreamOutput#writeNamedWriteable(NamedWriteable)} unless you
* have a compelling reason to use this method instead.
*/
diff --git a/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamOutput.java b/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamOutput.java
index 566abf9f08f53..b7599265aece3 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamOutput.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/io/stream/StreamOutput.java
@@ -45,14 +45,16 @@
import org.opensearch.Version;
import org.opensearch.common.CharArrays;
import org.opensearch.common.Nullable;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.common.unit.TimeValue;
import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.common.io.stream.Writeable.WriteableRegistry;
import org.opensearch.core.common.io.stream.Writeable.Writer;
import org.opensearch.core.common.settings.SecureString;
import org.opensearch.core.common.text.Text;
-import org.opensearch.common.unit.TimeValue;
import org.opensearch.core.concurrency.OpenSearchRejectedExecutionException;
+import org.opensearch.semver.SemverRange;
import java.io.EOFException;
import java.io.FileNotFoundException;
@@ -87,7 +89,7 @@
/**
* A stream from another node to this node. Technically, it can also be streamed from a byte array but that is mostly for testing.
- *
+ *
* This class's methods are optimized so you can put the methods that read and write a class next to each other and you can scan them
* visually for differences. That means that most variables should be read and written in a single line so even large objects fit both
* reading and writing on the screen. It also means that the methods on this class are named very similarly to {@link StreamInput}. Finally
@@ -96,8 +98,9 @@
* lists, either by storing {@code List}s internally or just converting to and from a {@code List} when calling. This comment is repeated
* on {@link StreamInput}.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public abstract class StreamOutput extends OutputStream {
private static final int MAX_NESTED_EXCEPTION_LEVEL = 100;
@@ -782,6 +785,10 @@ public final void writeOptionalInstant(@Nullable Instant instant) throws IOExcep
o.writeByte((byte) 26);
o.writeString(v.toString());
});
+ writers.put(SemverRange.class, (o, v) -> {
+ o.writeByte((byte) 27);
+ o.writeSemverRange((SemverRange) v);
+ });
WRITERS = Collections.unmodifiableMap(writers);
}
@@ -804,6 +811,23 @@ private static Class> getGenericType(Object value) {
}
}
+ /**
+ * Returns the registered writer for the given class type.
+ */
+ @SuppressWarnings("unchecked")
+ public static > W getWriter(Class> type) {
+ Writer writer = WriteableRegistry.getWriter(type);
+ if (writer == null) {
+ // fallback to this local hashmap
+ // todo: move all writers to the registry
+ writer = WRITERS.get(type);
+ }
+ if (writer == null) {
+ throw new IllegalArgumentException("can not write type [" + type + "]");
+ }
+ return (W) writer;
+ }
+
/**
* Notice: when serialization a map, the stream out map with the stream in map maybe have the
* different key-value orders, they will maybe have different stream order.
@@ -816,17 +840,8 @@ public void writeGenericValue(@Nullable Object value) throws IOException {
return;
}
final Class> type = getGenericType(value);
- Writer writer = WriteableRegistry.getWriter(type);
- if (writer == null) {
- // fallback to this local hashmap
- // todo: move all writers to the registry
- writer = WRITERS.get(type);
- }
- if (writer != null) {
- writer.write(this, value);
- } else {
- throw new IllegalArgumentException("can not write type [" + type + "]");
- }
+ final Writer writer = getWriter(type);
+ writer.write(this, value);
}
public static void checkWriteable(@Nullable Object value) throws IllegalArgumentException {
@@ -1091,6 +1106,10 @@ public void writeVersion(final Version version) throws IOException {
writeVInt(version.id);
}
+ public void writeSemverRange(final SemverRange range) throws IOException {
+ writeString(range.toString());
+ }
+
/** Writes the OpenSearch {@link Build} informn to the output stream */
public void writeBuild(final Build build) throws IOException {
// the following is new for opensearch: we write the distribution name to support any "forks" of the code
diff --git a/libs/core/src/main/java/org/opensearch/core/common/io/stream/Writeable.java b/libs/core/src/main/java/org/opensearch/core/common/io/stream/Writeable.java
index af9df51655414..960f4bec5eeb5 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/io/stream/Writeable.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/io/stream/Writeable.java
@@ -32,6 +32,8 @@
package org.opensearch.core.common.io.stream;
+import org.opensearch.common.annotation.PublicApi;
+
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -41,8 +43,9 @@
* across the wire" using OpenSearch's internal protocol. If the implementer also implements equals and hashCode then a copy made by
* serializing and deserializing must be equal and have the same hashCode. It isn't required that such a copy be entirely unchanged.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "2.8.0")
public interface Writeable {
/**
* A WriteableRegistry registers {@link Writer} methods for writing data types over a
@@ -135,8 +138,11 @@ public static Class> getCustomClassFromInstance(final Object value) {
* out.writeMapOfLists(someMap, StreamOutput::writeString, StreamOutput::writeString);
* }
*
+ *
+ * @opensearch.api
*/
@FunctionalInterface
+ @PublicApi(since = "2.8.0")
interface Writer {
/**
@@ -161,8 +167,11 @@ interface Writer {
* this.someMap = in.readMapOfLists(StreamInput::readString, StreamInput::readString);
* }
*
+ *
+ * @opensearch.api
*/
@FunctionalInterface
+ @PublicApi(since = "2.8.0")
interface Reader {
/**
diff --git a/libs/core/src/main/java/org/opensearch/core/common/logging/LoggerMessageFormat.java b/libs/core/src/main/java/org/opensearch/core/common/logging/LoggerMessageFormat.java
index 59492193d16dc..c7b9bee3cbf4d 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/logging/LoggerMessageFormat.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/logging/LoggerMessageFormat.java
@@ -30,6 +30,13 @@
* GitHub history for details.
*/
+/*
+ * This code is based on code from SFL4J 1.5.11
+ * Copyright (c) 2004-2007 QOS.ch
+ * All rights reserved.
+ * SPDX-License-Identifier: MIT
+ */
+
package org.opensearch.core.common.logging;
import java.util.HashSet;
@@ -37,6 +44,10 @@
/**
* Format string for OpenSearch log messages.
+ *
+ * This class is almost a copy of {@code org.slf4j.helpers.MessageFormatter}
+ * The original code is licensed under the MIT License and is available at :
+ * MessageFormatter.java
*
* @opensearch.internal
*/
@@ -51,6 +62,17 @@ public static String format(final String messagePattern, final Object... argArra
return format(null, messagePattern, argArray);
}
+ /**
+ * (this is almost a copy of {@code org.slf4j.helpers.MessageFormatter.arrayFormat})
+ *
+ * @param prefix the prefix to prepend to the formatted message (can be null)
+ * @param messagePattern the message pattern which will be parsed and formatted
+ * @param argArray an array of arguments to be substituted in place of formatting anchors
+ * @return null if messagePattern is null
+ * messagePattern if argArray is (null or empty) and prefix is null
+ * prefix + messagePattern if argArray is (null or empty) and prefix is not null
+ * formatted message otherwise (even if prefix is null)
+ */
public static String format(final String prefix, final String messagePattern, final Object... argArray) {
if (messagePattern == null) {
return null;
@@ -110,6 +132,13 @@ public static String format(final String prefix, final String messagePattern, fi
return sbuf.toString();
}
+ /**
+ * Checks if (delimterStartIndex - 1) in messagePattern is an escape character.
+ * @param messagePattern the message pattern
+ * @param delimiterStartIndex the index of the character to check
+ * @return true if there is an escape char before the character at delimiterStartIndex.
+ * Always returns false if delimiterStartIndex == 0 (edge case)
+ */
static boolean isEscapedDelimiter(String messagePattern, int delimiterStartIndex) {
if (delimiterStartIndex == 0) {
@@ -119,6 +148,13 @@ static boolean isEscapedDelimiter(String messagePattern, int delimiterStartIndex
return potentialEscape == ESCAPE_CHAR;
}
+ /**
+ * Checks if (delimterStartIndex - 2) in messagePattern is an escape character.
+ * @param messagePattern the message pattern
+ * @param delimiterStartIndex the index of the character to check
+ * @return true if (delimterStartIndex - 2) in messagePattern is an escape character.
+ * Always returns false if delimiterStartIndex is less than 2 (edge case)
+ */
static boolean isDoubleEscaped(String messagePattern, int delimiterStartIndex) {
return delimiterStartIndex >= 2 && messagePattern.charAt(delimiterStartIndex - 2) == ESCAPE_CHAR;
}
diff --git a/libs/core/src/main/java/org/opensearch/core/common/settings/SecureString.java b/libs/core/src/main/java/org/opensearch/core/common/settings/SecureString.java
index f5529bcebc82f..45ee72f558724 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/settings/SecureString.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/settings/SecureString.java
@@ -32,6 +32,8 @@
package org.opensearch.core.common.settings;
+import org.opensearch.common.annotation.PublicApi;
+
import java.io.Closeable;
import java.util.Arrays;
import java.util.Objects;
@@ -39,15 +41,16 @@
/**
* A String implementations which allows clearing the underlying char array.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public final class SecureString implements CharSequence, Closeable {
private char[] chars;
/**
* Constructs a new SecureString which controls the passed in char array.
- *
+ *
* Note: When this instance is closed, the array will be zeroed out.
*/
public SecureString(char[] chars) {
@@ -56,7 +59,7 @@ public SecureString(char[] chars) {
/**
* Constructs a new SecureString from an existing String.
- *
+ *
* NOTE: This is not actually secure, since the provided String cannot be deallocated, but
* this constructor allows for easy compatibility between new and old apis.
*
diff --git a/libs/core/src/main/java/org/opensearch/core/common/text/Text.java b/libs/core/src/main/java/org/opensearch/core/common/text/Text.java
index ca5402edae59e..3a46bd4602297 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/text/Text.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/text/Text.java
@@ -32,6 +32,7 @@
package org.opensearch.core.common.text;
import org.apache.lucene.util.BytesRef;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.common.bytes.BytesReference;
import org.opensearch.core.xcontent.ToXContentFragment;
@@ -44,8 +45,9 @@
* Both {@link String} and {@link BytesReference} representation of the text. Starts with one of those, and if
* the other is requests, caches the other one in a local reference so no additional conversion will be needed.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public final class Text implements Comparable, ToXContentFragment {
public static final Text[] EMPTY_ARRAY = new Text[0];
diff --git a/server/src/main/java/org/opensearch/common/transport/BoundTransportAddress.java b/libs/core/src/main/java/org/opensearch/core/common/transport/BoundTransportAddress.java
similarity index 98%
rename from server/src/main/java/org/opensearch/common/transport/BoundTransportAddress.java
rename to libs/core/src/main/java/org/opensearch/core/common/transport/BoundTransportAddress.java
index 3a9c337f2d950..8908a172395f2 100644
--- a/server/src/main/java/org/opensearch/common/transport/BoundTransportAddress.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/transport/BoundTransportAddress.java
@@ -30,12 +30,12 @@
* GitHub history for details.
*/
-package org.opensearch.common.transport;
+package org.opensearch.core.common.transport;
+import org.opensearch.common.network.InetAddresses;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.common.network.InetAddresses;
import java.io.IOException;
diff --git a/server/src/main/java/org/opensearch/common/transport/TransportAddress.java b/libs/core/src/main/java/org/opensearch/core/common/transport/TransportAddress.java
similarity index 88%
rename from server/src/main/java/org/opensearch/common/transport/TransportAddress.java
rename to libs/core/src/main/java/org/opensearch/core/common/transport/TransportAddress.java
index 737e8f3496143..3b5fbb7d76307 100644
--- a/server/src/main/java/org/opensearch/common/transport/TransportAddress.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/transport/TransportAddress.java
@@ -30,12 +30,13 @@
* GitHub history for details.
*/
-package org.opensearch.common.transport;
+package org.opensearch.core.common.transport;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.common.network.NetworkAddress;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.common.network.NetworkAddress;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
@@ -47,8 +48,9 @@
/**
* A transport address used for IP socket address (wraps {@link java.net.InetSocketAddress}).
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public final class TransportAddress implements Writeable, ToXContentFragment {
/**
@@ -71,6 +73,12 @@ public TransportAddress(InetAddress address, int port) {
this(new InetSocketAddress(address, port));
}
+ /**
+ * Creates a new {@link TransportAddress} from a {@link InetSocketAddress}.
+ * @param address the address to wrap
+ * @throws IllegalArgumentException if the address is null or not resolved
+ * @see InetSocketAddress#getAddress()
+ */
public TransportAddress(InetSocketAddress address) {
if (address == null) {
throw new IllegalArgumentException("InetSocketAddress must not be null");
@@ -82,7 +90,9 @@ public TransportAddress(InetSocketAddress address) {
}
/**
- * Read from a stream.
+ * Creates a new {@link TransportAddress} from a {@link StreamInput}.
+ * @param in the stream to read from
+ * @throws IOException if an I/O error occurs
*/
public TransportAddress(StreamInput in) throws IOException {
final int len = in.readByte();
@@ -116,6 +126,8 @@ public String getAddress() {
/**
* Returns the addresses port
+ * @return the port number, or 0 if the socket is not bound yet.
+ * @see InetSocketAddress#getPort()
*/
public int getPort() {
return address.getPort();
diff --git a/libs/core/src/main/java/org/opensearch/core/common/transport/package-info.java b/libs/core/src/main/java/org/opensearch/core/common/transport/package-info.java
new file mode 100644
index 0000000000000..21d2abfce958a
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/common/transport/package-info.java
@@ -0,0 +1,10 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/** Common / Base Transport classes used to implement the OpenSearch transport layer */
+package org.opensearch.core.common.transport;
diff --git a/server/src/main/java/org/opensearch/common/unit/ByteSizeUnit.java b/libs/core/src/main/java/org/opensearch/core/common/unit/ByteSizeUnit.java
similarity index 96%
rename from server/src/main/java/org/opensearch/common/unit/ByteSizeUnit.java
rename to libs/core/src/main/java/org/opensearch/core/common/unit/ByteSizeUnit.java
index b95e39feb8fac..49eadbbb2bc00 100644
--- a/server/src/main/java/org/opensearch/common/unit/ByteSizeUnit.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/unit/ByteSizeUnit.java
@@ -30,8 +30,9 @@
* GitHub history for details.
*/
-package org.opensearch.common.unit;
+package org.opensearch.core.common.unit;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
@@ -44,9 +45,17 @@
* A {@code SizeUnit} does not maintain size information, but only
* helps organize and use size representations that may be maintained
* separately across various contexts.
+ *
+ * It use conventional data storage values (base-2) :
+ *
+ * 1KB = 1024 bytes
+ * 1MB = 1024KB
+ * ...
+ *
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public enum ByteSizeUnit implements Writeable {
BYTES {
@Override
diff --git a/server/src/main/java/org/opensearch/common/unit/ByteSizeValue.java b/libs/core/src/main/java/org/opensearch/core/common/unit/ByteSizeValue.java
similarity index 88%
rename from server/src/main/java/org/opensearch/common/unit/ByteSizeValue.java
rename to libs/core/src/main/java/org/opensearch/core/common/unit/ByteSizeValue.java
index a123c79464727..1ed6d2d204a99 100644
--- a/server/src/main/java/org/opensearch/common/unit/ByteSizeValue.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/unit/ByteSizeValue.java
@@ -30,16 +30,14 @@
* GitHub history for details.
*/
-package org.opensearch.common.unit;
+package org.opensearch.core.common.unit;
import org.opensearch.OpenSearchParseException;
-import org.opensearch.common.Strings;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.common.logging.DeprecationLogger;
-import org.opensearch.common.logging.LogConfigurator;
-import org.opensearch.common.network.NetworkService;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
@@ -50,21 +48,11 @@
/**
* A byte size value
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class ByteSizeValue implements Writeable, Comparable, ToXContentFragment {
- /**
- * We have to lazy initialize the deprecation logger as otherwise a static logger here would be constructed before logging is configured
- * leading to a runtime failure (see {@link LogConfigurator#checkErrorListener()} ). The premature construction would come from any
- * {@link ByteSizeValue} object constructed in, for example, settings in {@link NetworkService}.
- *
- * @opensearch.internal
- */
- static class DeprecationLoggerHolder {
- static DeprecationLogger deprecationLogger = DeprecationLogger.getLogger(ByteSizeValue.class);
- }
-
public static final ByteSizeValue ZERO = new ByteSizeValue(0, ByteSizeUnit.BYTES);
private final long size;
@@ -262,14 +250,14 @@ private static ByteSizeValue parse(
return new ByteSizeValue(Long.parseLong(s), unit);
} catch (final NumberFormatException e) {
try {
- final double doubleValue = Double.parseDouble(s);
- DeprecationLoggerHolder.deprecationLogger.deprecate(
- "fractional_byte_values",
- "Fractional bytes values are deprecated. Use non-fractional bytes values instead: [{}] found for setting [{}]",
+ Double.parseDouble(s);
+ throw new OpenSearchParseException(
+ "Failed to parse bytes value [{}]. Fractional bytes values have been "
+ + "deprecated since Legacy 6.2. Use non-fractional bytes values instead: found for setting [{}]",
+ e,
initialInput,
settingName
);
- return new ByteSizeValue((long) (doubleValue * unit.toBytes(1)));
} catch (final NumberFormatException ignored) {
throw new OpenSearchParseException("failed to parse [{}]", e, initialInput);
}
diff --git a/libs/core/src/main/java/org/opensearch/core/common/unit/package-info.java b/libs/core/src/main/java/org/opensearch/core/common/unit/package-info.java
new file mode 100644
index 0000000000000..79b5dcdcba3b6
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/common/unit/package-info.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Common units of measurement used by the core library. These units of measurement classes exist
+ * in the core because they depend on core functionality beyond the common library (e.g., serializable).
+ *
+ * @opensearch.api
+ * @opensearch.experimental
+ */
+package org.opensearch.core.common.unit;
diff --git a/libs/core/src/main/java/org/opensearch/core/common/util/ByteArray.java b/libs/core/src/main/java/org/opensearch/core/common/util/ByteArray.java
index e50f24417f8bc..f4d81c4ca4363 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/util/ByteArray.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/util/ByteArray.java
@@ -33,14 +33,16 @@
package org.opensearch.core.common.util;
import org.apache.lucene.util.BytesRef;
+import org.opensearch.common.annotation.PublicApi;
import java.nio.ByteBuffer;
/**
* Abstraction of an array of byte values.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface ByteArray extends BigArray {
/**
diff --git a/server/src/main/java/org/opensearch/common/util/CollectionUtils.java b/libs/core/src/main/java/org/opensearch/core/common/util/CollectionUtils.java
similarity index 79%
rename from server/src/main/java/org/opensearch/common/util/CollectionUtils.java
rename to libs/core/src/main/java/org/opensearch/core/common/util/CollectionUtils.java
index 2037b2e46488f..5335c98182b64 100644
--- a/server/src/main/java/org/opensearch/common/util/CollectionUtils.java
+++ b/libs/core/src/main/java/org/opensearch/core/common/util/CollectionUtils.java
@@ -30,7 +30,7 @@
* GitHub history for details.
*/
-package org.opensearch.common.util;
+package org.opensearch.core.common.util;
import org.opensearch.common.collect.Iterators;
import org.opensearch.core.common.Strings;
@@ -73,6 +73,16 @@ public static boolean isEmpty(Object[] array) {
/**
* Return a rotated view of the given list with the given distance.
+ *
+ * The distance can be negative, in which case the list is rotated to the left.
+ * The distance can be larger than the size of the list, in which case the list is rotated multiple times.
+ * The distance can be zero, in which case the list is not rotated.
+ * The list can be empty, in which case it remains empty.
+ *
+ * @param list the list to rotate
+ * @param distance the distance to rotate (positive rotates right, negative rotates left)
+ * @return a rotated view of the given list with the given distance
+ * @see RotatedList
*/
public static List rotate(final List list, int distance) {
if (list.isEmpty()) {
@@ -92,7 +102,13 @@ public static List rotate(final List list, int distance) {
}
/**
- * in place de-duplicates items in a list
+ * In place de-duplicates items in a list
+ * Noop if the list is empty or has one item.
+ *
+ * @throws NullPointerException if the list is `null` or comparator is `null`
+ * @param array the list to de-duplicate
+ * @param comparator the comparator to use to compare items
+ * @param the type of the items in the list
*/
public static void sortAndDedup(final List array, Comparator comparator) {
// base case: one item
@@ -115,6 +131,12 @@ public static void sortAndDedup(final List array, Comparator comparato
array.subList(deduped.nextIndex(), array.size()).clear();
}
+ /**
+ * Converts a collection of Integers to an array of ints.
+ * @param ints The collection of Integers to convert
+ * @return The array of ints
+ * @throws NullPointerException if ints is null
+ */
public static int[] toArray(Collection ints) {
Objects.requireNonNull(ints);
return ints.stream().mapToInt(s -> s).toArray();
@@ -134,6 +156,12 @@ public static void ensureNoSelfReferences(Object value, String messageHint) {
}
}
+ /**
+ * Converts an object to an Iterable, if possible.
+ * @param value The object to convert
+ * @return The Iterable, or null if the object cannot be converted
+ */
+ @SuppressWarnings("unchecked")
private static Iterable> convert(Object value) {
if (value == null) {
return null;
@@ -191,6 +219,13 @@ private static class RotatedList extends AbstractList implements RandomAcc
private final List in;
private final int distance;
+ /**
+ * Creates a rotated list
+ * @param list The list to rotate
+ * @param distance The distance to rotate to the right
+ * @throws IllegalArgumentException if the distance is negative or greater than the size of the list;
+ * or if the list is not a {@link RandomAccess} list
+ */
RotatedList(List list, int distance) {
if (distance < 0 || distance >= list.size()) {
throw new IllegalArgumentException();
@@ -217,6 +252,14 @@ public int size() {
}
}
+ /**
+ * Converts an {@link Iterable} to an {@link ArrayList}.
+ * @param elements The iterable to convert
+ * @param the type the elements
+ * @return an {@link ArrayList}
+ * @throws NullPointerException if elements is null
+ */
+ @SuppressWarnings("unchecked")
public static ArrayList iterableAsArrayList(Iterable extends E> elements) {
if (elements == null) {
throw new NullPointerException("elements");
@@ -232,6 +275,7 @@ public static ArrayList iterableAsArrayList(Iterable extends E> element
}
}
+ @SuppressWarnings("unchecked")
public static ArrayList arrayAsArrayList(E... elements) {
if (elements == null) {
throw new NullPointerException("elements");
@@ -239,6 +283,7 @@ public static ArrayList arrayAsArrayList(E... elements) {
return new ArrayList<>(Arrays.asList(elements));
}
+ @SuppressWarnings("unchecked")
public static ArrayList asArrayList(E first, E... other) {
if (other == null) {
throw new NullPointerException("other");
@@ -249,6 +294,7 @@ public static ArrayList asArrayList(E first, E... other) {
return list;
}
+ @SuppressWarnings("unchecked")
public static ArrayList asArrayList(E first, E second, E... other) {
if (other == null) {
throw new NullPointerException("other");
@@ -292,11 +338,11 @@ public static List> eagerPartition(List list, int size) {
}
/**
- * Check if a collection is empty or not. Empty collection mean either it is null or it has no elements in it. If
- * collection contains a null element it means it is not empty.
+ * Checks if a collection is empty or not. Empty collection mean either it is null or it has no elements in it.
+ * If collection contains a null element it means it is not empty.
*
* @param collection {@link Collection}
- * @return boolean
+ * @return true if collection is null or {@code isEmpty()}, false otherwise
* @param Element
*/
public static boolean isEmpty(final Collection collection) {
diff --git a/server/src/main/java/org/opensearch/common/compress/Compressor.java b/libs/core/src/main/java/org/opensearch/core/compress/Compressor.java
similarity index 77%
rename from server/src/main/java/org/opensearch/common/compress/Compressor.java
rename to libs/core/src/main/java/org/opensearch/core/compress/Compressor.java
index 1034e3a1da5da..5324ea6151e51 100644
--- a/server/src/main/java/org/opensearch/common/compress/Compressor.java
+++ b/libs/core/src/main/java/org/opensearch/core/compress/Compressor.java
@@ -30,8 +30,10 @@
* GitHub history for details.
*/
-package org.opensearch.common.compress;
+package org.opensearch.core.compress;
+import org.opensearch.common.annotation.ExperimentalApi;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.common.bytes.BytesReference;
import java.io.IOException;
@@ -39,10 +41,18 @@
import java.io.OutputStream;
/**
- * Compressor interface
+ * Compressor interface used for compressing {@link org.opensearch.core.xcontent.MediaType} and
+ * {@code org.opensearch.repositories.blobstore.BlobStoreRepository} implementations.
+ *
+ * This is not to be confused with {@link org.apache.lucene.codecs.compressing.Compressor} which is used
+ * for codec implementations such as {@code org.opensearch.index.codec.customcodecs.Lucene95CustomCodec}
+ * for compressing {@link org.apache.lucene.document.StoredField}s
*
- * @opensearch.internal
+ * @opensearch.api - intended to be extended
+ * @opensearch.experimental - however, bwc is not guaranteed at this time
*/
+@ExperimentalApi
+@PublicApi(since = "2.10.0")
public interface Compressor {
boolean isCompressed(BytesReference bytes);
diff --git a/libs/core/src/main/java/org/opensearch/core/compress/CompressorRegistry.java b/libs/core/src/main/java/org/opensearch/core/compress/CompressorRegistry.java
new file mode 100644
index 0000000000000..af09a7aebba79
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/compress/CompressorRegistry.java
@@ -0,0 +1,115 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.core.compress;
+
+import org.opensearch.common.Nullable;
+import org.opensearch.common.annotation.InternalApi;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.compress.spi.CompressorProvider;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
+
+import java.io.IOException;
+import java.util.Map;
+import java.util.Objects;
+import java.util.ServiceLoader;
+import java.util.stream.Collectors;
+
+/**
+ * A registry that wraps a static Map singleton which holds a mapping of unique String names (typically the
+ * compressor header as a string) to registerd {@link Compressor} implementations.
+ *
+ * This enables plugins, modules, extensions to register their own compression implementations through SPI
+ *
+ * @opensearch.experimental
+ * @opensearch.internal
+ */
+@InternalApi
+public final class CompressorRegistry {
+
+ // the backing registry map
+ private static final Map registeredCompressors = ServiceLoader.load(
+ CompressorProvider.class,
+ CompressorProvider.class.getClassLoader()
+ )
+ .stream()
+ .flatMap(p -> p.get().getCompressors().stream())
+ .collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
+
+ // no instance:
+ private CompressorRegistry() {}
+
+ /**
+ * Returns the default compressor
+ */
+ public static Compressor defaultCompressor() {
+ return registeredCompressors.get("DEFLATE");
+ }
+
+ public static Compressor none() {
+ return registeredCompressors.get(NoneCompressor.NAME);
+ }
+
+ public static boolean isCompressed(BytesReference bytes) {
+ return compressor(bytes) != null;
+ }
+
+ @Nullable
+ public static Compressor compressor(final BytesReference bytes) {
+ for (Compressor compressor : registeredCompressors.values()) {
+ if (compressor.isCompressed(bytes) == true) {
+ // bytes should be either detected as compressed or as xcontent,
+ // if we have bytes that can be either detected as compressed or
+ // as a xcontent, we have a problem
+ assert MediaTypeRegistry.xContentType(bytes) == null;
+ return compressor;
+ }
+ }
+
+ if (MediaTypeRegistry.xContentType(bytes) == null) {
+ throw new NotXContentException("Compressor detection can only be called on some xcontent bytes or compressed xcontent bytes");
+ }
+
+ return null;
+ }
+
+ /** Decompress the provided {@link BytesReference}. */
+ public static BytesReference uncompress(BytesReference bytes) throws IOException {
+ Compressor compressor = compressor(bytes);
+ if (compressor == null) {
+ throw new NotCompressedException();
+ }
+ return compressor.uncompress(bytes);
+ }
+
+ /**
+ * Uncompress the provided data, data can be detected as compressed using {@link #isCompressed(BytesReference)}.
+ */
+ public static BytesReference uncompressIfNeeded(BytesReference bytes) throws IOException {
+ Compressor compressor = compressor(Objects.requireNonNull(bytes, "the BytesReference must not be null"));
+ return compressor == null ? bytes : compressor.uncompress(bytes);
+ }
+
+ /** Returns a registered compressor by its registered name */
+ public static Compressor getCompressor(final String name) {
+ if (registeredCompressors.containsKey(name)) {
+ return registeredCompressors.get(name);
+ }
+ throw new IllegalArgumentException("No registered compressor found by name [" + name + "]");
+ }
+
+ /**
+ * Returns the registered compressors as an Immutable collection
+ *
+ * note: used for testing
+ */
+ public static Map registeredCompressors() {
+ // no destructive danger as backing map is immutable
+ return registeredCompressors;
+ }
+}
diff --git a/libs/core/src/main/java/org/opensearch/core/compress/NoneCompressor.java b/libs/core/src/main/java/org/opensearch/core/compress/NoneCompressor.java
new file mode 100644
index 0000000000000..6e607ed701633
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/compress/NoneCompressor.java
@@ -0,0 +1,63 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.core.compress;
+
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.common.bytes.BytesReference;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * {@link Compressor} no compressor implementation.
+ *
+ * @opensearch.api - registered name requires BWC support
+ * @opensearch.experimental - class methods might change
+ */
+public class NoneCompressor implements Compressor {
+ /**
+ * The name to register the compressor by
+ *
+ * @opensearch.api - requires BWC support
+ */
+ @PublicApi(since = "2.10.0")
+ public static final String NAME = "NONE";
+
+ @Override
+ public boolean isCompressed(BytesReference bytes) {
+ return false;
+ }
+
+ @Override
+ public int headerLength() {
+ return 0;
+ }
+
+ @Override
+ public InputStream threadLocalInputStream(InputStream in) throws IOException {
+ return in;
+ }
+
+ @Override
+ public OutputStream threadLocalOutputStream(OutputStream out) throws IOException {
+ return out;
+ }
+
+ @Override
+ public BytesReference uncompress(BytesReference bytesReference) throws IOException {
+ return bytesReference;
+ }
+
+ @Override
+ public BytesReference compress(BytesReference bytesReference) throws IOException {
+ return bytesReference;
+ }
+
+}
diff --git a/server/src/main/java/org/opensearch/common/compress/NotCompressedException.java b/libs/core/src/main/java/org/opensearch/core/compress/NotCompressedException.java
similarity index 97%
rename from server/src/main/java/org/opensearch/common/compress/NotCompressedException.java
rename to libs/core/src/main/java/org/opensearch/core/compress/NotCompressedException.java
index 7f070e0b499d8..91d6bc57f1cd6 100644
--- a/server/src/main/java/org/opensearch/common/compress/NotCompressedException.java
+++ b/libs/core/src/main/java/org/opensearch/core/compress/NotCompressedException.java
@@ -30,7 +30,7 @@
* GitHub history for details.
*/
-package org.opensearch.common.compress;
+package org.opensearch.core.compress;
/**
* Exception indicating that we were expecting something compressed, which
diff --git a/libs/core/src/main/java/org/opensearch/core/common/compress/NotXContentException.java b/libs/core/src/main/java/org/opensearch/core/compress/NotXContentException.java
similarity index 96%
rename from libs/core/src/main/java/org/opensearch/core/common/compress/NotXContentException.java
rename to libs/core/src/main/java/org/opensearch/core/compress/NotXContentException.java
index d1a3e7709a7d0..99337d5a26025 100644
--- a/libs/core/src/main/java/org/opensearch/core/common/compress/NotXContentException.java
+++ b/libs/core/src/main/java/org/opensearch/core/compress/NotXContentException.java
@@ -30,7 +30,7 @@
* GitHub history for details.
*/
-package org.opensearch.core.common.compress;
+package org.opensearch.core.compress;
import org.opensearch.core.xcontent.XContent;
diff --git a/libs/core/src/main/java/org/opensearch/core/compress/package-info.java b/libs/core/src/main/java/org/opensearch/core/compress/package-info.java
new file mode 100644
index 0000000000000..c0365e45702bc
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/compress/package-info.java
@@ -0,0 +1,14 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Concrete {@link org.opensearch.core.compress.Compressor} implementations provided by the core library
+ *
+ * See {@link org.opensearch.core.compress.NoneCompressor}
+ */
+package org.opensearch.core.compress;
diff --git a/libs/core/src/main/java/org/opensearch/core/compress/spi/CompressorProvider.java b/libs/core/src/main/java/org/opensearch/core/compress/spi/CompressorProvider.java
new file mode 100644
index 0000000000000..9b806618fe0a0
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/compress/spi/CompressorProvider.java
@@ -0,0 +1,34 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.core.compress.spi;
+
+import org.opensearch.common.annotation.ExperimentalApi;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.compress.Compressor;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Service Provider Interface for plugins, modules, extensions providing custom
+ * compression algorithms
+ *
+ * see {@link Compressor} for implementing methods
+ * and {@link org.opensearch.core.compress.CompressorRegistry} for the registration of custom
+ * Compressors
+ *
+ * @opensearch.experimental
+ * @opensearch.api
+ */
+@ExperimentalApi
+@PublicApi(since = "2.10.0")
+public interface CompressorProvider {
+ /** Extensions that implement their own concrete {@link Compressor}s provide them through this interface method*/
+ List> getCompressors();
+}
diff --git a/libs/core/src/main/java/org/opensearch/core/compress/spi/DefaultCompressorProvider.java b/libs/core/src/main/java/org/opensearch/core/compress/spi/DefaultCompressorProvider.java
new file mode 100644
index 0000000000000..3ca10b564ef68
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/compress/spi/DefaultCompressorProvider.java
@@ -0,0 +1,31 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.core.compress.spi;
+
+import org.opensearch.core.compress.Compressor;
+import org.opensearch.core.compress.NoneCompressor;
+
+import java.util.AbstractMap.SimpleEntry;
+import java.util.List;
+import java.util.Map.Entry;
+
+/**
+ * Default {@link Compressor} implementations provided by the
+ * opensearch core library
+ *
+ * @opensearch.internal
+ */
+public class DefaultCompressorProvider implements CompressorProvider {
+ /** Returns the default {@link Compressor}s provided by the core library */
+ @SuppressWarnings({ "unchecked", "rawtypes" })
+ @Override
+ public List> getCompressors() {
+ return List.of(new SimpleEntry(NoneCompressor.NAME, new NoneCompressor()));
+ }
+}
diff --git a/libs/core/src/main/java/org/opensearch/core/compress/spi/package-info.java b/libs/core/src/main/java/org/opensearch/core/compress/spi/package-info.java
new file mode 100644
index 0000000000000..6e33cc8fb63d3
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/compress/spi/package-info.java
@@ -0,0 +1,16 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * The Service Provider Interface implementation for registering {@link org.opensearch.core.compress.Compressor}
+ * with the {@link org.opensearch.core.compress.CompressorRegistry}
+ *
+ * See {@link org.opensearch.core.compress.spi.DefaultCompressorProvider} as an example of registering the core
+ * {@link org.opensearch.core.compress.NoneCompressor}
+ */
+package org.opensearch.core.compress.spi;
diff --git a/libs/core/src/main/java/org/opensearch/core/index/Index.java b/libs/core/src/main/java/org/opensearch/core/index/Index.java
index fc5c5152a5500..a927179114188 100644
--- a/libs/core/src/main/java/org/opensearch/core/index/Index.java
+++ b/libs/core/src/main/java/org/opensearch/core/index/Index.java
@@ -32,11 +32,12 @@
package org.opensearch.core.index;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.ParseField;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.core.common.Strings;
import org.opensearch.core.xcontent.ObjectParser;
import org.opensearch.core.xcontent.ToXContentObject;
import org.opensearch.core.xcontent.XContentBuilder;
@@ -47,14 +48,19 @@
/**
* A value class representing the basic required properties of an OpenSearch index.
+ *
+ * (This class is immutable.)
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class Index implements Writeable, ToXContentObject {
public static final Index[] EMPTY_ARRAY = new Index[0];
private static final String INDEX_UUID_KEY = "index_uuid";
private static final String INDEX_NAME_KEY = "index_name";
+ public static final String UNKNOWN_INDEX_NAME = "_unknown_";
+
private static final ObjectParser INDEX_PARSER = new ObjectParser<>("index", Builder::new);
static {
INDEX_PARSER.declareString(Builder::name, new ParseField(INDEX_NAME_KEY));
@@ -64,39 +70,74 @@ public class Index implements Writeable, ToXContentObject {
private final String name;
private final String uuid;
+ /**
+ * Creates a new Index instance with name and unique identifier
+ *
+ * @param name the name of the index
+ * @param uuid the unique identifier of the index
+ * @throws NullPointerException if either name or uuid are null
+ */
public Index(String name, String uuid) {
this.name = Objects.requireNonNull(name);
this.uuid = Objects.requireNonNull(uuid);
}
/**
- * Read from a stream.
+ * Creates a new Index instance from a {@link StreamInput}.
+ * Reads the name and unique identifier from the stream.
+ *
+ * @param in the stream to read from
+ * @throws IOException if an error occurs while reading from the stream
+ * @see #writeTo(StreamOutput)
*/
public Index(StreamInput in) throws IOException {
this.name = in.readString();
this.uuid = in.readString();
}
+ /**
+ * Gets the name of the index.
+ *
+ * @return the name of the index.
+ */
public String getName() {
return this.name;
}
+ /**
+ * Gets the unique identifier of the index.
+ *
+ * @return the unique identifier of the index. "_na_" if {@link Strings#UNKNOWN_UUID_VALUE}.
+ */
public String getUUID() {
return uuid;
}
+ /**
+ * Returns either the name and unique identifier of the index
+ * or only the name if the uuid is {@link Strings#UNKNOWN_UUID_VALUE}.
+ *
+ * If we have a uuid we put it in the toString so it'll show up in logs
+ * which is useful as more and more things use the uuid rather
+ * than the name as the lookup key for the index.
+ *
+ * @return {@code "[name/uuid]"} or {@code "[name]"}
+ */
@Override
public String toString() {
- /*
- * If we have a uuid we put it in the toString so it'll show up in logs which is useful as more and more things use the uuid rather
- * than the name as the lookup key for the index.
- */
if (Strings.UNKNOWN_UUID_VALUE.equals(uuid)) {
return "[" + name + "]";
}
return "[" + name + "/" + uuid + "]";
}
+ /**
+ * Checks if this index is the same as another index by comparing the name and unique identifier.
+ * If both uuid are {@link Strings#UNKNOWN_UUID_VALUE} then only the name is compared.
+ *
+ * @param o the index to compare to
+ * @return true if the name and unique identifier are the same, false otherwise.
+ */
@Override
public boolean equals(Object o) {
if (this == o) {
@@ -116,6 +157,10 @@ public int hashCode() {
return result;
}
+ /** Writes the name and unique identifier to the {@link StreamOutput}
+ *
+ * @param out The stream to write to
+ */
@Override
public void writeTo(final StreamOutput out) throws IOException {
out.writeString(name);
diff --git a/libs/core/src/main/java/org/opensearch/core/index/shard/ShardId.java b/libs/core/src/main/java/org/opensearch/core/index/shard/ShardId.java
index b01121c3f30d4..1e48cf1f476da 100644
--- a/libs/core/src/main/java/org/opensearch/core/index/shard/ShardId.java
+++ b/libs/core/src/main/java/org/opensearch/core/index/shard/ShardId.java
@@ -32,65 +32,117 @@
package org.opensearch.core.index.shard;
+import org.apache.lucene.util.RamUsageEstimator;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
+import org.opensearch.core.index.Index;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.core.index.Index;
import java.io.IOException;
/**
* Allows for shard level components to be injected with the shard id.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class ShardId implements Comparable, ToXContentFragment, Writeable {
private final Index index;
private final int shardId;
private final int hashCode;
+ private final static long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(ShardId.class);
+
+ /**
+ * Constructs a new shard id.
+ * @param index the index name
+ * @param shardId the shard id
+ */
public ShardId(Index index, int shardId) {
this.index = index;
this.shardId = shardId;
this.hashCode = computeHashCode();
}
+ /**
+ * Constructs a new shard id with the given index name, index unique identifier, and shard id.
+ * @param index the index name
+ * @param indexUUID the index unique identifier
+ * @param shardId the shard id
+ */
public ShardId(String index, String indexUUID, int shardId) {
this(new Index(index, indexUUID), shardId);
}
+ /**
+ * Constructs a new shardId from a stream.
+ * @param in the stream to read from
+ * @throws IOException if an error occurs while reading from the stream
+ * @see #writeTo(StreamOutput)
+ */
public ShardId(StreamInput in) throws IOException {
index = new Index(in);
shardId = in.readVInt();
hashCode = computeHashCode();
}
+ public long getBaseRamBytesUsed() {
+ return BASE_RAM_BYTES_USED;
+ }
+
+ /**
+ * Writes this shard id to a stream.
+ * @param out the stream to write to
+ * @throws IOException if an error occurs while writing to the stream
+ */
@Override
public void writeTo(StreamOutput out) throws IOException {
index.writeTo(out);
out.writeVInt(shardId);
}
+ /**
+ * Returns the index of this shard id.
+ * @return the index of this shard id
+ */
public Index getIndex() {
return index;
}
+ /**
+ * Returns the name of the index of this shard id.
+ * @return the name of the index of this shard id
+ */
public String getIndexName() {
return index.getName();
}
+ /**
+ * Return the shardId of this shard id.
+ * @return the shardId of this shard id
+ * @see #getId()
+ */
public int id() {
return this.shardId;
}
+ /**
+ * Returns the shard id of this shard id.
+ * @return the shard id of this shard id
+ */
public int getId() {
return id();
}
+ /**
+ * Returns a string representation of this shard id.
+ * @return "[indexName][shardId]"
+ */
@Override
public String toString() {
return "[" + index.getName() + "][" + shardId + "]";
@@ -98,9 +150,13 @@ public String toString() {
/**
* Parse the string representation of this shardId back to an object.
+ *
* We lose index uuid information here, but since we use toString in
* rest responses, this is the best we can do to reconstruct the object
* on the client side.
+ *
+ * @param shardIdString the string representation of the shard id
+ * (Expect a string of format "[indexName][shardId]" (square brackets included))
*/
public static ShardId fromString(String shardIdString) {
int splitPosition = shardIdString.indexOf("][");
@@ -120,17 +176,30 @@ public boolean equals(Object o) {
return shardId == shardId1.shardId && index.equals(shardId1.index);
}
+ /** Returns the hash code of this shard id.
+ *
+ * @return the hash code of this shard id
+ */
@Override
public int hashCode() {
return hashCode;
}
+ /** Computes the hash code of this shard id.
+ *
+ * @return the hash code of this shard id.
+ */
private int computeHashCode() {
int result = index != null ? index.hashCode() : 0;
result = 31 * result + shardId;
return result;
}
+ /**
+ * Compares this ShardId with the specified ShardId.
+ * @param o the ShardId to be compared.
+ * @return a negative integer, zero, or a positive integer if this ShardId is less than, equal to, or greater than the specified ShardId
+ */
@Override
public int compareTo(ShardId o) {
if (o.getId() == shardId) {
diff --git a/libs/core/src/main/java/org/opensearch/core/indices/breaker/AllCircuitBreakerStats.java b/libs/core/src/main/java/org/opensearch/core/indices/breaker/AllCircuitBreakerStats.java
new file mode 100644
index 0000000000000..992655efec8f0
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/indices/breaker/AllCircuitBreakerStats.java
@@ -0,0 +1,126 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+package org.opensearch.core.indices.breaker;
+
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.common.io.stream.StreamInput;
+import org.opensearch.core.common.io.stream.StreamOutput;
+import org.opensearch.core.common.io.stream.Writeable;
+import org.opensearch.core.xcontent.ToXContentFragment;
+import org.opensearch.core.xcontent.XContentBuilder;
+
+import java.io.IOException;
+
+/**
+ * Stats class encapsulating all of the different circuit breaker stats
+ *
+ * @opensearch.api
+ */
+@PublicApi(since = "1.0.0")
+public class AllCircuitBreakerStats implements Writeable, ToXContentFragment {
+
+ /** An array of all the circuit breaker stats */
+ private final CircuitBreakerStats[] allStats;
+
+ /**
+ * Constructs the instance
+ *
+ * @param allStats an array of all the circuit breaker stats
+ */
+ public AllCircuitBreakerStats(CircuitBreakerStats[] allStats) {
+ this.allStats = allStats;
+ }
+
+ /**
+ * Constructs the new instance from {@link StreamInput}
+ * @param in the {@link StreamInput} to read from
+ * @throws IOException If an error occurs while reading from the StreamInput
+ * @see #writeTo(StreamOutput)
+ */
+ public AllCircuitBreakerStats(StreamInput in) throws IOException {
+ allStats = in.readArray(CircuitBreakerStats::new, CircuitBreakerStats[]::new);
+ }
+
+ /**
+ * Writes this instance into a {@link StreamOutput}
+ * @param out the {@link StreamOutput} to write to
+ * @throws IOException if an error occurs while writing to the StreamOutput
+ */
+ @Override
+ public void writeTo(StreamOutput out) throws IOException {
+ out.writeArray(allStats);
+ }
+
+ /**
+ * Returns inner stats instances for all circuit breakers
+ * @return inner stats instances for all circuit breakers
+ */
+ public CircuitBreakerStats[] getAllStats() {
+ return this.allStats;
+ }
+
+ /**
+ * Returns the stats for a specific circuit breaker
+ * @param name the name of the circuit breaker
+ * @return the {@link CircuitBreakerStats} for the circuit breaker, null if the circuit breaker with such name does not exist
+ */
+ public CircuitBreakerStats getStats(String name) {
+ for (CircuitBreakerStats stats : allStats) {
+ if (stats.getName().equals(name)) {
+ return stats;
+ }
+ }
+ return null;
+ }
+
+ @Override
+ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
+ builder.startObject(Fields.BREAKERS);
+ for (CircuitBreakerStats stats : allStats) {
+ if (stats != null) {
+ stats.toXContent(builder, params);
+ }
+ }
+ builder.endObject();
+ return builder;
+ }
+
+ /**
+ * Fields used for parsing and toXContent
+ *
+ * @opensearch.internal
+ */
+ static final class Fields {
+ static final String BREAKERS = "breakers";
+ }
+}
diff --git a/server/src/main/java/org/opensearch/indices/breaker/CircuitBreakerService.java b/libs/core/src/main/java/org/opensearch/core/indices/breaker/CircuitBreakerService.java
similarity index 83%
rename from server/src/main/java/org/opensearch/indices/breaker/CircuitBreakerService.java
rename to libs/core/src/main/java/org/opensearch/core/indices/breaker/CircuitBreakerService.java
index b5cc1a6b1c6c5..dedeb0803271f 100644
--- a/server/src/main/java/org/opensearch/indices/breaker/CircuitBreakerService.java
+++ b/libs/core/src/main/java/org/opensearch/core/indices/breaker/CircuitBreakerService.java
@@ -30,22 +30,20 @@
* GitHub history for details.
*/
-package org.opensearch.indices.breaker;
+package org.opensearch.core.indices.breaker;
-import org.apache.logging.log4j.LogManager;
-import org.apache.logging.log4j.Logger;
-import org.opensearch.common.breaker.CircuitBreaker;
-import org.opensearch.common.component.AbstractLifecycleComponent;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.common.lifecycle.AbstractLifecycleComponent;
+import org.opensearch.core.common.breaker.CircuitBreaker;
/**
* Interface for Circuit Breaker services, which provide breakers to classes
* that load field data.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public abstract class CircuitBreakerService extends AbstractLifecycleComponent {
- private static final Logger logger = LogManager.getLogger(CircuitBreakerService.class);
-
protected CircuitBreakerService() {}
/**
diff --git a/libs/core/src/main/java/org/opensearch/core/indices/breaker/CircuitBreakerStats.java b/libs/core/src/main/java/org/opensearch/core/indices/breaker/CircuitBreakerStats.java
new file mode 100644
index 0000000000000..ee71cf8d2ac0e
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/indices/breaker/CircuitBreakerStats.java
@@ -0,0 +1,204 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+package org.opensearch.core.indices.breaker;
+
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.common.io.stream.StreamInput;
+import org.opensearch.core.common.io.stream.StreamOutput;
+import org.opensearch.core.common.io.stream.Writeable;
+import org.opensearch.core.common.unit.ByteSizeValue;
+import org.opensearch.core.xcontent.ToXContentObject;
+import org.opensearch.core.xcontent.XContentBuilder;
+
+import java.io.IOException;
+import java.util.Locale;
+
+/**
+ * Class encapsulating stats about the {@link org.opensearch.core.common.breaker.CircuitBreaker}
+ *
+ * @opensearch.api
+ */
+@PublicApi(since = "1.0.0")
+public class CircuitBreakerStats implements Writeable, ToXContentObject {
+
+ /** The name of the circuit breaker */
+ private final String name;
+ /** The limit size in byte of the circuit breaker. Field : "limit_size_in_bytes" */
+ private final long limit;
+ /** The estimated size in byte of the breaker. Field : "estimated_size_in_bytes" */
+ private final long estimated;
+ /** The number of times the breaker has been tripped. Field : "tripped" */
+ private final long trippedCount;
+ /** The overhead of the breaker. Field : "overhead" */
+ private final double overhead;
+
+ /**
+ * Constructs new instance
+ *
+ * @param name The name of the circuit breaker
+ * @param limit The limit size in byte of the circuit breaker
+ * @param estimated The estimated size in byte of the breaker
+ * @param overhead The overhead of the breaker
+ * @param trippedCount The number of times the breaker has been tripped
+ * @see org.opensearch.core.common.breaker.CircuitBreaker
+ */
+ public CircuitBreakerStats(String name, long limit, long estimated, double overhead, long trippedCount) {
+ this.name = name;
+ this.limit = limit;
+ this.estimated = estimated;
+ this.trippedCount = trippedCount;
+ this.overhead = overhead;
+ }
+
+ /**
+ * Constructs new instance from the {@link StreamInput}
+ *
+ * @param in The StreamInput
+ * @throws IOException if an error occurs while reading from the StreamInput
+ * @see org.opensearch.core.common.breaker.CircuitBreaker
+ * @see #writeTo(StreamOutput)
+ */
+ public CircuitBreakerStats(StreamInput in) throws IOException {
+ this.limit = in.readLong();
+ this.estimated = in.readLong();
+ this.overhead = in.readDouble();
+ this.trippedCount = in.readLong();
+ this.name = in.readString();
+ }
+
+ /**
+ * Writes this instance into a {@link StreamOutput}
+ *
+ * @param out The StreamOutput
+ * @throws IOException if an error occurs while writing to the StreamOutput
+ * @see #CircuitBreakerStats(StreamInput)
+ */
+ @Override
+ public void writeTo(StreamOutput out) throws IOException {
+ out.writeLong(limit);
+ out.writeLong(estimated);
+ out.writeDouble(overhead);
+ out.writeLong(trippedCount);
+ out.writeString(name);
+ }
+
+ /**
+ * Returns the name of the circuit breaker
+ * @return The name of the circuit breaker
+ */
+ public String getName() {
+ return this.name;
+ }
+
+ /**
+ * Returns the limit size in byte of the circuit breaker
+ * @return The limit size in byte of the circuit breaker
+ */
+ public long getLimit() {
+ return this.limit;
+ }
+
+ /**
+ * Returns the estimated size in byte of the breaker
+ * @return The estimated size in byte of the breaker
+ */
+ public long getEstimated() {
+ return this.estimated;
+ }
+
+ /**
+ * Returns the number of times the breaker has been tripped
+ * @return The number of times the breaker has been tripped
+ */
+ public long getTrippedCount() {
+ return this.trippedCount;
+ }
+
+ /**
+ * Returns the overhead of the breaker
+ * @return The overhead of the breaker
+ */
+ public double getOverhead() {
+ return this.overhead;
+ }
+
+ @Override
+ public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
+ builder.startObject(name.toLowerCase(Locale.ROOT));
+ builder.field(Fields.LIMIT, limit);
+ builder.field(Fields.LIMIT_HUMAN, new ByteSizeValue(limit));
+ builder.field(Fields.ESTIMATED, estimated);
+ builder.field(Fields.ESTIMATED_HUMAN, new ByteSizeValue(estimated));
+ builder.field(Fields.OVERHEAD, overhead);
+ builder.field(Fields.TRIPPED_COUNT, trippedCount);
+ builder.endObject();
+ return builder;
+ }
+
+ /**
+ * Returns a String representation of this CircuitBreakerStats
+ * @return "[name,limit=limit/limit_human,estimated=estimated/estimated_human,overhead=overhead,tripped=trippedCount]"
+ */
+ @Override
+ public String toString() {
+ return "["
+ + this.name
+ + ",limit="
+ + this.limit
+ + "/"
+ + new ByteSizeValue(this.limit)
+ + ",estimated="
+ + this.estimated
+ + "/"
+ + new ByteSizeValue(this.estimated)
+ + ",overhead="
+ + this.overhead
+ + ",tripped="
+ + this.trippedCount
+ + "]";
+ }
+
+ /**
+ * Fields used for statistics
+ *
+ * @opensearch.internal
+ */
+ static final class Fields {
+ static final String LIMIT = "limit_size_in_bytes";
+ static final String LIMIT_HUMAN = "limit_size";
+ static final String ESTIMATED = "estimated_size_in_bytes";
+ static final String ESTIMATED_HUMAN = "estimated_size";
+ static final String OVERHEAD = "overhead";
+ static final String TRIPPED_COUNT = "tripped";
+ }
+}
diff --git a/libs/core/src/main/java/org/opensearch/core/indices/breaker/NoneCircuitBreakerService.java b/libs/core/src/main/java/org/opensearch/core/indices/breaker/NoneCircuitBreakerService.java
new file mode 100644
index 0000000000000..49c5a393328b9
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/indices/breaker/NoneCircuitBreakerService.java
@@ -0,0 +1,79 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+package org.opensearch.core.indices.breaker;
+
+import org.opensearch.core.common.breaker.CircuitBreaker;
+import org.opensearch.core.common.breaker.NoopCircuitBreaker;
+
+/**
+ * Class that returns a breaker that use the NoopCircuitBreaker and never breaks
+ *
+ * @see org.opensearch.core.common.breaker.NoopCircuitBreaker
+ * @opensearch.internal
+ */
+public class NoneCircuitBreakerService extends CircuitBreakerService {
+
+ private final CircuitBreaker breaker = new NoopCircuitBreaker(CircuitBreaker.FIELDDATA);
+
+ public NoneCircuitBreakerService() {
+ super();
+ }
+
+ /**
+ * Returns a breaker that use the NoopCircuitBreaker and never breaks
+ *
+ * @param name name of the breaker (ignored)
+ * @return a NoopCircuitBreaker
+ */
+ @Override
+ public CircuitBreaker getBreaker(String name) {
+ return breaker;
+ }
+
+ @Override
+ public AllCircuitBreakerStats stats() {
+ return new AllCircuitBreakerStats(new CircuitBreakerStats[] { stats(CircuitBreaker.FIELDDATA) });
+ }
+
+ /**
+ * Always returns the same stats, a NoopCircuitBreaker never breaks and all operations are noops.
+ *
+ * @param name name of the breaker (ignored)
+ * @return always "fielddata", limit: -1, estimated: -1, overhead: 0, trippedCount: 0
+ */
+ @Override
+ public CircuitBreakerStats stats(String name) {
+ return new CircuitBreakerStats(CircuitBreaker.FIELDDATA, -1, -1, 0, 0);
+ }
+
+}
diff --git a/libs/core/src/main/java/org/opensearch/core/indices/breaker/package-info.java b/libs/core/src/main/java/org/opensearch/core/indices/breaker/package-info.java
new file mode 100644
index 0000000000000..a98f9ab1d9f1e
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/indices/breaker/package-info.java
@@ -0,0 +1,15 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Top Level core circuit breaker implementation
+ *
+ * @opensearch.internal
+ * @opensearch.experimental
+ */
+package org.opensearch.core.indices.breaker;
diff --git a/libs/core/src/main/java/org/opensearch/core/indices/package-info.java b/libs/core/src/main/java/org/opensearch/core/indices/package-info.java
new file mode 100644
index 0000000000000..c80edf3d2f01a
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/indices/package-info.java
@@ -0,0 +1,12 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/**
+ * Top Level Package for implementations used across indexes
+ */
+package org.opensearch.core.indices;
diff --git a/libs/core/src/main/java/org/opensearch/core/rest/RestStatus.java b/libs/core/src/main/java/org/opensearch/core/rest/RestStatus.java
index ae4f4c65b28d2..8441ce8b1b622 100644
--- a/libs/core/src/main/java/org/opensearch/core/rest/RestStatus.java
+++ b/libs/core/src/main/java/org/opensearch/core/rest/RestStatus.java
@@ -32,6 +32,7 @@
package org.opensearch.core.rest;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.action.ShardOperationFailedException;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
@@ -47,6 +48,7 @@
*
* @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public enum RestStatus {
/**
* The client SHOULD continue with its request. This interim response is used to inform the client that the
@@ -525,6 +527,15 @@ public int getStatus() {
return status;
}
+ /**
+ * Get category class of a rest status code.
+ *
+ * @return Integer representing class category of the concrete rest status code
+ */
+ public int getStatusFamilyCode() {
+ return status / 100;
+ }
+
public static RestStatus readFrom(StreamInput in) throws IOException {
return RestStatus.valueOf(in.readString());
}
diff --git a/server/src/main/java/org/opensearch/node/ReportingService.java b/libs/core/src/main/java/org/opensearch/core/service/ReportingService.java
similarity index 97%
rename from server/src/main/java/org/opensearch/node/ReportingService.java
rename to libs/core/src/main/java/org/opensearch/core/service/ReportingService.java
index 969652e215e5e..3c88169f1e3b0 100644
--- a/server/src/main/java/org/opensearch/node/ReportingService.java
+++ b/libs/core/src/main/java/org/opensearch/core/service/ReportingService.java
@@ -30,7 +30,7 @@
* GitHub history for details.
*/
-package org.opensearch.node;
+package org.opensearch.core.service;
import org.opensearch.core.common.io.stream.Writeable;
import org.opensearch.core.xcontent.ToXContent;
diff --git a/libs/core/src/main/java/org/opensearch/core/service/package-info.java b/libs/core/src/main/java/org/opensearch/core/service/package-info.java
new file mode 100644
index 0000000000000..d427c6e5934c9
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/service/package-info.java
@@ -0,0 +1,10 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/** OpenSearch Core Service Interfaces */
+package org.opensearch.core.service;
diff --git a/server/src/main/java/org/opensearch/tasks/TaskCancelledException.java b/libs/core/src/main/java/org/opensearch/core/tasks/TaskCancelledException.java
similarity index 97%
rename from server/src/main/java/org/opensearch/tasks/TaskCancelledException.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/TaskCancelledException.java
index 38e50f56b24b2..6bdc1e42f351a 100644
--- a/server/src/main/java/org/opensearch/tasks/TaskCancelledException.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/TaskCancelledException.java
@@ -29,7 +29,7 @@
* GitHub history for details.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks;
import org.opensearch.OpenSearchException;
import org.opensearch.core.common.io.stream.StreamInput;
diff --git a/server/src/main/java/org/opensearch/tasks/TaskId.java b/libs/core/src/main/java/org/opensearch/core/tasks/TaskId.java
similarity index 95%
rename from server/src/main/java/org/opensearch/tasks/TaskId.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/TaskId.java
index e7420fce397e2..d34d4acf00e6e 100644
--- a/server/src/main/java/org/opensearch/tasks/TaskId.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/TaskId.java
@@ -30,10 +30,11 @@
* GitHub history for details.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks;
import org.opensearch.OpenSearchParseException;
-import org.opensearch.common.Strings;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
@@ -45,8 +46,9 @@
/**
* Task id that consists of node id and id of the task on the node
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public final class TaskId implements Writeable {
public static final TaskId EMPTY_TASK_ID = new TaskId();
@@ -71,7 +73,7 @@ private TaskId() {
}
public TaskId(String taskId) {
- if (org.opensearch.core.common.Strings.hasLength(taskId) && "unset".equals(taskId) == false) {
+ if (Strings.hasLength(taskId) && "unset".equals(taskId) == false) {
String[] s = Strings.split(taskId, ":");
if (s == null || s.length != 2) {
throw new IllegalArgumentException("malformed task id " + taskId);
diff --git a/libs/core/src/main/java/org/opensearch/core/tasks/package-info.java b/libs/core/src/main/java/org/opensearch/core/tasks/package-info.java
new file mode 100644
index 0000000000000..e421816c6b541
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/package-info.java
@@ -0,0 +1,10 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/** Core Tasks Foundation classes used across the opensearch code base */
+package org.opensearch.core.tasks;
diff --git a/server/src/main/java/org/opensearch/tasks/ResourceStats.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceStats.java
similarity index 78%
rename from server/src/main/java/org/opensearch/tasks/ResourceStats.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceStats.java
index 31c129b7b2ff9..e99afbb759031 100644
--- a/server/src/main/java/org/opensearch/tasks/ResourceStats.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceStats.java
@@ -6,13 +6,16 @@
* compatible open source license.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks.resourcetracker;
+
+import org.opensearch.common.annotation.PublicApi;
/**
* Different resource stats are defined.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "2.1.0")
public enum ResourceStats {
CPU("cpu_time_in_nanos"),
MEMORY("memory_in_bytes");
diff --git a/server/src/main/java/org/opensearch/tasks/ResourceStatsType.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceStatsType.java
similarity index 84%
rename from server/src/main/java/org/opensearch/tasks/ResourceStatsType.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceStatsType.java
index 138c74e128d70..2aedff2940d83 100644
--- a/server/src/main/java/org/opensearch/tasks/ResourceStatsType.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceStatsType.java
@@ -6,13 +6,16 @@
* compatible open source license.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks.resourcetracker;
+
+import org.opensearch.common.annotation.PublicApi;
/**
* Defines the different types of resource stats.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "2.1.0")
public enum ResourceStatsType {
// resource stats of the worker thread reported directly from runnable.
WORKER_STATS("worker_stats", false);
diff --git a/server/src/main/java/org/opensearch/tasks/ResourceUsageInfo.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageInfo.java
similarity index 95%
rename from server/src/main/java/org/opensearch/tasks/ResourceUsageInfo.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageInfo.java
index 652562e3f9e7a..a278b61894a65 100644
--- a/server/src/main/java/org/opensearch/tasks/ResourceUsageInfo.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageInfo.java
@@ -6,10 +6,11 @@
* compatible open source license.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks.resourcetracker;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
+import org.opensearch.common.annotation.PublicApi;
import java.util.Collections;
import java.util.EnumMap;
@@ -22,8 +23,9 @@
* It captures the resource usage information like memory, CPU about a particular execution of thread
* for a specific stats type.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "2.1.0")
public class ResourceUsageInfo {
private static final Logger logger = LogManager.getLogger(ResourceUsageInfo.class);
private final EnumMap statsInfo = new EnumMap<>(ResourceStats.class);
@@ -89,7 +91,7 @@ public String toString() {
/**
* Defines resource stats information.
*/
- static class ResourceStatsInfo {
+ public static class ResourceStatsInfo {
private final long startValue;
private final AtomicLong endValue;
diff --git a/server/src/main/java/org/opensearch/tasks/ResourceUsageMetric.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageMetric.java
similarity index 80%
rename from server/src/main/java/org/opensearch/tasks/ResourceUsageMetric.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageMetric.java
index 931e3aa00d736..f4cce2de820a0 100644
--- a/server/src/main/java/org/opensearch/tasks/ResourceUsageMetric.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ResourceUsageMetric.java
@@ -6,13 +6,16 @@
* compatible open source license.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks.resourcetracker;
+
+import org.opensearch.common.annotation.PublicApi;
/**
* Information about resource usage
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "2.1.0")
public class ResourceUsageMetric {
private final ResourceStats stats;
private final long value;
diff --git a/server/src/main/java/org/opensearch/tasks/TaskResourceStats.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/TaskResourceStats.java
similarity index 92%
rename from server/src/main/java/org/opensearch/tasks/TaskResourceStats.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/TaskResourceStats.java
index 59526cd229001..048c4a228fbd5 100644
--- a/server/src/main/java/org/opensearch/tasks/TaskResourceStats.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/TaskResourceStats.java
@@ -6,14 +6,15 @@
* compatible open source license.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks.resourcetracker;
import org.opensearch.Version;
-import org.opensearch.common.Strings;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.common.xcontent.XContentType;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
@@ -23,20 +24,21 @@
import java.util.Map;
import java.util.Objects;
-import static org.opensearch.tasks.Task.THREAD_INFO;
-
/**
* Resource information about a currently running task.
*
* Writeable TaskResourceStats objects are used to represent resource
* snapshot information about currently running task.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "2.1.0")
public class TaskResourceStats implements Writeable, ToXContentFragment {
private final Map resourceUsage;
private final TaskThreadUsage threadUsage;
+ public static final String THREAD_INFO = "thread_info";
+
public TaskResourceStats(Map resourceUsage, TaskThreadUsage threadUsage) {
this.resourceUsage = Objects.requireNonNull(resourceUsage, "resource usage is required");
this.threadUsage = Objects.requireNonNull(threadUsage, "thread usage is required");
@@ -117,7 +119,7 @@ public static TaskResourceStats fromXContent(XContentParser parser) throws IOExc
@Override
public String toString() {
- return Strings.toString(XContentType.JSON, this, true, true);
+ return Strings.toString(MediaTypeRegistry.JSON, this, true, true);
}
// Implements equals and hashcode for testing
diff --git a/server/src/main/java/org/opensearch/tasks/TaskResourceUsage.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/TaskResourceUsage.java
similarity index 91%
rename from server/src/main/java/org/opensearch/tasks/TaskResourceUsage.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/TaskResourceUsage.java
index 490adc3e7c637..654f1c5695937 100644
--- a/server/src/main/java/org/opensearch/tasks/TaskResourceUsage.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/TaskResourceUsage.java
@@ -6,15 +6,16 @@
* compatible open source license.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks.resourcetracker;
-import org.opensearch.common.Strings;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.ParseField;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.common.xcontent.XContentType;
-import org.opensearch.core.ParseField;
import org.opensearch.core.xcontent.ConstructingObjectParser;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
@@ -30,8 +31,9 @@
* Writeable TaskResourceUsage objects are used to represent resource usage
* information of running tasks.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "2.1.0")
public class TaskResourceUsage implements Writeable, ToXContentFragment {
private static final ParseField CPU_TIME_IN_NANOS = new ParseField("cpu_time_in_nanos");
private static final ParseField MEMORY_IN_BYTES = new ParseField("memory_in_bytes");
@@ -88,7 +90,7 @@ public static TaskResourceUsage fromXContent(XContentParser parser) {
@Override
public String toString() {
- return Strings.toString(XContentType.JSON, this, true, true);
+ return Strings.toString(MediaTypeRegistry.JSON, this, true, true);
}
// Implements equals and hashcode for testing
diff --git a/server/src/main/java/org/opensearch/tasks/TaskThreadUsage.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/TaskThreadUsage.java
similarity index 91%
rename from server/src/main/java/org/opensearch/tasks/TaskThreadUsage.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/TaskThreadUsage.java
index d30a3d723a15a..abe03e3c520e0 100644
--- a/server/src/main/java/org/opensearch/tasks/TaskThreadUsage.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/TaskThreadUsage.java
@@ -6,15 +6,16 @@
* compatible open source license.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks.resourcetracker;
-import org.opensearch.common.Strings;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.ParseField;
+import org.opensearch.core.common.Strings;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.common.xcontent.XContentType;
-import org.opensearch.core.ParseField;
import org.opensearch.core.xcontent.ConstructingObjectParser;
+import org.opensearch.core.xcontent.MediaTypeRegistry;
import org.opensearch.core.xcontent.ToXContentFragment;
import org.opensearch.core.xcontent.XContentBuilder;
import org.opensearch.core.xcontent.XContentParser;
@@ -29,8 +30,9 @@
* Writeable TaskThreadExecutions objects are used to represent thread related resource usage of running tasks.
* asd
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "2.1.0")
public class TaskThreadUsage implements Writeable, ToXContentFragment {
private static final String THREAD_EXECUTIONS = "thread_executions";
@@ -104,6 +106,6 @@ public int hashCode() {
@Override
public String toString() {
- return Strings.toString(XContentType.JSON, this, true, true);
+ return Strings.toString(MediaTypeRegistry.JSON, this, true, true);
}
}
diff --git a/server/src/main/java/org/opensearch/tasks/ThreadResourceInfo.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ThreadResourceInfo.java
similarity index 92%
rename from server/src/main/java/org/opensearch/tasks/ThreadResourceInfo.java
rename to libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ThreadResourceInfo.java
index de49d86d1d5c4..703fdfdf8a784 100644
--- a/server/src/main/java/org/opensearch/tasks/ThreadResourceInfo.java
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/ThreadResourceInfo.java
@@ -6,7 +6,9 @@
* compatible open source license.
*/
-package org.opensearch.tasks;
+package org.opensearch.core.tasks.resourcetracker;
+
+import org.opensearch.common.annotation.PublicApi;
/**
* Resource consumption information about a particular execution of thread.
@@ -14,8 +16,9 @@
* It captures the resource usage information about a particular execution of thread
* for a specific stats type like worker_stats or response_stats etc.,
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "2.1.0")
public class ThreadResourceInfo {
private final long threadId;
private volatile boolean isActive = true;
diff --git a/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/package-info.java b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/package-info.java
new file mode 100644
index 0000000000000..b46b685ffaaf0
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/tasks/resourcetracker/package-info.java
@@ -0,0 +1,9 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+/** Resource tracking classes for tracking task resource consumption (e.g., memory, cpu) */
+package org.opensearch.core.tasks.resourcetracker;
diff --git a/server/src/main/java/org/opensearch/transport/TransportMessage.java b/libs/core/src/main/java/org/opensearch/core/transport/TransportMessage.java
similarity index 94%
rename from server/src/main/java/org/opensearch/transport/TransportMessage.java
rename to libs/core/src/main/java/org/opensearch/core/transport/TransportMessage.java
index 78216047d530e..941babda40aa3 100644
--- a/server/src/main/java/org/opensearch/transport/TransportMessage.java
+++ b/libs/core/src/main/java/org/opensearch/core/transport/TransportMessage.java
@@ -30,11 +30,11 @@
* GitHub history for details.
*/
-package org.opensearch.transport;
+package org.opensearch.core.transport;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.Writeable;
-import org.opensearch.common.transport.TransportAddress;
+import org.opensearch.core.common.transport.TransportAddress;
/**
* Message over the transport interface
diff --git a/server/src/main/java/org/opensearch/transport/TransportResponse.java b/libs/core/src/main/java/org/opensearch/core/transport/TransportResponse.java
similarity index 98%
rename from server/src/main/java/org/opensearch/transport/TransportResponse.java
rename to libs/core/src/main/java/org/opensearch/core/transport/TransportResponse.java
index 73713fa1447a8..038069e93a51b 100644
--- a/server/src/main/java/org/opensearch/transport/TransportResponse.java
+++ b/libs/core/src/main/java/org/opensearch/core/transport/TransportResponse.java
@@ -30,7 +30,7 @@
* GitHub history for details.
*/
-package org.opensearch.transport;
+package org.opensearch.core.transport;
import org.opensearch.core.common.io.stream.StreamInput;
import org.opensearch.core.common.io.stream.StreamOutput;
diff --git a/libs/core/src/main/java/org/opensearch/core/transport/package-info.java b/libs/core/src/main/java/org/opensearch/core/transport/package-info.java
new file mode 100644
index 0000000000000..91db839f40305
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/transport/package-info.java
@@ -0,0 +1,10 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/** Core Transport Layer classes used across the OpenSearch core */
+package org.opensearch.core.transport;
diff --git a/libs/core/src/main/java/org/opensearch/core/util/BytesRefUtils.java b/libs/core/src/main/java/org/opensearch/core/util/BytesRefUtils.java
index 30c9f182fcae6..2aad068534b9d 100644
--- a/libs/core/src/main/java/org/opensearch/core/util/BytesRefUtils.java
+++ b/libs/core/src/main/java/org/opensearch/core/util/BytesRefUtils.java
@@ -32,6 +32,7 @@
package org.opensearch.core.util;
+import org.apache.lucene.util.BitUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefArray;
import org.apache.lucene.util.BytesRefBuilder;
@@ -103,12 +104,12 @@ public static int sortAndDedup(final BytesRefArray bytes, final int[] indices) {
return uniqueCount;
}
+ /**
+ * Decodes a long value written as bytes in big endian order.
+ * @param bytes in big endian order
+ * @return long value
+ */
public static long bytesToLong(BytesRef bytes) {
- int high = (bytes.bytes[bytes.offset + 0] << 24) | ((bytes.bytes[bytes.offset + 1] & 0xff) << 16) | ((bytes.bytes[bytes.offset + 2]
- & 0xff) << 8) | (bytes.bytes[bytes.offset + 3] & 0xff);
- int low = (bytes.bytes[bytes.offset + 4] << 24) | ((bytes.bytes[bytes.offset + 5] & 0xff) << 16) | ((bytes.bytes[bytes.offset + 6]
- & 0xff) << 8) | (bytes.bytes[bytes.offset + 7] & 0xff);
- return (((long) high) << 32) | (low & 0x0ffffffffL);
+ return (long) BitUtil.VH_BE_LONG.get(bytes.bytes, bytes.offset);
}
-
}
diff --git a/libs/core/src/main/java/org/opensearch/core/util/FileSystemUtils.java b/libs/core/src/main/java/org/opensearch/core/util/FileSystemUtils.java
index d742e8584fa8b..99f48ed49dd39 100644
--- a/libs/core/src/main/java/org/opensearch/core/util/FileSystemUtils.java
+++ b/libs/core/src/main/java/org/opensearch/core/util/FileSystemUtils.java
@@ -34,8 +34,8 @@
import org.apache.logging.log4j.Logger;
import org.apache.lucene.util.Constants;
-import org.opensearch.common.util.io.IOUtils;
import org.opensearch.common.SuppressForbidden;
+import org.opensearch.common.util.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/AbstractObjectParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/AbstractObjectParser.java
index a0e2a54fce91c..32bbfc600f1f0 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/AbstractObjectParser.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/AbstractObjectParser.java
@@ -33,6 +33,7 @@
package org.opensearch.core.xcontent;
import org.opensearch.common.CheckedFunction;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.ParseField;
import org.opensearch.core.xcontent.ObjectParser.NamedObjectParser;
import org.opensearch.core.xcontent.ObjectParser.ValueType;
@@ -47,8 +48,9 @@
/**
* Superclass for {@link ObjectParser} and {@link ConstructingObjectParser}. Defines most of the "declare" methods so they can be shared.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public abstract class AbstractObjectParser {
/**
@@ -108,7 +110,7 @@ public abstract void declareNamedObject(
*
* Unlike the other version of this method, "ordered" mode (arrays of
* objects) is not supported.
- *
+ *
* See NamedObjectHolder in ObjectParserTests for examples of how to invoke
* this.
*
@@ -163,7 +165,7 @@ public abstract void declareNamedObjects(
* the order sent but tools that generate json are free to put object
* members in an unordered Map, jumbling them. Thus, if you care about order
* you can send the object in the second way.
- *
+ *
* See NamedObjectHolder in ObjectParserTests for examples of how to invoke
* this.
*
@@ -366,10 +368,10 @@ public void declareFieldArray(
/**
* Declares a set of fields that are required for parsing to succeed. Only one of the values
* provided per String[] must be matched.
- *
+ *
* E.g. declareRequiredFieldSet("foo", "bar");
means at least one of "foo" or
* "bar" fields must be present. If neither of those fields are present, an exception will be thrown.
- *
+ *
* Multiple required sets can be configured:
*
*
@@ -379,7 +381,7 @@ public void declareFieldArray(
*
* requires that one of "foo" or "bar" fields are present, and also that one of "bizz" or
* "buzz" fields are present.
- *
+ *
* In JSON, it means any of these combinations are acceptable:
*
*
@@ -415,12 +417,12 @@ public void declareFieldArray(
/**
* Declares a set of fields of which at most one must appear for parsing to succeed
- *
+ *
* E.g. declareExclusiveFieldSet("foo", "bar");
means that only one of 'foo'
* or 'bar' must be present, and if both appear then an exception will be thrown. Note
* that this does not make 'foo' or 'bar' required - see {@link #declareRequiredFieldSet(String...)}
* for required fields.
- *
+ *
* Multiple exclusive sets may be declared
*
* @param exclusiveSet a set of field names, at most one of which must appear
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/ContextParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/ContextParser.java
index d50dd2e68d890..f6e5647532bee 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/ContextParser.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/ContextParser.java
@@ -32,11 +32,16 @@
package org.opensearch.core.xcontent;
+import org.opensearch.common.annotation.PublicApi;
+
import java.io.IOException;
/**
* Reads an object from a parser using some context.
+ *
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
@FunctionalInterface
public interface ContextParser {
T parse(XContentParser p, Context c) throws IOException;
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/DeprecationHandler.java b/libs/core/src/main/java/org/opensearch/core/xcontent/DeprecationHandler.java
index 570a13ad8e093..a0e4027290742 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/DeprecationHandler.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/DeprecationHandler.java
@@ -32,12 +32,17 @@
package org.opensearch.core.xcontent;
+import org.opensearch.common.annotation.PublicApi;
+
import java.util.function.Supplier;
/**
* Callback for notifying the creator of the {@link XContentParser} that
* parsing hit a deprecated field.
+ *
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface DeprecationHandler {
/**
* Throws an {@link UnsupportedOperationException} when parsing hits a
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java
index 54329038e1fc5..0a5cda324ddb7 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/MapXContentParser.java
@@ -45,7 +45,7 @@
*/
public class MapXContentParser extends AbstractXContentParser {
- private MediaType xContentType;
+ private MediaType mediaType;
private TokenIterator iterator;
private boolean closed;
@@ -53,10 +53,10 @@ public MapXContentParser(
NamedXContentRegistry xContentRegistry,
DeprecationHandler deprecationHandler,
Map map,
- MediaType xContentType
+ MediaType mediaType
) {
super(xContentRegistry, deprecationHandler);
- this.xContentType = xContentType;
+ this.mediaType = mediaType;
this.iterator = new MapIterator(null, null, map);
}
@@ -105,7 +105,7 @@ protected BigInteger doBigIntegerValue() throws IOException {
@Override
public MediaType contentType() {
- return xContentType;
+ return mediaType;
}
@Override
@@ -277,7 +277,7 @@ public Token currentToken() {
/**
* field name that the child element needs to inherit.
- *
+ *
* In most cases this is the same as currentName() except with embedded arrays. In "foo": [[42]] the first START_ARRAY
* token will have the name "foo", but the second START_ARRAY will have no name.
*/
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/MediaType.java b/libs/core/src/main/java/org/opensearch/core/xcontent/MediaType.java
index c1409e551e47d..c58b3e80d98b5 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/MediaType.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/MediaType.java
@@ -32,15 +32,21 @@
package org.opensearch.core.xcontent;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.common.io.stream.Writeable;
+import java.io.IOException;
+import java.io.OutputStream;
import java.util.Locale;
/**
* Abstracts a Media Type and a format parameter.
* Media types are used as values on Content-Type and Accept headers
* format is an URL parameter, specifies response media type.
+ *
+ * @opensearch.api
*/
+@PublicApi(since = "2.1.0")
public interface MediaType extends Writeable {
/**
* Returns a type part of a MediaType
@@ -69,12 +75,20 @@ default String typeWithSubtype() {
XContent xContent();
+ boolean detectedXContent(final byte[] bytes, int offset, int length);
+
+ boolean detectedXContent(final CharSequence content, final int length);
+
default String mediaType() {
return mediaTypeWithoutParameters();
}
String mediaTypeWithoutParameters();
+ XContentBuilder contentBuilder() throws IOException;
+
+ XContentBuilder contentBuilder(final OutputStream os) throws IOException;
+
/**
* Accepts a format string, which is most of the time is equivalent to {@link MediaType#subtype()}
* and attempts to match the value to an {@link MediaType}.
@@ -82,7 +96,7 @@ default String mediaType() {
* This method will return {@code null} if no match is found
*/
static MediaType fromFormat(String mediaType) {
- return MediaTypeParserRegistry.fromFormat(mediaType);
+ return MediaTypeRegistry.fromFormat(mediaType);
}
/**
@@ -93,7 +107,7 @@ static MediaType fromFormat(String mediaType) {
*/
static MediaType fromMediaType(String mediaTypeHeaderValue) {
mediaTypeHeaderValue = removeVersionInMediaType(mediaTypeHeaderValue);
- return MediaTypeParserRegistry.fromMediaType(mediaTypeHeaderValue);
+ return MediaTypeRegistry.fromMediaType(mediaTypeHeaderValue);
}
/**
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeParserRegistry.java b/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeParserRegistry.java
deleted file mode 100644
index 62a26b4458b09..0000000000000
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeParserRegistry.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * SPDX-License-Identifier: Apache-2.0
- *
- * The OpenSearch Contributors require contributions made to
- * this file be licensed under the Apache-2.0 license or a
- * compatible open source license.
- */
-
-/*
- * Licensed to Elasticsearch under one or more contributor
- * license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright
- * ownership. Elasticsearch licenses this file to you under
- * the Apache License, Version 2.0 (the "License"); you may
- * not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-/*
- * Modifications Copyright OpenSearch Contributors. See
- * GitHub history for details.
- */
-
-package org.opensearch.core.xcontent;
-
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * Parses supported internet media types
- *
- * @opensearch.internal
- */
-public final class MediaTypeParserRegistry {
- private static Map formatToMediaType = Map.of();
- private static Map typeWithSubtypeToMediaType = Map.of();
-
- // Default mediaType singleton
- private static MediaType DEFAULT_MEDIA_TYPE;
-
- public static void register(MediaType[] acceptedMediaTypes, Map additionalMediaTypes) {
- // ensures the map is not overwritten:
- Map typeMap = new HashMap<>(typeWithSubtypeToMediaType);
- Map formatMap = new HashMap<>(formatToMediaType);
- for (MediaType mediaType : acceptedMediaTypes) {
- if (formatMap.containsKey(mediaType.format())) {
- throw new IllegalArgumentException("unable to register mediaType: [" + mediaType.format() + "]. Type already exists.");
- }
- typeMap.put(mediaType.typeWithSubtype(), mediaType);
- formatMap.put(mediaType.format(), mediaType);
- }
- for (Map.Entry entry : additionalMediaTypes.entrySet()) {
- String typeWithSubtype = entry.getKey().toLowerCase(Locale.ROOT);
- if (typeMap.containsKey(typeWithSubtype)) {
- throw new IllegalArgumentException(
- "unable to register mediaType: ["
- + entry.getKey()
- + "]. "
- + "Type already exists and is mapped to: [."
- + entry.getValue().format()
- + "]"
- );
- }
-
- MediaType mediaType = entry.getValue();
- typeMap.put(typeWithSubtype, mediaType);
- formatMap.putIfAbsent(mediaType.format(), mediaType); // ignore if the additional type mapping already exists
- }
-
- formatToMediaType = Map.copyOf(formatMap);
- typeWithSubtypeToMediaType = Map.copyOf(typeMap);
- }
-
- public static MediaType fromMediaType(String mediaType) {
- ParsedMediaType parsedMediaType = parseMediaType(mediaType);
- return parsedMediaType != null ? parsedMediaType.getMediaType() : null;
- }
-
- public static MediaType fromFormat(String format) {
- if (format == null) {
- return null;
- }
- return formatToMediaType.get(format.toLowerCase(Locale.ROOT));
- }
-
- /**
- * parsing media type that follows https://tools.ietf.org/html/rfc7231#section-3.1.1.1
- * @param headerValue a header value from Accept or Content-Type
- * @return a parsed media-type
- */
- public static ParsedMediaType parseMediaType(String headerValue) {
- if (headerValue != null) {
- String[] split = headerValue.toLowerCase(Locale.ROOT).split(";");
-
- String[] typeSubtype = split[0].trim().split("/");
- if (typeSubtype.length == 2) {
- String type = typeSubtype[0];
- String subtype = typeSubtype[1];
- MediaType mediaType = typeWithSubtypeToMediaType.get(type + "/" + subtype);
- if (mediaType != null) {
- Map parameters = new HashMap<>();
- for (int i = 1; i < split.length; i++) {
- // spaces are allowed between parameters, but not between '=' sign
- String[] keyValueParam = split[i].trim().split("=");
- if (keyValueParam.length != 2 || hasSpaces(keyValueParam[0]) || hasSpaces(keyValueParam[1])) {
- return null;
- }
- parameters.put(keyValueParam[0], keyValueParam[1]);
- }
- return new ParsedMediaType(mediaType, parameters);
- }
- }
-
- }
- return null;
- }
-
- private static boolean hasSpaces(String s) {
- return s.trim().equals(s) == false;
- }
-
- /**
- * A media type object that contains all the information provided on a Content-Type or Accept header
- */
- public static class ParsedMediaType {
- private final Map parameters;
- private final MediaType mediaType;
-
- public ParsedMediaType(MediaType mediaType, Map parameters) {
- this.parameters = parameters;
- this.mediaType = mediaType;
- }
-
- public MediaType getMediaType() {
- return mediaType;
- }
-
- public Map getParameters() {
- return parameters;
- }
- }
-
- public static void setDefaultMediaType(final MediaType mediaType) {
- if (DEFAULT_MEDIA_TYPE != null) {
- throw new RuntimeException(
- "unable to reset the default media type from current default [" + DEFAULT_MEDIA_TYPE + "] to [" + mediaType + "]"
- );
- } else {
- DEFAULT_MEDIA_TYPE = mediaType;
- }
- }
-
- public static MediaType getDefaultMediaType() {
- return DEFAULT_MEDIA_TYPE;
- }
-}
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeRegistry.java b/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeRegistry.java
new file mode 100644
index 0000000000000..bbb55204712d1
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/MediaTypeRegistry.java
@@ -0,0 +1,405 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+/*
+ * Licensed to Elasticsearch under one or more contributor
+ * license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright
+ * ownership. Elasticsearch licenses this file to you under
+ * the Apache License, Version 2.0 (the "License"); you may
+ * not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Modifications Copyright OpenSearch Contributors. See
+ * GitHub history for details.
+ */
+
+package org.opensearch.core.xcontent;
+
+import org.opensearch.core.common.bytes.BytesArray;
+import org.opensearch.core.common.bytes.BytesReference;
+import org.opensearch.core.xcontent.spi.MediaTypeProvider;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.UncheckedIOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.ServiceLoader;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * Parses supported internet media types
+ *
+ * @opensearch.internal
+ */
+public final class MediaTypeRegistry {
+ private static Map formatToMediaType = Map.of();
+ private static Map typeWithSubtypeToMediaType = Map.of();
+
+ // Default mediaType singleton
+ private static MediaType DEFAULT_MEDIA_TYPE;
+ public static final int GUESS_HEADER_LENGTH = 20;
+
+ // JSON is a core type, so we create a static instance for implementations that require JSON format (e.g., tests)
+ // todo we should explore moving the concrete JSON implementation from the xcontent library to core
+ public static final MediaType JSON;
+
+ static {
+ List mediaTypes = new ArrayList<>();
+ Map amt = new HashMap<>();
+ for (MediaTypeProvider provider : ServiceLoader.load(MediaTypeProvider.class, MediaTypeProvider.class.getClassLoader())) {
+ mediaTypes.addAll(provider.getMediaTypes());
+ amt = Stream.of(amt, provider.getAdditionalMediaTypes())
+ .flatMap(map -> map.entrySet().stream())
+ .collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+ register(mediaTypes.toArray(new MediaType[0]), amt);
+ JSON = fromMediaType("application/json");
+ setDefaultMediaType(JSON);
+ }
+
+ private static void register(MediaType[] acceptedMediaTypes, Map additionalMediaTypes) {
+ // ensures the map is not overwritten:
+ Map typeMap = new HashMap<>(typeWithSubtypeToMediaType);
+ Map formatMap = new HashMap<>(formatToMediaType);
+ for (MediaType mediaType : acceptedMediaTypes) {
+ if (formatMap.containsKey(mediaType.format())) {
+ throw new IllegalArgumentException("unable to register mediaType: [" + mediaType.format() + "]. Type already exists.");
+ }
+ typeMap.put(mediaType.typeWithSubtype(), mediaType);
+ formatMap.put(mediaType.format(), mediaType);
+ }
+ for (Map.Entry entry : additionalMediaTypes.entrySet()) {
+ String typeWithSubtype = entry.getKey().toLowerCase(Locale.ROOT);
+ if (typeMap.containsKey(typeWithSubtype)) {
+ throw new IllegalArgumentException(
+ "unable to register mediaType: ["
+ + entry.getKey()
+ + "]. "
+ + "Type already exists and is mapped to: [."
+ + entry.getValue().format()
+ + "]"
+ );
+ }
+
+ MediaType mediaType = entry.getValue();
+ typeMap.put(typeWithSubtype, mediaType);
+ formatMap.putIfAbsent(mediaType.format(), mediaType); // ignore if the additional type mapping already exists
+ }
+
+ formatToMediaType = Map.copyOf(formatMap);
+ typeWithSubtypeToMediaType = Map.copyOf(typeMap);
+ }
+
+ public static MediaType fromMediaType(String mediaType) {
+ ParsedMediaType parsedMediaType = parseMediaType(mediaType);
+ return parsedMediaType != null ? parsedMediaType.getMediaType() : null;
+ }
+
+ public static MediaType fromFormat(String format) {
+ if (format == null) {
+ return null;
+ }
+ return formatToMediaType.get(format.toLowerCase(Locale.ROOT));
+ }
+
+ /**
+ * Returns a binary content builder for the provided content type.
+ */
+ public static XContentBuilder contentBuilder(MediaType type) throws IOException {
+ for (var mediaType : formatToMediaType.values()) {
+ if (type == mediaType) {
+ return type.contentBuilder();
+ }
+ }
+ throw new IllegalArgumentException("No matching content type for " + type);
+ }
+
+ public static XContentBuilder contentBuilder(MediaType type, OutputStream outputStream) throws IOException {
+ for (var mediaType : formatToMediaType.values()) {
+ if (type == mediaType) {
+ return type.contentBuilder(outputStream);
+ }
+ }
+ throw new IllegalArgumentException("No matching content type for " + type);
+ }
+
+ /**
+ * Guesses the content (type) based on the provided char sequence and returns the corresponding {@link XContent}
+ *
+ * @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
+ * The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
+ * This method is deprecated to prevent usages of it from spreading further without specific reasons.
+ */
+ @Deprecated
+ public static MediaType xContent(final byte[] data, int offset, int length) {
+ MediaType type = mediaTypeFromBytes(data, offset, length);
+ if (type == null) {
+ throw new XContentParseException("Failed to derive xcontent");
+ }
+ return type;
+ }
+
+ /**
+ * Guesses the content type based on the provided bytes and returns the corresponding {@link XContent}
+ *
+ * @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
+ * The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
+ * This method is deprecated to prevent usages of it from spreading further without specific reasons.
+ */
+ @Deprecated
+ public static MediaType xContent(byte[] data) {
+ return xContent(data, 0, data.length);
+ }
+
+ /**
+ * Guesses the content (type) based on the provided char sequence and returns the corresponding {@link XContent}
+ *
+ * @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
+ * The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
+ * This method is deprecated to prevent usages of it from spreading further without specific reasons.
+ */
+ @Deprecated
+ public static MediaType xContent(CharSequence content) {
+ MediaType type = xContentType(content);
+ if (type == null) {
+ throw new XContentParseException("Failed to derive xcontent");
+ }
+ return type;
+ }
+
+ /**
+ * Guesses the content type based on the provided char sequence.
+ *
+ * @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
+ * The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
+ * This method is deprecated to prevent usages of it from spreading further without specific reasons.
+ */
+ @Deprecated
+ public static MediaType xContentType(CharSequence content) {
+ int length = content.length() < GUESS_HEADER_LENGTH ? content.length() : GUESS_HEADER_LENGTH;
+ if (length == 0) {
+ return null;
+ }
+ for (var mediaType : formatToMediaType.values()) {
+ if (mediaType.detectedXContent(content, length)) {
+ return mediaType;
+ }
+ }
+
+ // fallback for json
+ for (int i = 0; i < length; i++) {
+ char c = content.charAt(i);
+ if (c == '{') {
+ return MediaType.fromMediaType("application/json");
+ }
+ if (Character.isWhitespace(c) == false) {
+ break;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Guesses the content type based on the provided input stream without consuming it.
+ *
+ * @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
+ * The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
+ * This method is deprecated to prevent usages of it from spreading further without specific reasons.
+ */
+ @Deprecated
+ public static MediaType xContentType(InputStream si) throws IOException {
+ /*
+ * We need to guess the content type. To do this, we look for the first non-whitespace character and then try to guess the content
+ * type on the GUESS_HEADER_LENGTH bytes that follow. We do this in a way that does not modify the initial read position in the
+ * underlying input stream. This is why the input stream must support mark/reset and why we repeatedly mark the read position and
+ * reset.
+ */
+ if (si.markSupported() == false) {
+ throw new IllegalArgumentException("Cannot guess the xcontent type without mark/reset support on " + si.getClass());
+ }
+ si.mark(Integer.MAX_VALUE);
+ try {
+ // scan until we find the first non-whitespace character or the end of the stream
+ int current;
+ do {
+ current = si.read();
+ if (current == -1) {
+ return null;
+ }
+ } while (Character.isWhitespace((char) current));
+ // now guess the content type off the next GUESS_HEADER_LENGTH bytes including the current byte
+ final byte[] firstBytes = new byte[GUESS_HEADER_LENGTH];
+ firstBytes[0] = (byte) current;
+ int read = 1;
+ while (read < GUESS_HEADER_LENGTH) {
+ final int r = si.read(firstBytes, read, GUESS_HEADER_LENGTH - read);
+ if (r == -1) {
+ break;
+ }
+ read += r;
+ }
+ return mediaTypeFromBytes(firstBytes, 0, read);
+ } finally {
+ si.reset();
+ }
+
+ }
+
+ /**
+ * Guesses the content type based on the provided bytes.
+ *
+ * @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
+ * The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
+ * This method is deprecated to prevent usages of it from spreading further without specific reasons.
+ */
+ @Deprecated
+ public static MediaType xContentType(BytesReference bytes) {
+ if (bytes instanceof BytesArray) {
+ final BytesArray array = (BytesArray) bytes;
+ return mediaTypeFromBytes(array.array(), array.offset(), array.length());
+ }
+ try {
+ final InputStream inputStream = bytes.streamInput();
+ assert inputStream.markSupported();
+ return xContentType(inputStream);
+ } catch (IOException e) {
+ assert false : "Should not happen, we're just reading bytes from memory";
+ throw new UncheckedIOException(e);
+ }
+ }
+
+ /**
+ * Guesses the content type based on the provided bytes.
+ *
+ * @deprecated the content type should not be guessed except for few cases where we effectively don't know the content type.
+ * The REST layer should move to reading the Content-Type header instead. There are other places where auto-detection may be needed.
+ * This method is deprecated to prevent usages of it from spreading further without specific reasons.
+ */
+ @Deprecated
+ public static MediaType mediaTypeFromBytes(final byte[] data, int offset, int length) {
+ int totalLength = data.length;
+ if (totalLength == 0 || length == 0) {
+ return null;
+ } else if ((offset + length) > totalLength) {
+ return null;
+ }
+ for (var mediaType : formatToMediaType.values()) {
+ if (mediaType.detectedXContent(data, offset, length)) {
+ return mediaType;
+ }
+ }
+
+ // a last chance for JSON
+ int jsonStart = 0;
+ // JSON may be preceded by UTF-8 BOM
+ if (length > 3 && data[offset] == (byte) 0xEF && data[offset + 1] == (byte) 0xBB && data[offset + 2] == (byte) 0xBF) {
+ jsonStart = 3;
+ }
+
+ for (int i = jsonStart; i < length; i++) {
+ byte b = data[offset + i];
+ if (b == '{') {
+ return fromMediaType("application/json");
+ }
+ if (Character.isWhitespace(b) == false) {
+ break;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * parsing media type that follows https://tools.ietf.org/html/rfc7231#section-3.1.1.1
+ * @param headerValue a header value from Accept or Content-Type
+ * @return a parsed media-type
+ */
+ public static ParsedMediaType parseMediaType(String headerValue) {
+ if (headerValue != null) {
+ String[] split = headerValue.toLowerCase(Locale.ROOT).split(";");
+
+ String[] typeSubtype = split[0].trim().split("/");
+ if (typeSubtype.length == 2) {
+ String type = typeSubtype[0];
+ String subtype = typeSubtype[1];
+ MediaType mediaType = typeWithSubtypeToMediaType.get(type + "/" + subtype);
+ if (mediaType != null) {
+ Map parameters = new HashMap<>();
+ for (int i = 1; i < split.length; i++) {
+ // spaces are allowed between parameters, but not between '=' sign
+ String[] keyValueParam = split[i].trim().split("=");
+ if (keyValueParam.length != 2 || hasSpaces(keyValueParam[0]) || hasSpaces(keyValueParam[1])) {
+ return null;
+ }
+ parameters.put(keyValueParam[0], keyValueParam[1]);
+ }
+ return new ParsedMediaType(mediaType, parameters);
+ }
+ }
+
+ }
+ return null;
+ }
+
+ private static boolean hasSpaces(String s) {
+ return s.trim().equals(s) == false;
+ }
+
+ /**
+ * A media type object that contains all the information provided on a Content-Type or Accept header
+ */
+ public static class ParsedMediaType {
+ private final Map parameters;
+ private final MediaType mediaType;
+
+ public ParsedMediaType(MediaType mediaType, Map parameters) {
+ this.parameters = parameters;
+ this.mediaType = mediaType;
+ }
+
+ public MediaType getMediaType() {
+ return mediaType;
+ }
+
+ public Map getParameters() {
+ return parameters;
+ }
+ }
+
+ private static void setDefaultMediaType(final MediaType mediaType) {
+ if (DEFAULT_MEDIA_TYPE != null) {
+ throw new RuntimeException(
+ "unable to reset the default media type from current default [" + DEFAULT_MEDIA_TYPE + "] to [" + mediaType + "]"
+ );
+ } else {
+ DEFAULT_MEDIA_TYPE = mediaType;
+ }
+ }
+
+ public static MediaType getDefaultMediaType() {
+ return DEFAULT_MEDIA_TYPE;
+ }
+}
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/NamedXContentRegistry.java b/libs/core/src/main/java/org/opensearch/core/xcontent/NamedXContentRegistry.java
index 10718ba98fe17..9d876825c5196 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/NamedXContentRegistry.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/NamedXContentRegistry.java
@@ -33,6 +33,7 @@
package org.opensearch.core.xcontent;
import org.opensearch.common.CheckedFunction;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.ParseField;
import java.io.IOException;
@@ -49,8 +50,9 @@
/**
* Main registry for serializable content (e.g., field mappers, aggregations)
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public class NamedXContentRegistry {
/**
* The empty {@link NamedXContentRegistry} for use when you are sure that you aren't going to call
@@ -64,6 +66,7 @@ public class NamedXContentRegistry {
/**
* An entry in the {@linkplain NamedXContentRegistry} containing the name of the object and the parser that can parse it.
*/
+ @PublicApi(since = "1.0.0")
public static class Entry {
/** The class that this entry can read. */
public final Class> categoryClass;
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParser.java
index 365b36c755dd2..04d0bce27c04f 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParser.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParser.java
@@ -32,6 +32,7 @@
package org.opensearch.core.xcontent;
import org.opensearch.common.Nullable;
+import org.opensearch.common.annotation.PublicApi;
import org.opensearch.core.ParseField;
import java.io.IOException;
@@ -83,8 +84,9 @@
* It's highly recommended to use the high level declare methods like {@link #declareString(BiConsumer, ParseField)} instead of
* {@link #declareField} which can be used to implement exceptional parsing operations not covered by the high level methods.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public final class ObjectParser extends AbstractObjectParser
implements
BiFunction,
diff --git a/server/src/main/java/org/opensearch/common/xcontent/ObjectParserHelper.java b/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParserHelper.java
similarity index 84%
rename from server/src/main/java/org/opensearch/common/xcontent/ObjectParserHelper.java
rename to libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParserHelper.java
index 77c13dc5de60e..b29ca9dea56c0 100644
--- a/server/src/main/java/org/opensearch/common/xcontent/ObjectParserHelper.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/ObjectParserHelper.java
@@ -30,17 +30,12 @@
* GitHub history for details.
*/
-package org.opensearch.common.xcontent;
+package org.opensearch.core.xcontent;
import org.opensearch.common.CheckedFunction;
import org.opensearch.core.ParseField;
import org.opensearch.core.common.bytes.BytesReference;
-import org.opensearch.core.xcontent.AbstractObjectParser;
-import org.opensearch.core.xcontent.ObjectParser;
import org.opensearch.core.xcontent.ObjectParser.ValueType;
-import org.opensearch.common.xcontent.json.JsonXContent;
-import org.opensearch.core.xcontent.XContentBuilder;
-import org.opensearch.core.xcontent.XContentParser;
import java.io.IOException;
import java.util.function.BiConsumer;
@@ -62,7 +57,7 @@ public void declareRawObject(
final ParseField field
) {
final CheckedFunction bytesParser = p -> {
- try (XContentBuilder builder = JsonXContent.contentBuilder()) {
+ try (XContentBuilder builder = MediaTypeRegistry.JSON.contentBuilder()) {
builder.copyCurrentStructure(p);
return BytesReference.bytes(builder);
}
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/ToXContent.java b/libs/core/src/main/java/org/opensearch/core/xcontent/ToXContent.java
index 90dd0cbfb9a1a..ee8dad198df09 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/ToXContent.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/ToXContent.java
@@ -33,6 +33,7 @@
package org.opensearch.core.xcontent;
import org.opensearch.common.Booleans;
+import org.opensearch.common.annotation.PublicApi;
import java.io.IOException;
import java.util.Map;
@@ -42,15 +43,17 @@
* The output may or may not be a value object. Objects implementing {@link ToXContentObject} output a valid value
* but those that don't may or may not require emitting a startObject and an endObject.
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface ToXContent {
/**
* Base parameters class
*
- * @opensearch.internal
+ * @opensearch.api
*/
+ @PublicApi(since = "1.0.0")
interface Params {
String param(String key);
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContent.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContent.java
index dbc0041af42b5..1ebdd69d2b7a3 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/XContent.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContent.java
@@ -32,6 +32,8 @@
package org.opensearch.core.xcontent;
+import org.opensearch.common.annotation.PublicApi;
+
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -41,7 +43,10 @@
/**
* A generic abstraction on top of handling content, inspired by JSON and pull parsing.
+ *
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface XContent {
/**
* The type this content handles and produces.
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilder.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilder.java
index 061837d27ed0a..976f353100c55 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilder.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilder.java
@@ -32,6 +32,9 @@
package org.opensearch.core.xcontent;
+import org.opensearch.common.annotation.PublicApi;
+import org.opensearch.core.common.bytes.BytesReference;
+
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.Flushable;
@@ -59,6 +62,7 @@
/**
* A utility to build XContent (ie json).
*/
+@PublicApi(since = "1.0.0")
public final class XContentBuilder implements Closeable, Flushable {
/**
@@ -151,6 +155,14 @@ public static XContentBuilder builder(XContent xContent, Set includes, S
DATE_TRANSFORMERS = Collections.unmodifiableMap(dateTransformers);
}
+ /**
+ * Returns a string representation of the builder (only applicable for text based xcontent).
+ */
+ @Override
+ public String toString() {
+ return BytesReference.bytes(this).utf8ToString();
+ }
+
/**
* The writer interface for the serializable content builder
*
@@ -714,7 +726,7 @@ public XContentBuilder value(byte[] value, int offset, int length) throws IOExce
/**
* Writes the binary content of the given byte array as UTF-8 bytes.
- *
+ *
* Use {@link XContentParser#charBuffer()} to read the value back
*/
public XContentBuilder utf8Value(byte[] bytes, int offset, int length) throws IOException {
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilderExtension.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilderExtension.java
index 0535da1a584be..9b13ebb23be86 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilderExtension.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentBuilderExtension.java
@@ -37,7 +37,7 @@
/**
* This interface provides a way for non-JDK classes to plug in a way to serialize to xcontent.
- *
+ *
* It is greatly preferred that you implement {@link ToXContentFragment}
* in the class for encoding, however, in some situations you may not own the
* class, in which case you can add an implementation here for encoding it.
@@ -63,7 +63,7 @@ public interface XContentBuilderExtension {
* Used for plugging in a human readable version of a class's encoding. It is assumed that
* the human readable equivalent is always behind the {@code toString()} method, so
* this transformer returns the raw value to be used.
- *
+ *
* An example implementation:
*
*
@@ -79,7 +79,7 @@ public interface XContentBuilderExtension {
/**
* Used for plugging a transformer for a date or time type object into a String (or other
* encodable object).
- *
+ *
* For example:
*
*
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentHelper.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentHelper.java
new file mode 100644
index 0000000000000..a99a12273a6f0
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentHelper.java
@@ -0,0 +1,53 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.core.xcontent;
+
+import org.opensearch.core.common.bytes.BytesReference;
+
+import java.io.IOException;
+
+/**
+ * Core XContent Helper Utilities
+ *
+ * @opensearch.internal
+ */
+public final class XContentHelper {
+ // no instance
+ private XContentHelper() {}
+
+ /**
+ * Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided
+ * {@link MediaType}. Wraps the output into a new anonymous object according to the value returned
+ * by the {@link ToXContent#isFragment()} method returns.
+ */
+ @Deprecated
+ public static BytesReference toXContent(ToXContent toXContent, MediaType mediaType, boolean humanReadable) throws IOException {
+ return toXContent(toXContent, mediaType, ToXContent.EMPTY_PARAMS, humanReadable);
+ }
+
+ /**
+ * Returns the bytes that represent the XContent output of the provided {@link ToXContent} object, using the provided
+ * {@link MediaType}. Wraps the output into a new anonymous object according to the value returned
+ * by the {@link ToXContent#isFragment()} method returns.
+ */
+ public static BytesReference toXContent(ToXContent toXContent, MediaType mediaType, ToXContent.Params params, boolean humanReadable)
+ throws IOException {
+ try (XContentBuilder builder = XContentBuilder.builder(mediaType.xContent())) {
+ builder.humanReadable(humanReadable);
+ if (toXContent.isFragment()) {
+ builder.startObject();
+ }
+ toXContent.toXContent(builder, params);
+ if (toXContent.isFragment()) {
+ builder.endObject();
+ }
+ return BytesReference.bytes(builder);
+ }
+ }
+}
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParser.java
index 328eaa4bc36e9..85c3579b74cd5 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParser.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParser.java
@@ -33,6 +33,7 @@
package org.opensearch.core.xcontent;
import org.opensearch.common.CheckedFunction;
+import org.opensearch.common.annotation.PublicApi;
import java.io.Closeable;
import java.io.IOException;
@@ -44,17 +45,18 @@
/**
* Interface for pull - parsing {@link XContent} see {@code XContentType} for supported types.
- *
+ *
* To obtain an instance of this class use the following pattern:
*
*
- * XContentType xContentType = XContentType.JSON;
- * XContentParser parser = xContentType.xContent().createParser(
+ * MediaType mediaType = MediaTypeRegistry.JSON;
+ * XContentParser parser = mediaType.xContent().createParser(
* NamedXContentRegistry.EMPTY, ParserField."{\"key\" : \"value\"}");
*
*
- * @opensearch.internal
+ * @opensearch.api
*/
+@PublicApi(since = "1.0.0")
public interface XContentParser extends Closeable {
/**
@@ -202,11 +204,11 @@ Map map(Supplier> mapFactory, CheckedFunction
* Default implementation simply returns false since only actual
* implementation class has knowledge of its internal buffering
* state.
- *
+ *
* This method shouldn't be used to check if the token contains text or not.
*/
boolean hasTextCharacters();
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParserUtils.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParserUtils.java
index fff3d5f83f82e..b10be393f9adb 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParserUtils.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentParserUtils.java
@@ -33,8 +33,8 @@
package org.opensearch.core.xcontent;
import org.opensearch.core.common.ParsingException;
-import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.common.Strings;
+import org.opensearch.core.common.bytes.BytesArray;
import org.opensearch.core.xcontent.XContentParser.Token;
import java.io.IOException;
@@ -142,10 +142,10 @@ public static Object parseFieldsValue(XContentParser parser) throws IOException
* This method expects that the current field name is the concatenation of a type, a delimiter and a name
* (ex: terms#foo where "terms" refers to the type of a registered {@link NamedXContentRegistry.Entry},
* "#" is the delimiter and "foo" the name of the object to parse).
- *
+ *
* It also expected that following this field name is either an Object or an array xContent structure and
* the cursor points to the start token of this structure.
- *
+ *
* The method splits the field's name to extract the type and name and then parses the object
* using the {@link XContentParser#namedObject(Class, String, Object)} method.
*
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentSubParser.java b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentSubParser.java
index d1cdda4aeb8be..337cf9f95fe5f 100644
--- a/libs/core/src/main/java/org/opensearch/core/xcontent/XContentSubParser.java
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/XContentSubParser.java
@@ -43,7 +43,7 @@
/**
* Wrapper for a XContentParser that makes a single object/array look like a complete document.
- *
+ *
* The wrapper prevents the parsing logic to consume tokens outside of the wrapped object as well
* as skipping to the end of the object in case of a parsing error. The wrapper is intended to be
* used for parsing objects that should be ignored if they are malformed.
diff --git a/libs/core/src/main/java/org/opensearch/core/xcontent/spi/MediaTypeProvider.java b/libs/core/src/main/java/org/opensearch/core/xcontent/spi/MediaTypeProvider.java
new file mode 100644
index 0000000000000..eeaadc1698df6
--- /dev/null
+++ b/libs/core/src/main/java/org/opensearch/core/xcontent/spi/MediaTypeProvider.java
@@ -0,0 +1,29 @@
+/*
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * The OpenSearch Contributors require contributions made to
+ * this file be licensed under the Apache-2.0 license or a
+ * compatible open source license.
+ */
+
+package org.opensearch.core.xcontent.spi;
+
+import org.opensearch.core.xcontent.MediaType;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Service Provider Interface for plugins, modules, extensions providing
+ * their own Media Types
+ *
+ * @opensearch.experimental
+ * @opensearch.api
+ */
+public interface MediaTypeProvider {
+ /** Extensions that implement their own concrete {@link MediaType}s provide them through this interface method */
+ List