diff --git a/buildSrc/src/main/groovy/org/elasticsearch/gradle/doc/RestTestsFromSnippetsTask.groovy b/buildSrc/src/main/groovy/org/elasticsearch/gradle/doc/RestTestsFromSnippetsTask.groovy
index ba7311fee6f..c7f4316ee04 100644
--- a/buildSrc/src/main/groovy/org/elasticsearch/gradle/doc/RestTestsFromSnippetsTask.groovy
+++ b/buildSrc/src/main/groovy/org/elasticsearch/gradle/doc/RestTestsFromSnippetsTask.groovy
@@ -131,8 +131,9 @@ public class RestTestsFromSnippetsTask extends SnippetsTask {
}
private void response(Snippet response) {
- current.println(" - response_body: |")
- response.contents.eachLine { current.println(" $it") }
+ current.println(" - match: ")
+ current.println(" \$body: ")
+ response.contents.eachLine { current.println(" $it") }
}
void emitDo(String method, String pathAndQuery,
diff --git a/buildSrc/src/main/resources/checkstyle.xml b/buildSrc/src/main/resources/checkstyle.xml
index de47736913f..fe726062706 100644
--- a/buildSrc/src/main/resources/checkstyle.xml
+++ b/buildSrc/src/main/resources/checkstyle.xml
@@ -39,6 +39,25 @@
+
+
+
waiting for 3 nodes to be up");
- assertBusy(new Runnable() {
- @Override
- public void run() {
- NodesStatsResponse resp = client().admin().cluster().prepareNodesStats().get();
- assertThat(resp.getNodes().size(), equalTo(3));
- }
+ assertBusy(() -> {
+ NodesStatsResponse resp = client().admin().cluster().prepareNodesStats().get();
+ assertThat(resp.getNodes().size(), equalTo(3));
});
logger.info("--> creating 'test' index");
@@ -126,7 +123,6 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
Map explanations = cae.getNodeExplanations();
- Float noAttrWeight = -1f;
Float barAttrWeight = -1f;
Float fooBarAttrWeight = -1f;
for (Map.Entry entry : explanations.entrySet()) {
@@ -134,7 +130,6 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
String nodeName = node.getName();
NodeExplanation explanation = entry.getValue();
ClusterAllocationExplanation.FinalDecision finalDecision = explanation.getFinalDecision();
- String finalExplanation = explanation.getFinalExplanation();
ClusterAllocationExplanation.StoreCopy storeCopy = explanation.getStoreCopy();
Decision d = explanation.getDecision();
float weight = explanation.getWeight();
@@ -143,7 +138,6 @@ public final class ClusterAllocationExplainIT extends ESIntegTestCase {
assertEquals(d.type(), Decision.Type.NO);
if (noAttrNode.equals(nodeName)) {
assertThat(d.toString(), containsString("node does not match index include filters [foo:\"bar\"]"));
- noAttrWeight = weight;
assertNull(storeStatus);
assertEquals("the shard cannot be assigned because one or more allocation decider returns a 'NO' decision",
explanation.getFinalExplanation());
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainTests.java
index d5cefc6d1f3..6c23d1604b8 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplainTests.java
@@ -47,7 +47,6 @@ public final class ClusterAllocationExplainTests extends ESSingleNodeTestCase {
NodeExplanation explanation = cae.getNodeExplanations().values().iterator().next();
ClusterAllocationExplanation.FinalDecision fd = explanation.getFinalDecision();
ClusterAllocationExplanation.StoreCopy storeCopy = explanation.getStoreCopy();
- String finalExplanation = explanation.getFinalExplanation();
Decision d = explanation.getDecision();
assertNotNull("should have a decision", d);
assertEquals(Decision.Type.NO, d.type());
@@ -76,7 +75,6 @@ public final class ClusterAllocationExplainTests extends ESSingleNodeTestCase {
d = explanation.getDecision();
fd = explanation.getFinalDecision();
storeCopy = explanation.getStoreCopy();
- finalExplanation = explanation.getFinalExplanation();
assertNotNull("should have a decision", d);
assertEquals(Decision.Type.NO, d.type());
assertEquals(ClusterAllocationExplanation.FinalDecision.ALREADY_ASSIGNED, fd);
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplanationTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplanationTests.java
index d0e8ef14d01..1561ab7a77c 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplanationTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/allocation/ClusterAllocationExplanationTests.java
@@ -41,7 +41,6 @@ import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
-import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@@ -205,7 +204,7 @@ public final class ClusterAllocationExplanationTests extends ESTestCase {
"assignedNode", allocationDelay, remainingDelay, null, false, nodeExplanations);
BytesStreamOutput out = new BytesStreamOutput();
cae.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
ClusterAllocationExplanation cae2 = new ClusterAllocationExplanation(in);
assertEquals(shard, cae2.getShard());
assertTrue(cae2.isPrimary());
@@ -215,9 +214,7 @@ public final class ClusterAllocationExplanationTests extends ESTestCase {
assertEquals(allocationDelay, cae2.getAllocationDelayMillis());
assertEquals(remainingDelay, cae2.getRemainingDelayMillis());
for (Map.Entry entry : cae2.getNodeExplanations().entrySet()) {
- DiscoveryNode node = entry.getKey();
NodeExplanation explanation = entry.getValue();
- IndicesShardStoresResponse.StoreStatus status = explanation.getStoreStatus();
assertNotNull(explanation.getStoreStatus());
assertNotNull(explanation.getDecision());
assertEquals(nodeWeight, explanation.getWeight());
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponsesTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponsesTests.java
index 704c1348b7e..d0d452df478 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponsesTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/health/ClusterHealthResponsesTests.java
@@ -84,7 +84,7 @@ public class ClusterHealthResponsesTests extends ESTestCase {
if (randomBoolean()) {
BytesStreamOutput out = new BytesStreamOutput();
clusterHealth.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
clusterHealth = ClusterHealthResponse.readResponseFrom(in);
}
return clusterHealth;
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java
index c4d49d899b9..56756ad9fdb 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/node/tasks/TransportTasksActionTests.java
@@ -249,7 +249,7 @@ public class TransportTasksActionTests extends TaskManagerTestCase {
/**
* Test class for testing task operations
*/
- static abstract class TestTasksAction extends TransportTasksAction {
+ abstract static class TestTasksAction extends TransportTasksAction {
protected TestTasksAction(Settings settings, String actionName, ThreadPool threadPool,
ClusterService clusterService, TransportService transportService) {
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java
index b736751b781..4f553dfb88a 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteRequestTests.java
@@ -166,7 +166,7 @@ public class ClusterRerouteRequestTests extends ESTestCase {
private ClusterRerouteRequest roundTripThroughBytes(ClusterRerouteRequest original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
ClusterRerouteRequest copy = new ClusterRerouteRequest();
copy.readFrom(in);
return copy;
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java
index 00fcbf60a5a..dac878eefec 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/reroute/ClusterRerouteTests.java
@@ -66,7 +66,7 @@ public class ClusterRerouteTests extends ESAllocationTestCase {
BytesReference bytes = out.bytes();
NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry();
new NetworkModule(null, Settings.EMPTY, true, namedWriteableRegistry);
- StreamInput wrap = new NamedWriteableAwareStreamInput(StreamInput.wrap(bytes.toBytes()),
+ StreamInput wrap = new NamedWriteableAwareStreamInput(bytes.streamInput(),
namedWriteableRegistry);
ClusterRerouteRequest deserializedReq = new ClusterRerouteRequest();
deserializedReq.readFrom(wrap);
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTests.java
index fc04de81254..b515829b72a 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/state/ClusterStateRequestTests.java
@@ -45,7 +45,7 @@ public class ClusterStateRequestTests extends ESTestCase {
output.setVersion(testVersion);
clusterStateRequest.writeTo(output);
- StreamInput streamInput = StreamInput.wrap(output.bytes());
+ StreamInput streamInput = output.bytes().streamInput();
streamInput.setVersion(testVersion);
ClusterStateRequest deserializedCSRequest = new ClusterStateRequest();
deserializedCSRequest.readFrom(streamInput);
diff --git a/core/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestTests.java b/core/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestTests.java
index e4c2849b907..2e9239a2c3b 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequestTests.java
@@ -37,7 +37,7 @@ public class GetStoredScriptRequestTests extends ESTestCase {
out.setVersion(randomVersion(random()));
request.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
in.setVersion(out.getVersion());
GetStoredScriptRequest request2 = new GetStoredScriptRequest();
request2.readFrom(in);
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushUnitTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushUnitTests.java
index 04f6037f64b..7040c92ec1d 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushUnitTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/flush/SyncedFlushUnitTests.java
@@ -84,7 +84,7 @@ public class SyncedFlushUnitTests extends ESTestCase {
assertThat(testPlan.result.restStatus(), equalTo(testPlan.totalCounts.failed > 0 ? RestStatus.CONFLICT : RestStatus.OK));
BytesStreamOutput out = new BytesStreamOutput();
testPlan.result.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
SyncedFlushResponse readResponse = new SyncedFlushResponse();
readResponse.readFrom(in);
assertThat(readResponse.totalShards(), equalTo(testPlan.totalCounts.total));
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreRequestIT.java b/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreRequestIT.java
index 6e3e5d76224..1cd1704e164 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreRequestIT.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/shards/IndicesShardStoreRequestIT.java
@@ -215,7 +215,7 @@ public class IndicesShardStoreRequestIT extends ESIntegTestCase {
client().admin().indices().prepareFlush().setForce(true).setWaitIfOngoing(true).execute().actionGet();
}
- private final static class IndexNodePredicate implements Predicate {
+ private static final class IndexNodePredicate implements Predicate {
private final Set nodesWithShard;
public IndexNodePredicate(String index) {
diff --git a/core/src/test/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsTests.java b/core/src/test/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsTests.java
index 726dccee597..dfc10169e70 100644
--- a/core/src/test/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsTests.java
+++ b/core/src/test/java/org/elasticsearch/action/admin/indices/stats/IndicesStatsTests.java
@@ -19,6 +19,7 @@
package org.elasticsearch.action.admin.indices.stats;
+import org.elasticsearch.action.ShardOperationFailedException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.engine.CommitStats;
@@ -26,6 +27,8 @@ import org.elasticsearch.index.engine.SegmentsStats;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.test.ESSingleNodeTestCase;
+import java.util.List;
+
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasKey;
@@ -108,4 +111,12 @@ public class IndicesStatsTests extends ESSingleNodeTestCase {
}
}
+ /**
+ * Gives access to package private IndicesStatsResponse constructor for test purpose.
+ **/
+ public static IndicesStatsResponse newIndicesStatsResponse(ShardStats[] shards, int totalShards, int successfulShards,
+ int failedShards, List shardFailures) {
+ return new IndicesStatsResponse(shards, totalShards, successfulShards, failedShards, shardFailures);
+ }
+
}
diff --git a/core/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java b/core/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java
index 337f881d41b..142fb282c20 100644
--- a/core/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/bulk/BulkRequestTests.java
@@ -55,9 +55,9 @@ public class BulkRequestTests extends ESTestCase {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.add(bulkAction.getBytes(StandardCharsets.UTF_8), 0, bulkAction.length(), null, null);
assertThat(bulkRequest.numberOfActions(), equalTo(3));
- assertThat(((IndexRequest) bulkRequest.requests().get(0)).source().toBytes(), equalTo(new BytesArray("{ \"field1\" : \"value1\" }").toBytes()));
+ assertThat(((IndexRequest) bulkRequest.requests().get(0)).source(), equalTo(new BytesArray("{ \"field1\" : \"value1\" }")));
assertThat(bulkRequest.requests().get(1), instanceOf(DeleteRequest.class));
- assertThat(((IndexRequest) bulkRequest.requests().get(2)).source().toBytes(), equalTo(new BytesArray("{ \"field1\" : \"value3\" }").toBytes()));
+ assertThat(((IndexRequest) bulkRequest.requests().get(2)).source(), equalTo(new BytesArray("{ \"field1\" : \"value3\" }")));
}
public void testSimpleBulk2() throws Exception {
@@ -81,7 +81,7 @@ public class BulkRequestTests extends ESTestCase {
assertThat(bulkRequest.numberOfActions(), equalTo(4));
assertThat(((UpdateRequest) bulkRequest.requests().get(0)).id(), equalTo("1"));
assertThat(((UpdateRequest) bulkRequest.requests().get(0)).retryOnConflict(), equalTo(2));
- assertThat(((UpdateRequest) bulkRequest.requests().get(0)).doc().source().toUtf8(), equalTo("{\"field\":\"value\"}"));
+ assertThat(((UpdateRequest) bulkRequest.requests().get(0)).doc().source().utf8ToString(), equalTo("{\"field\":\"value\"}"));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).id(), equalTo("0"));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).type(), equalTo("type1"));
assertThat(((UpdateRequest) bulkRequest.requests().get(1)).index(), equalTo("index1"));
@@ -93,7 +93,7 @@ public class BulkRequestTests extends ESTestCase {
assertThat(scriptParams, notNullValue());
assertThat(scriptParams.size(), equalTo(1));
assertThat(((Integer) scriptParams.get("param1")), equalTo(1));
- assertThat(((UpdateRequest) bulkRequest.requests().get(1)).upsertRequest().source().toUtf8(), equalTo("{\"counter\":1}"));
+ assertThat(((UpdateRequest) bulkRequest.requests().get(1)).upsertRequest().source().utf8ToString(), equalTo("{\"counter\":1}"));
}
public void testBulkAllowExplicitIndex() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/action/bulk/BulkShardRequestTests.java b/core/src/test/java/org/elasticsearch/action/bulk/BulkShardRequestTests.java
index b26d2531ff0..bb406366d25 100644
--- a/core/src/test/java/org/elasticsearch/action/bulk/BulkShardRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/bulk/BulkShardRequestTests.java
@@ -29,11 +29,11 @@ public class BulkShardRequestTests extends ESTestCase {
public void testToString() {
String index = randomSimpleString(random(), 10);
int count = between(1, 100);
- BulkShardRequest r = new BulkShardRequest(null, new ShardId(index, "ignored", 0), RefreshPolicy.NONE, new BulkItemRequest[count]);
+ BulkShardRequest r = new BulkShardRequest(new ShardId(index, "ignored", 0), RefreshPolicy.NONE, new BulkItemRequest[count]);
assertEquals("BulkShardRequest to [" + index + "] containing [" + count + "] requests", r.toString());
- r = new BulkShardRequest(null, new ShardId(index, "ignored", 0), RefreshPolicy.IMMEDIATE, new BulkItemRequest[count]);
+ r = new BulkShardRequest(new ShardId(index, "ignored", 0), RefreshPolicy.IMMEDIATE, new BulkItemRequest[count]);
assertEquals("BulkShardRequest to [" + index + "] containing [" + count + "] requests and a refresh", r.toString());
- r = new BulkShardRequest(null, new ShardId(index, "ignored", 0), RefreshPolicy.WAIT_UNTIL, new BulkItemRequest[count]);
+ r = new BulkShardRequest(new ShardId(index, "ignored", 0), RefreshPolicy.WAIT_UNTIL, new BulkItemRequest[count]);
assertEquals("BulkShardRequest to [" + index + "] containing [" + count + "] requests blocking until refresh", r.toString());
}
}
diff --git a/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java b/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java
index 6ae7559ba62..6111c4c9953 100644
--- a/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java
+++ b/core/src/test/java/org/elasticsearch/action/bulk/TransportBulkActionTookTests.java
@@ -59,7 +59,7 @@ import static org.hamcrest.Matchers.greaterThanOrEqualTo;
public class TransportBulkActionTookTests extends ESTestCase {
- static private ThreadPool threadPool;
+ private static ThreadPool threadPool;
private ClusterService clusterService;
@BeforeClass
diff --git a/core/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java b/core/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java
index 451ade62584..ef259463139 100644
--- a/core/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/get/MultiGetShardRequestTests.java
@@ -70,7 +70,7 @@ public class MultiGetShardRequestTests extends ESTestCase {
out.setVersion(randomVersion(random()));
multiGetShardRequest.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
in.setVersion(out.getVersion());
MultiGetShardRequest multiGetShardRequest2 = new MultiGetShardRequest();
multiGetShardRequest2.readFrom(in);
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/SimulateDocumentSimpleResultTests.java b/core/src/test/java/org/elasticsearch/action/ingest/SimulateDocumentSimpleResultTests.java
index 323a8c0aaa6..544e2932b44 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/SimulateDocumentSimpleResultTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/SimulateDocumentSimpleResultTests.java
@@ -45,7 +45,7 @@ public class SimulateDocumentSimpleResultTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
simulateDocumentBaseResult.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
SimulateDocumentBaseResult otherSimulateDocumentBaseResult = new SimulateDocumentBaseResult(streamInput);
if (isFailure) {
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineResponseTests.java b/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineResponseTests.java
index 1376ca4280e..576e8e01724 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineResponseTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/SimulatePipelineResponseTests.java
@@ -73,7 +73,7 @@ public class SimulatePipelineResponseTests extends ESTestCase {
SimulatePipelineResponse response = new SimulatePipelineResponse(randomAsciiOfLengthBetween(1, 10), isVerbose, results);
BytesStreamOutput out = new BytesStreamOutput();
response.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
SimulatePipelineResponse otherResponse = new SimulatePipelineResponse();
otherResponse.readFrom(streamInput);
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/SimulateProcessorResultTests.java b/core/src/test/java/org/elasticsearch/action/ingest/SimulateProcessorResultTests.java
index f612f36c9d6..ccf3a674944 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/SimulateProcessorResultTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/SimulateProcessorResultTests.java
@@ -48,7 +48,7 @@ public class SimulateProcessorResultTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
simulateProcessorResult.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
SimulateProcessorResult otherSimulateProcessorResult = new SimulateProcessorResult(streamInput);
assertThat(otherSimulateProcessorResult.getProcessorTag(), equalTo(simulateProcessorResult.getProcessorTag()));
if (isFailure) {
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/WritePipelineResponseTests.java b/core/src/test/java/org/elasticsearch/action/ingest/WritePipelineResponseTests.java
index 3f252c37072..00327603ba8 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/WritePipelineResponseTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/WritePipelineResponseTests.java
@@ -35,7 +35,7 @@ public class WritePipelineResponseTests extends ESTestCase {
response = new WritePipelineResponse(isAcknowledged);
BytesStreamOutput out = new BytesStreamOutput();
response.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
WritePipelineResponse otherResponse = new WritePipelineResponse();
otherResponse.readFrom(streamInput);
@@ -46,7 +46,7 @@ public class WritePipelineResponseTests extends ESTestCase {
WritePipelineResponse response = new WritePipelineResponse();
BytesStreamOutput out = new BytesStreamOutput();
response.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
WritePipelineResponse otherResponse = new WritePipelineResponse();
otherResponse.readFrom(streamInput);
diff --git a/core/src/test/java/org/elasticsearch/action/ingest/WriteableIngestDocumentTests.java b/core/src/test/java/org/elasticsearch/action/ingest/WriteableIngestDocumentTests.java
index a7ce842913d..b4908846e97 100644
--- a/core/src/test/java/org/elasticsearch/action/ingest/WriteableIngestDocumentTests.java
+++ b/core/src/test/java/org/elasticsearch/action/ingest/WriteableIngestDocumentTests.java
@@ -112,7 +112,7 @@ public class WriteableIngestDocumentTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
writeableIngestDocument.writeTo(out);
- StreamInput streamInput = StreamInput.wrap(out.bytes());
+ StreamInput streamInput = out.bytes().streamInput();
WriteableIngestDocument otherWriteableIngestDocument = new WriteableIngestDocument(streamInput);
assertIngestDocument(otherWriteableIngestDocument.getIngestDocument(), writeableIngestDocument.getIngestDocument());
}
diff --git a/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java b/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java
index 2bff71d3c40..3e592d1c341 100644
--- a/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java
+++ b/core/src/test/java/org/elasticsearch/action/main/MainActionTests.java
@@ -64,7 +64,7 @@ public class MainActionTests extends ESTestCase {
BytesStreamOutput streamOutput = new BytesStreamOutput();
mainResponse.writeTo(streamOutput);
final MainResponse serialized = new MainResponse();
- serialized.readFrom(new ByteBufferStreamInput(ByteBuffer.wrap(streamOutput.bytes().toBytes())));
+ serialized.readFrom(streamOutput.bytes().streamInput());
assertThat(serialized.getNodeName(), equalTo(nodeName));
assertThat(serialized.getClusterName(), equalTo(clusterName));
diff --git a/core/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java b/core/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java
index d5ed5302b97..d656e0f62a9 100644
--- a/core/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java
+++ b/core/src/test/java/org/elasticsearch/action/support/IndicesOptionsTests.java
@@ -38,7 +38,7 @@ public class IndicesOptionsTests extends ESTestCase {
output.setVersion(outputVersion);
indicesOptions.writeIndicesOptions(output);
- StreamInput streamInput = StreamInput.wrap(output.bytes());
+ StreamInput streamInput = output.bytes().streamInput();
streamInput.setVersion(randomVersion(random()));
IndicesOptions indicesOptions2 = IndicesOptions.readIndicesOptions(streamInput);
diff --git a/core/src/test/java/org/elasticsearch/action/support/replication/ClusterStateCreationUtils.java b/core/src/test/java/org/elasticsearch/action/support/replication/ClusterStateCreationUtils.java
index dc40fda3f8e..d0e26c22cfb 100644
--- a/core/src/test/java/org/elasticsearch/action/support/replication/ClusterStateCreationUtils.java
+++ b/core/src/test/java/org/elasticsearch/action/support/replication/ClusterStateCreationUtils.java
@@ -220,7 +220,6 @@ public class ClusterStateCreationUtils {
* Creates a cluster state with no index
*/
public static ClusterState stateWithNoShard() {
- int numberOfNodes = 2;
DiscoveryNodes.Builder discoBuilder = DiscoveryNodes.builder();
discoBuilder.localNodeId(newNode(0).getId());
discoBuilder.masterNodeId(newNode(1).getId());
@@ -260,7 +259,7 @@ public class ClusterStateCreationUtils {
new HashSet<>(Arrays.asList(DiscoveryNode.Role.values())), Version.CURRENT);
}
- static private String selectAndRemove(Set strings) {
+ private static String selectAndRemove(Set strings) {
String selection = randomFrom(strings.toArray(new String[strings.size()]));
strings.remove(selection);
return selection;
diff --git a/core/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java b/core/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java
index 208945a6179..d9f351120b2 100644
--- a/core/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java
+++ b/core/src/test/java/org/elasticsearch/action/termvectors/AbstractTermVectorsTestCase.java
@@ -68,10 +68,10 @@ import static org.hamcrest.Matchers.equalTo;
public abstract class AbstractTermVectorsTestCase extends ESIntegTestCase {
protected static class TestFieldSetting {
- final public String name;
- final public boolean storedOffset;
- final public boolean storedPayloads;
- final public boolean storedPositions;
+ public final String name;
+ public final boolean storedOffset;
+ public final boolean storedPayloads;
+ public final boolean storedPositions;
public TestFieldSetting(String name, boolean storedOffset, boolean storedPayloads, boolean storedPositions) {
this.name = name;
@@ -124,9 +124,9 @@ public abstract class AbstractTermVectorsTestCase extends ESIntegTestCase {
}
protected static class TestDoc {
- final public String id;
- final public TestFieldSetting[] fieldSettings;
- final public String[] fieldContent;
+ public final String id;
+ public final TestFieldSetting[] fieldSettings;
+ public final String[] fieldContent;
public String index = "test";
public String alias = "alias";
public String type = "type1";
@@ -163,11 +163,11 @@ public abstract class AbstractTermVectorsTestCase extends ESIntegTestCase {
}
protected static class TestConfig {
- final public TestDoc doc;
- final public String[] selectedFields;
- final public boolean requestPositions;
- final public boolean requestOffsets;
- final public boolean requestPayloads;
+ public final TestDoc doc;
+ public final String[] selectedFields;
+ public final boolean requestPositions;
+ public final boolean requestOffsets;
+ public final boolean requestPayloads;
public Class expectedException = null;
public TestConfig(TestDoc doc, String[] selectedFields, boolean requestPositions, boolean requestOffsets, boolean requestPayloads) {
diff --git a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsCheckDocFreqIT.java b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsCheckDocFreqIT.java
index 37a1bc92e9c..1611c63d2ba 100644
--- a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsCheckDocFreqIT.java
+++ b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsCheckDocFreqIT.java
@@ -140,7 +140,7 @@ public class GetTermVectorsCheckDocFreqIT extends ESIntegTestCase {
xBuilder.startObject();
response.toXContent(xBuilder, null);
xBuilder.endObject();
- String utf8 = xBuilder.bytes().toUtf8().replaceFirst("\"took\":\\d+,", "");;
+ String utf8 = xBuilder.bytes().utf8ToString().replaceFirst("\"took\":\\d+,", "");;
String expectedString = "{\"_index\":\"test\",\"_type\":\"type1\",\"_id\":\""
+ i
+ "\",\"_version\":1,\"found\":true,\"term_vectors\":{\"field\":{\"terms\":{\"brown\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":2,\"start_offset\":10,\"end_offset\":15,\"payload\":\"d29yZA==\"}]},\"dog\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":8,\"start_offset\":40,\"end_offset\":43,\"payload\":\"d29yZA==\"}]},\"fox\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":3,\"start_offset\":16,\"end_offset\":19,\"payload\":\"d29yZA==\"}]},\"jumps\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":4,\"start_offset\":20,\"end_offset\":25,\"payload\":\"d29yZA==\"}]},\"lazy\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":7,\"start_offset\":35,\"end_offset\":39,\"payload\":\"d29yZA==\"}]},\"over\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":5,\"start_offset\":26,\"end_offset\":30,\"payload\":\"d29yZA==\"}]},\"quick\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":1,\"start_offset\":4,\"end_offset\":9,\"payload\":\"d29yZA==\"}]},\"the\":{\"doc_freq\":15,\"ttf\":30,\"term_freq\":2,\"tokens\":[{\"position\":0,\"start_offset\":0,\"end_offset\":3,\"payload\":\"d29yZA==\"},{\"position\":6,\"start_offset\":31,\"end_offset\":34,\"payload\":\"d29yZA==\"}]}}}}}";
@@ -196,7 +196,7 @@ public class GetTermVectorsCheckDocFreqIT extends ESIntegTestCase {
xBuilder.startObject();
response.toXContent(xBuilder, null);
xBuilder.endObject();
- String utf8 = xBuilder.bytes().toUtf8().replaceFirst("\"took\":\\d+,", "");;
+ String utf8 = xBuilder.bytes().utf8ToString().replaceFirst("\"took\":\\d+,", "");;
String expectedString = "{\"_index\":\"test\",\"_type\":\"type1\",\"_id\":\""
+ i
+ "\",\"_version\":1,\"found\":true,\"term_vectors\":{\"field\":{\"field_statistics\":{\"sum_doc_freq\":120,\"doc_count\":15,\"sum_ttf\":135},\"terms\":{\"brown\":{\"term_freq\":1,\"tokens\":[{\"position\":2,\"start_offset\":10,\"end_offset\":15,\"payload\":\"d29yZA==\"}]},\"dog\":{\"term_freq\":1,\"tokens\":[{\"position\":8,\"start_offset\":40,\"end_offset\":43,\"payload\":\"d29yZA==\"}]},\"fox\":{\"term_freq\":1,\"tokens\":[{\"position\":3,\"start_offset\":16,\"end_offset\":19,\"payload\":\"d29yZA==\"}]},\"jumps\":{\"term_freq\":1,\"tokens\":[{\"position\":4,\"start_offset\":20,\"end_offset\":25,\"payload\":\"d29yZA==\"}]},\"lazy\":{\"term_freq\":1,\"tokens\":[{\"position\":7,\"start_offset\":35,\"end_offset\":39,\"payload\":\"d29yZA==\"}]},\"over\":{\"term_freq\":1,\"tokens\":[{\"position\":5,\"start_offset\":26,\"end_offset\":30,\"payload\":\"d29yZA==\"}]},\"quick\":{\"term_freq\":1,\"tokens\":[{\"position\":1,\"start_offset\":4,\"end_offset\":9,\"payload\":\"d29yZA==\"}]},\"the\":{\"term_freq\":2,\"tokens\":[{\"position\":0,\"start_offset\":0,\"end_offset\":3,\"payload\":\"d29yZA==\"},{\"position\":6,\"start_offset\":31,\"end_offset\":34,\"payload\":\"d29yZA==\"}]}}}}}";
@@ -255,7 +255,7 @@ public class GetTermVectorsCheckDocFreqIT extends ESIntegTestCase {
xBuilder.startObject();
response.toXContent(xBuilder, ToXContent.EMPTY_PARAMS);
xBuilder.endObject();
- String utf8 = xBuilder.bytes().toUtf8().replaceFirst("\"took\":\\d+,", "");;
+ String utf8 = xBuilder.bytes().utf8ToString().replaceFirst("\"took\":\\d+,", "");;
String expectedString = "{\"_index\":\"test\",\"_type\":\"type1\",\"_id\":\""
+ i
+ "\",\"_version\":1,\"found\":true,\"term_vectors\":{\"field\":{\"field_statistics\":{\"sum_doc_freq\":120,\"doc_count\":15,\"sum_ttf\":135},\"terms\":{\"brown\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":2,\"start_offset\":10,\"end_offset\":15,\"payload\":\"d29yZA==\"}]},\"dog\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":8,\"start_offset\":40,\"end_offset\":43,\"payload\":\"d29yZA==\"}]},\"fox\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":3,\"start_offset\":16,\"end_offset\":19,\"payload\":\"d29yZA==\"}]},\"jumps\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":4,\"start_offset\":20,\"end_offset\":25,\"payload\":\"d29yZA==\"}]},\"lazy\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":7,\"start_offset\":35,\"end_offset\":39,\"payload\":\"d29yZA==\"}]},\"over\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":5,\"start_offset\":26,\"end_offset\":30,\"payload\":\"d29yZA==\"}]},\"quick\":{\"doc_freq\":15,\"ttf\":15,\"term_freq\":1,\"tokens\":[{\"position\":1,\"start_offset\":4,\"end_offset\":9,\"payload\":\"d29yZA==\"}]},\"the\":{\"doc_freq\":15,\"ttf\":30,\"term_freq\":2,\"tokens\":[{\"position\":0,\"start_offset\":0,\"end_offset\":3,\"payload\":\"d29yZA==\"},{\"position\":6,\"start_offset\":31,\"end_offset\":34,\"payload\":\"d29yZA==\"}]}}}}}";
diff --git a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java
index 12af9f8a2c2..6ba31fdb88e 100644
--- a/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java
+++ b/core/src/test/java/org/elasticsearch/action/termvectors/GetTermVectorsIT.java
@@ -39,7 +39,6 @@ import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.index.mapper.FieldMapper;
-import org.hamcrest.Matcher;
import java.io.IOException;
import java.util.ArrayList;
@@ -55,7 +54,6 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows;
import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
@@ -963,21 +961,6 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
return randomBoolean() ? "test" : "alias";
}
- private Map getFieldStatistics(Map stats, String fieldName) throws IOException {
- return (Map) ((Map) stats.get(fieldName)).get("field_statistics");
- }
-
- private Map getTermStatistics(Map stats, String fieldName, String term) {
- return (Map) ((Map) ((Map) stats.get(fieldName)).get("terms")).get(term);
- }
-
- private Matcher equalOrLessThanTo(Integer value, boolean isEqual) {
- if (isEqual) {
- return equalTo(value);
- }
- return lessThan(value);
- }
-
public void testTermVectorsWithVersion() {
assertAcked(prepareCreate("test").addAlias(new Alias("alias"))
.setSettings(Settings.builder().put("index.refresh_interval", -1)));
diff --git a/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java b/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java
index 597a2a4db39..d105a4bf63b 100644
--- a/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java
+++ b/core/src/test/java/org/elasticsearch/action/update/UpdateRequestTests.java
@@ -135,7 +135,7 @@ public class UpdateRequestTests extends ESTestCase {
TimeValue providedTTLValue = TimeValue.parseTimeValue(randomTimeValue(), null, "ttl");
Settings settings = settings(Version.CURRENT).build();
- UpdateHelper updateHelper = new UpdateHelper(settings, null, null);
+ UpdateHelper updateHelper = new UpdateHelper(settings, null);
// We just upsert one document with ttl
IndexRequest indexRequest = new IndexRequest("test", "type1", "1")
diff --git a/core/src/test/java/org/elasticsearch/blocks/SimpleBlocksIT.java b/core/src/test/java/org/elasticsearch/blocks/SimpleBlocksIT.java
index ffe82f9388d..699b919cf05 100644
--- a/core/src/test/java/org/elasticsearch/blocks/SimpleBlocksIT.java
+++ b/core/src/test/java/org/elasticsearch/blocks/SimpleBlocksIT.java
@@ -141,15 +141,6 @@ public class SimpleBlocksIT extends ESIntegTestCase {
}
}
- private void canNotIndexExists(String index) {
- try {
- IndicesExistsResponse r = client().admin().indices().prepareExists(index).execute().actionGet();
- fail();
- } catch (ClusterBlockException e) {
- // all is well
- }
- }
-
private void setIndexReadOnly(String index, Object value) {
HashMap newSettings = new HashMap<>();
newSettings.put(IndexMetaData.SETTING_READ_ONLY, value);
diff --git a/core/src/test/java/org/elasticsearch/bwcompat/BasicAnalysisBackwardCompatibilityIT.java b/core/src/test/java/org/elasticsearch/bwcompat/BasicAnalysisBackwardCompatibilityIT.java
index 40995ff778b..be0848ed4dc 100644
--- a/core/src/test/java/org/elasticsearch/bwcompat/BasicAnalysisBackwardCompatibilityIT.java
+++ b/core/src/test/java/org/elasticsearch/bwcompat/BasicAnalysisBackwardCompatibilityIT.java
@@ -41,7 +41,7 @@ import static org.hamcrest.Matchers.equalTo;
public class BasicAnalysisBackwardCompatibilityIT extends ESBackcompatTestCase {
// This pattern match characters with Line_Break = Complex_Content.
- final static Pattern complexUnicodeChars = Pattern.compile("[\u17B4\u17B5\u17D3\u17CB-\u17D1\u17DD\u1036\u17C6\u1A74\u1038\u17C7\u0E4E\u0E47-\u0E4D\u0EC8-\u0ECD\uAABF\uAAC1\u1037\u17C8-\u17CA\u1A75-\u1A7C\u1AA8-\u1AAB\uAADE\uAADF\u1AA0-\u1AA6\u1AAC\u1AAD\u109E\u109F\uAA77-\uAA79\u0E46\u0EC6\u17D7\u1AA7\uA9E6\uAA70\uAADD\u19DA\u0E01-\u0E3A\u0E40-\u0E45\u0EDE\u0E81\u0E82\u0E84\u0E87\u0E88\u0EAA\u0E8A\u0EDF\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAB\u0EDC\u0EDD\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\uAA80-\uAABE\uAAC0\uAAC2\uAADB\uAADC\u1000\u1075\u1001\u1076\u1002\u1077\uAA60\uA9E9\u1003\uA9E0\uA9EA\u1004\u105A\u1005\u1078\uAA61\u1006\uA9E1\uAA62\uAA7E\u1007\uAA63\uA9EB\u1079\uAA72\u1008\u105B\uA9E2\uAA64\uA9EC\u1061\uAA7F\u1009\u107A\uAA65\uA9E7\u100A\u100B\uAA66\u100C\uAA67\u100D\uAA68\uA9ED\u100E\uAA69\uA9EE\u100F\u106E\uA9E3\uA9EF\u1010-\u1012\u107B\uA9FB\u1013\uAA6A\uA9FC\u1014\u107C\uAA6B\u105E\u1015\u1016\u107D\u107E\uAA6F\u108E\uA9E8\u1017\u107F\uA9FD\u1018\uA9E4\uA9FE\u1019\u105F\u101A\u103B\u101B\uAA73\uAA7A\u103C\u101C\u1060\u101D\u103D\u1082\u1080\u1050\u1051\u1065\u101E\u103F\uAA6C\u101F\u1081\uAA6D\u103E\uAA6E\uAA71\u1020\uA9FA\u105C\u105D\u106F\u1070\u1066\u1021-\u1026\u1052-\u1055\u1027-\u102A\u102C\u102B\u1083\u1072\u109C\u102D\u1071\u102E\u1033\u102F\u1073\u1074\u1030\u1056-\u1059\u1031\u1084\u1035\u1085\u1032\u109D\u1034\u1062\u1067\u1068\uA9E5\u1086\u1039\u103A\u1063\u1064\u1069-\u106D\u1087\u108B\u1088\u108C\u108D\u1089\u108A\u108F\u109A\u109B\uAA7B-\uAA7D\uAA74-\uAA76\u1780-\u17A2\u17DC\u17A3-\u17B3\u17B6-\u17C5\u17D2\u1950-\u196D\u1970-\u1974\u1980-\u199C\u19DE\u19DF\u199D-\u19AB\u19B0-\u19C9\u1A20-\u1A26\u1A58\u1A59\u1A27-\u1A3B\u1A5A\u1A5B\u1A3C-\u1A46\u1A54\u1A47-\u1A4C\u1A53\u1A6B\u1A55-\u1A57\u1A5C-\u1A5E\u1A4D-\u1A52\u1A61\u1A6C\u1A62-\u1A6A\u1A6E\u1A6F\u1A73\u1A70-\u1A72\u1A6D\u1A60]");
+ static final Pattern complexUnicodeChars = Pattern.compile("[\u17B4\u17B5\u17D3\u17CB-\u17D1\u17DD\u1036\u17C6\u1A74\u1038\u17C7\u0E4E\u0E47-\u0E4D\u0EC8-\u0ECD\uAABF\uAAC1\u1037\u17C8-\u17CA\u1A75-\u1A7C\u1AA8-\u1AAB\uAADE\uAADF\u1AA0-\u1AA6\u1AAC\u1AAD\u109E\u109F\uAA77-\uAA79\u0E46\u0EC6\u17D7\u1AA7\uA9E6\uAA70\uAADD\u19DA\u0E01-\u0E3A\u0E40-\u0E45\u0EDE\u0E81\u0E82\u0E84\u0E87\u0E88\u0EAA\u0E8A\u0EDF\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAB\u0EDC\u0EDD\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\uAA80-\uAABE\uAAC0\uAAC2\uAADB\uAADC\u1000\u1075\u1001\u1076\u1002\u1077\uAA60\uA9E9\u1003\uA9E0\uA9EA\u1004\u105A\u1005\u1078\uAA61\u1006\uA9E1\uAA62\uAA7E\u1007\uAA63\uA9EB\u1079\uAA72\u1008\u105B\uA9E2\uAA64\uA9EC\u1061\uAA7F\u1009\u107A\uAA65\uA9E7\u100A\u100B\uAA66\u100C\uAA67\u100D\uAA68\uA9ED\u100E\uAA69\uA9EE\u100F\u106E\uA9E3\uA9EF\u1010-\u1012\u107B\uA9FB\u1013\uAA6A\uA9FC\u1014\u107C\uAA6B\u105E\u1015\u1016\u107D\u107E\uAA6F\u108E\uA9E8\u1017\u107F\uA9FD\u1018\uA9E4\uA9FE\u1019\u105F\u101A\u103B\u101B\uAA73\uAA7A\u103C\u101C\u1060\u101D\u103D\u1082\u1080\u1050\u1051\u1065\u101E\u103F\uAA6C\u101F\u1081\uAA6D\u103E\uAA6E\uAA71\u1020\uA9FA\u105C\u105D\u106F\u1070\u1066\u1021-\u1026\u1052-\u1055\u1027-\u102A\u102C\u102B\u1083\u1072\u109C\u102D\u1071\u102E\u1033\u102F\u1073\u1074\u1030\u1056-\u1059\u1031\u1084\u1035\u1085\u1032\u109D\u1034\u1062\u1067\u1068\uA9E5\u1086\u1039\u103A\u1063\u1064\u1069-\u106D\u1087\u108B\u1088\u108C\u108D\u1089\u108A\u108F\u109A\u109B\uAA7B-\uAA7D\uAA74-\uAA76\u1780-\u17A2\u17DC\u17A3-\u17B3\u17B6-\u17C5\u17D2\u1950-\u196D\u1970-\u1974\u1980-\u199C\u19DE\u19DF\u199D-\u19AB\u19B0-\u19C9\u1A20-\u1A26\u1A58\u1A59\u1A27-\u1A3B\u1A5A\u1A5B\u1A3C-\u1A46\u1A54\u1A47-\u1A4C\u1A53\u1A6B\u1A55-\u1A57\u1A5C-\u1A5E\u1A4D-\u1A52\u1A61\u1A6C\u1A62-\u1A6A\u1A6E\u1A6F\u1A73\u1A70-\u1A72\u1A6D\u1A60]");
/**
* Simple upgrade test for analyzers to make sure they analyze to the same tokens after upgrade
diff --git a/core/src/test/java/org/elasticsearch/bwcompat/NodesStatsBasicBackwardsCompatIT.java b/core/src/test/java/org/elasticsearch/bwcompat/NodesStatsBasicBackwardsCompatIT.java
index c9d5f0b622e..4601c1bcfcf 100644
--- a/core/src/test/java/org/elasticsearch/bwcompat/NodesStatsBasicBackwardsCompatIT.java
+++ b/core/src/test/java/org/elasticsearch/bwcompat/NodesStatsBasicBackwardsCompatIT.java
@@ -22,7 +22,6 @@ package org.elasticsearch.bwcompat;
import org.elasticsearch.action.admin.cluster.node.info.NodeInfo;
import org.elasticsearch.action.admin.cluster.node.info.NodesInfoResponse;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsRequestBuilder;
-import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESBackcompatTestCase;
@@ -46,7 +45,7 @@ public class NodesStatsBasicBackwardsCompatIT extends ESBackcompatTestCase {
for (NodeInfo n : nodesInfo.getNodes()) {
TransportClient tc = TransportClient.builder().settings(settings).build().addTransportAddress(n.getNode().getAddress());
// Just verify that the NS can be sent and serialized/deserialized between nodes with basic indices
- NodesStatsResponse ns = tc.admin().cluster().prepareNodesStats().setIndices(true).execute().actionGet();
+ tc.admin().cluster().prepareNodesStats().setIndices(true).execute().actionGet();
tc.close();
}
}
@@ -78,7 +77,7 @@ public class NodesStatsBasicBackwardsCompatIT extends ESBackcompatTestCase {
method.invoke(nsBuilder);
}
}
- NodesStatsResponse ns = nsBuilder.execute().actionGet();
+ nsBuilder.execute().actionGet();
tc.close();
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/ClusterStateDiffIT.java b/core/src/test/java/org/elasticsearch/cluster/ClusterStateDiffIT.java
index b82b5e0ba60..da196d5d1d3 100644
--- a/core/src/test/java/org/elasticsearch/cluster/ClusterStateDiffIT.java
+++ b/core/src/test/java/org/elasticsearch/cluster/ClusterStateDiffIT.java
@@ -30,6 +30,7 @@ import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.IndexTemplateMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.RepositoriesMetaData;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.snapshots.SnapshotId;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
@@ -121,7 +122,7 @@ public class ClusterStateDiffIT extends ESIntegTestCase {
Diff diffBeforeSerialization = clusterState.diff(previousClusterState);
BytesStreamOutput os = new BytesStreamOutput();
diffBeforeSerialization.writeTo(os);
- byte[] diffBytes = os.bytes().toBytes();
+ byte[] diffBytes = BytesReference.toBytes(os.bytes());
Diff diff;
try (StreamInput input = StreamInput.wrap(diffBytes)) {
diff = previousClusterStateFromDiffs.readDiffFrom(input);
diff --git a/core/src/test/java/org/elasticsearch/cluster/block/ClusterBlockTests.java b/core/src/test/java/org/elasticsearch/cluster/block/ClusterBlockTests.java
index 7f2d0828128..a7fe1b918c0 100644
--- a/core/src/test/java/org/elasticsearch/cluster/block/ClusterBlockTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/block/ClusterBlockTests.java
@@ -55,7 +55,7 @@ public class ClusterBlockTests extends ESTestCase {
out.setVersion(version);
clusterBlock.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
in.setVersion(version);
ClusterBlock result = ClusterBlock.readClusterBlock(in);
diff --git a/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java b/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java
index fd1e3e62466..0918358a510 100644
--- a/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/health/ClusterStateHealthTests.java
@@ -169,7 +169,7 @@ public class ClusterStateHealthTests extends ESTestCase {
if (randomBoolean()) {
BytesStreamOutput out = new BytesStreamOutput();
clusterStateHealth.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
clusterStateHealth = new ClusterStateHealth(in);
}
return clusterStateHealth;
diff --git a/core/src/test/java/org/elasticsearch/cluster/metadata/IndexGraveyardTests.java b/core/src/test/java/org/elasticsearch/cluster/metadata/IndexGraveyardTests.java
index aec701052fb..8dd950ba8e6 100644
--- a/core/src/test/java/org/elasticsearch/cluster/metadata/IndexGraveyardTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/metadata/IndexGraveyardTests.java
@@ -60,8 +60,7 @@ public class IndexGraveyardTests extends ESTestCase {
final IndexGraveyard graveyard = createRandom();
final BytesStreamOutput out = new BytesStreamOutput();
graveyard.writeTo(out);
- final ByteBufferStreamInput in = new ByteBufferStreamInput(ByteBuffer.wrap(out.bytes().toBytes()));
- assertThat(IndexGraveyard.fromStream(in), equalTo(graveyard));
+ assertThat(IndexGraveyard.fromStream(out.bytes().streamInput()), equalTo(graveyard));
}
public void testXContent() throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/cluster/metadata/IndexMetaDataTests.java b/core/src/test/java/org/elasticsearch/cluster/metadata/IndexMetaDataTests.java
index 0c9827587ea..5fef33be388 100644
--- a/core/src/test/java/org/elasticsearch/cluster/metadata/IndexMetaDataTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/metadata/IndexMetaDataTests.java
@@ -69,7 +69,7 @@ public class IndexMetaDataTests extends ESTestCase {
final BytesStreamOutput out = new BytesStreamOutput();
metaData.writeTo(out);
- IndexMetaData deserialized = IndexMetaData.PROTO.readFrom(StreamInput.wrap(out.bytes()));
+ IndexMetaData deserialized = IndexMetaData.PROTO.readFrom(out.bytes().streamInput());
assertEquals(metaData, deserialized);
assertEquals(metaData.hashCode(), deserialized.hashCode());
diff --git a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataTests.java b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataTests.java
index e1e3a39122c..cf040fb3c7f 100644
--- a/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/metadata/MetaDataTests.java
@@ -22,7 +22,6 @@ package org.elasticsearch.cluster.metadata;
import org.elasticsearch.Version;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.bytes.BytesReference;
-import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
@@ -34,7 +33,6 @@ import org.elasticsearch.index.Index;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
-import java.nio.ByteBuffer;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
@@ -185,8 +183,7 @@ public class MetaDataTests extends ESTestCase {
final MetaData originalMeta = MetaData.builder().indexGraveyard(graveyard).build();
final BytesStreamOutput out = new BytesStreamOutput();
originalMeta.writeTo(out);
- final ByteBufferStreamInput in = new ByteBufferStreamInput(ByteBuffer.wrap(out.bytes().toBytes()));
- final MetaData fromStreamMeta = MetaData.PROTO.readFrom(in);
+ final MetaData fromStreamMeta = MetaData.PROTO.readFrom(out.bytes().streamInput());
assertThat(fromStreamMeta.indexGraveyard(), equalTo(fromStreamMeta.indexGraveyard()));
}
}
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryTermsTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryTermsTests.java
index 2d3e44db68a..32072282d6f 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryTermsTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/PrimaryTermsTests.java
@@ -50,7 +50,7 @@ public class PrimaryTermsTests extends ESAllocationTestCase {
private RoutingTable testRoutingTable;
private int numberOfShards;
private int numberOfReplicas;
- private final static Settings DEFAULT_SETTINGS = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
+ private static final Settings DEFAULT_SETTINGS = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
private AllocationService allocationService;
private ClusterState clusterState;
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java
index 2d1a467a001..9da5e76ed1f 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/RoutingTableTests.java
@@ -47,7 +47,7 @@ public class RoutingTableTests extends ESAllocationTestCase {
private int numberOfReplicas;
private int shardsPerIndex;
private int totalNumberOfShards;
- private final static Settings DEFAULT_SETTINGS = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
+ private static final Settings DEFAULT_SETTINGS = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
private final AllocationService ALLOCATION_SERVICE = createAllocationService(Settings.builder()
.put("cluster.routing.allocation.node_concurrent_recoveries", Integer.MAX_VALUE) // don't limit recoveries
.put("cluster.routing.allocation.node_initial_primaries_recoveries", Integer.MAX_VALUE)
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/ShardRoutingTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/ShardRoutingTests.java
index 7267252b19f..fa9133f6d36 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/ShardRoutingTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/ShardRoutingTests.java
@@ -206,7 +206,7 @@ public class ShardRoutingTests extends ESTestCase {
if (randomBoolean()) {
BytesStreamOutput out = new BytesStreamOutput();
routing.writeTo(out);
- routing = new ShardRouting(StreamInput.wrap(out.bytes()));
+ routing = new ShardRouting(out.bytes().streamInput());
}
if (routing.initializing() || routing.relocating()) {
assertEquals(routing.toString(), byteSize, routing.getExpectedShardSize());
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/UnassignedInfoTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/UnassignedInfoTests.java
index 75300a4beb8..ec33a3cd5fc 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/UnassignedInfoTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/UnassignedInfoTests.java
@@ -82,7 +82,7 @@ public class UnassignedInfoTests extends ESAllocationTestCase {
meta.writeTo(out);
out.close();
- UnassignedInfo read = new UnassignedInfo(StreamInput.wrap(out.bytes()));
+ UnassignedInfo read = new UnassignedInfo(out.bytes().streamInput());
assertThat(read.getReason(), equalTo(meta.getReason()));
assertThat(read.getUnassignedTimeInMillis(), equalTo(meta.getUnassignedTimeInMillis()));
assertThat(read.getMessage(), equalTo(meta.getMessage()));
diff --git a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationCommandsTests.java b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationCommandsTests.java
index 28f27b8988c..f95fb687c76 100644
--- a/core/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationCommandsTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/routing/allocation/AllocationCommandsTests.java
@@ -430,7 +430,7 @@ public class AllocationCommandsTests extends ESAllocationTestCase {
);
BytesStreamOutput bytes = new BytesStreamOutput();
AllocationCommands.writeTo(commands, bytes);
- StreamInput in = StreamInput.wrap(bytes.bytes());
+ StreamInput in = bytes.bytes().streamInput();
// Since the commands are named writeable we need to register them and wrap the input stream
NamedWriteableRegistry namedWriteableRegistry = new NamedWriteableRegistry();
diff --git a/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java b/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java
index 7b81d3ece27..4fa6615ac45 100644
--- a/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/serialization/ClusterSerializationTests.java
@@ -80,7 +80,7 @@ public class ClusterSerializationTests extends ESAllocationTestCase {
BytesStreamOutput outStream = new BytesStreamOutput();
source.writeTo(outStream);
- StreamInput inStream = StreamInput.wrap(outStream.bytes().toBytes());
+ StreamInput inStream = outStream.bytes().streamInput();
RoutingTable target = RoutingTable.Builder.readFrom(inStream);
assertThat(target.prettyPrint(), equalTo(source.prettyPrint()));
diff --git a/core/src/test/java/org/elasticsearch/cluster/serialization/DiffableTests.java b/core/src/test/java/org/elasticsearch/cluster/serialization/DiffableTests.java
index 452c6054576..611c261e334 100644
--- a/core/src/test/java/org/elasticsearch/cluster/serialization/DiffableTests.java
+++ b/core/src/test/java/org/elasticsearch/cluster/serialization/DiffableTests.java
@@ -310,7 +310,7 @@ public class DiffableTests extends ESTestCase {
logger.debug("--> serializing diff");
BytesStreamOutput out = new BytesStreamOutput();
diffMap.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
logger.debug("--> reading diff back");
diffMap = readDiff(in);
}
diff --git a/core/src/test/java/org/elasticsearch/common/ChannelsTests.java b/core/src/test/java/org/elasticsearch/common/ChannelsTests.java
index 4f2bad36d4a..c0cb3482b0e 100644
--- a/core/src/test/java/org/elasticsearch/common/ChannelsTests.java
+++ b/core/src/test/java/org/elasticsearch/common/ChannelsTests.java
@@ -19,14 +19,11 @@
package org.elasticsearch.common;
-import org.elasticsearch.common.bytes.ByteBufferBytesReference;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.Channels;
import org.elasticsearch.test.ESTestCase;
import org.hamcrest.Matchers;
-import org.jboss.netty.buffer.ByteBufferBackedChannelBuffer;
-import org.jboss.netty.buffer.ChannelBuffer;
import org.junit.After;
import org.junit.Before;
@@ -85,7 +82,7 @@ public class ChannelsTests extends ESTestCase {
BytesReference source = new BytesArray(randomBytes, offset + offsetToRead, lengthToRead);
BytesReference read = new BytesArray(readBytes, offset + offsetToRead, lengthToRead);
- assertThat("read bytes didn't match written bytes", source.toBytes(), Matchers.equalTo(read.toBytes()));
+ assertThat("read bytes didn't match written bytes", BytesReference.toBytes(source), Matchers.equalTo(BytesReference.toBytes(read)));
}
public void testBufferReadPastEOFWithException() throws Exception {
@@ -157,7 +154,9 @@ public class ChannelsTests extends ESTestCase {
copy.flip();
BytesReference sourceRef = new BytesArray(randomBytes, offset + offsetToRead, lengthToRead);
- BytesReference copyRef = new ByteBufferBytesReference(copy);
+ byte[] tmp = new byte[copy.remaining()];
+ copy.duplicate().get(tmp);
+ BytesReference copyRef = new BytesArray(tmp);
assertTrue("read bytes didn't match written bytes", sourceRef.equals(copyRef));
}
diff --git a/core/src/test/java/org/elasticsearch/common/bytes/AbstractBytesReferenceTestCase.java b/core/src/test/java/org/elasticsearch/common/bytes/AbstractBytesReferenceTestCase.java
index f31d7c69325..90922327732 100644
--- a/core/src/test/java/org/elasticsearch/common/bytes/AbstractBytesReferenceTestCase.java
+++ b/core/src/test/java/org/elasticsearch/common/bytes/AbstractBytesReferenceTestCase.java
@@ -29,7 +29,6 @@ import org.elasticsearch.common.util.BigArrays;
import org.elasticsearch.common.util.ByteArray;
import org.elasticsearch.indices.breaker.NoneCircuitBreakerService;
import org.elasticsearch.test.ESTestCase;
-import org.hamcrest.Matchers;
import java.io.EOFException;
import java.io.IOException;
@@ -66,12 +65,9 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
int sliceLength = Math.max(0, length - sliceOffset - 1);
BytesReference slice = pbr.slice(sliceOffset, sliceLength);
assertEquals(sliceLength, slice.length());
-
- if (slice.hasArray()) {
- assertEquals(sliceOffset, slice.arrayOffset());
- } else {
- expectThrows(IllegalStateException.class, () ->
- slice.arrayOffset());
+ BytesRef singlePageOrNull = getSinglePageOrNull(slice);
+ if (singlePageOrNull != null) {
+ assertEquals(sliceOffset, singlePageOrNull.offset);
}
}
@@ -109,7 +105,7 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
// bulk-read all
si.readFully(targetBuf);
- assertArrayEquals(pbr.toBytes(), targetBuf);
+ assertArrayEquals(BytesReference.toBytes(pbr), targetBuf);
// continuing to read should now fail with EOFException
try {
@@ -141,7 +137,7 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
// now do NOT reset the stream - keep the stream's offset!
// buffer to compare remaining bytes against bulk read
- byte[] pbrBytesWithOffset = Arrays.copyOfRange(pbr.toBytes(), offset, length);
+ byte[] pbrBytesWithOffset = Arrays.copyOfRange(BytesReference.toBytes(pbr), offset, length);
// randomized target buffer to ensure no stale slots
byte[] targetBytes = new byte[pbrBytesWithOffset.length];
random().nextBytes(targetBytes);
@@ -178,7 +174,7 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
}
assertEquals(pbr.length(), target.length());
BytesRef targetBytes = target.get();
- assertArrayEquals(pbr.toBytes(), Arrays.copyOfRange(targetBytes.bytes, targetBytes.offset, targetBytes.length));
+ assertArrayEquals(BytesReference.toBytes(pbr), Arrays.copyOfRange(targetBytes.bytes, targetBytes.offset, targetBytes.length));
}
public void testSliceStreamInput() throws IOException {
@@ -208,11 +204,11 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
assertEquals(sliceInput.available(), 0);
// compare slice content with upper half of original
- byte[] pbrSliceBytes = Arrays.copyOfRange(pbr.toBytes(), sliceOffset, length);
+ byte[] pbrSliceBytes = Arrays.copyOfRange(BytesReference.toBytes(pbr), sliceOffset, length);
assertArrayEquals(pbrSliceBytes, sliceBytes);
// compare slice bytes with bytes read from slice via streamInput :D
- byte[] sliceToBytes = slice.toBytes();
+ byte[] sliceToBytes = BytesReference.toBytes(slice);
assertEquals(sliceBytes.length, sliceToBytes.length);
assertArrayEquals(sliceBytes, sliceToBytes);
@@ -233,7 +229,7 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
pbr.writeTo(out);
assertEquals(pbr.length(), out.size());
- assertArrayEquals(pbr.toBytes(), out.bytes().toBytes());
+ assertArrayEquals(BytesReference.toBytes(pbr), BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -246,7 +242,7 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
BytesStreamOutput sliceOut = new BytesStreamOutput(sliceLength);
slice.writeTo(sliceOut);
assertEquals(slice.length(), sliceOut.size());
- assertArrayEquals(slice.toBytes(), sliceOut.bytes().toBytes());
+ assertArrayEquals(BytesReference.toBytes(slice), BytesReference.toBytes(sliceOut.bytes()));
sliceOut.close();
}
@@ -254,16 +250,16 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
int[] sizes = {0, randomInt(PAGE_SIZE), PAGE_SIZE, randomIntBetween(2, PAGE_SIZE * randomIntBetween(2, 5))};
for (int i = 0; i < sizes.length; i++) {
BytesReference pbr = newBytesReference(sizes[i]);
- byte[] bytes = pbr.toBytes();
+ byte[] bytes = BytesReference.toBytes(pbr);
assertEquals(sizes[i], bytes.length);
}
}
- public void testToBytesArraySharedPage() throws IOException {
+ public void testToBytesRefSharedPage() throws IOException {
int length = randomIntBetween(10, PAGE_SIZE);
BytesReference pbr = newBytesReference(length);
- BytesArray ba = pbr.toBytesArray();
- BytesArray ba2 = pbr.toBytesArray();
+ BytesArray ba = new BytesArray(pbr.toBytesRef());
+ BytesArray ba2 = new BytesArray(pbr.toBytesRef());
assertNotNull(ba);
assertNotNull(ba2);
assertEquals(pbr.length(), ba.length());
@@ -272,46 +268,46 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
assertSame(ba.array(), ba2.array());
}
- public void testToBytesArrayMaterializedPages() throws IOException {
+ public void testToBytesRefMaterializedPages() throws IOException {
// we need a length != (n * pagesize) to avoid page sharing at boundaries
int length = 0;
while ((length % PAGE_SIZE) == 0) {
length = randomIntBetween(PAGE_SIZE, PAGE_SIZE * randomIntBetween(2, 5));
}
BytesReference pbr = newBytesReference(length);
- BytesArray ba = pbr.toBytesArray();
- BytesArray ba2 = pbr.toBytesArray();
+ BytesArray ba = new BytesArray(pbr.toBytesRef());
+ BytesArray ba2 = new BytesArray(pbr.toBytesRef());
assertNotNull(ba);
assertNotNull(ba2);
assertEquals(pbr.length(), ba.length());
assertEquals(ba.length(), ba2.length());
}
- public void testCopyBytesArray() throws IOException {
+ public void testCopyBytesRefSharesBytes() throws IOException {
// small PBR which would normally share the first page
int length = randomIntBetween(10, PAGE_SIZE);
BytesReference pbr = newBytesReference(length);
- BytesArray ba = pbr.copyBytesArray();
- BytesArray ba2 = pbr.copyBytesArray();
+ BytesArray ba = new BytesArray(pbr.toBytesRef(), true);
+ BytesArray ba2 = new BytesArray(pbr.toBytesRef(), true);
assertNotNull(ba);
assertNotSame(ba, ba2);
assertNotSame(ba.array(), ba2.array());
}
- public void testSliceCopyBytesArray() throws IOException {
+ public void testSliceCopyBytesRef() throws IOException {
int length = randomIntBetween(10, PAGE_SIZE * randomIntBetween(2, 8));
BytesReference pbr = newBytesReference(length);
int sliceOffset = randomIntBetween(0, pbr.length());
- int sliceLength = randomIntBetween(pbr.length() - sliceOffset, pbr.length() - sliceOffset);
+ int sliceLength = randomIntBetween(0, pbr.length() - sliceOffset);
BytesReference slice = pbr.slice(sliceOffset, sliceLength);
- BytesArray ba1 = slice.copyBytesArray();
- BytesArray ba2 = slice.copyBytesArray();
+ BytesArray ba1 = new BytesArray(slice.toBytesRef(), true);
+ BytesArray ba2 = new BytesArray(slice.toBytesRef(), true);
assertNotNull(ba1);
assertNotNull(ba2);
assertNotSame(ba1.array(), ba2.array());
- assertArrayEquals(slice.toBytes(), ba1.array());
- assertArrayEquals(slice.toBytes(), ba2.array());
+ assertArrayEquals(BytesReference.toBytes(slice), ba1.array());
+ assertArrayEquals(BytesReference.toBytes(slice), ba2.array());
assertArrayEquals(ba1.array(), ba2.array());
}
@@ -329,14 +325,14 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
while((ref = iterator.next()) != null) {
builder.append(ref);
}
- assertArrayEquals(pbr.toBytes(), BytesRef.deepCopyOf(builder.toBytesRef()).bytes);
+ assertArrayEquals(BytesReference.toBytes(pbr), BytesRef.deepCopyOf(builder.toBytesRef()).bytes);
}
public void testSliceIterator() throws IOException {
int length = randomIntBetween(10, PAGE_SIZE * randomIntBetween(2, 8));
BytesReference pbr = newBytesReference(length);
int sliceOffset = randomIntBetween(0, pbr.length());
- int sliceLength = randomIntBetween(pbr.length() - sliceOffset, pbr.length() - sliceOffset);
+ int sliceLength = randomIntBetween(0, pbr.length() - sliceOffset);
BytesReference slice = pbr.slice(sliceOffset, sliceLength);
BytesRefIterator iterator = slice.iterator();
BytesRef ref = null;
@@ -344,7 +340,7 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
while((ref = iterator.next()) != null) {
builder.append(ref);
}
- assertArrayEquals(slice.toBytes(), BytesRef.deepCopyOf(builder.toBytesRef()).bytes);
+ assertArrayEquals(BytesReference.toBytes(slice), BytesRef.deepCopyOf(builder.toBytesRef()).bytes);
}
public void testIteratorRandom() throws IOException {
@@ -352,12 +348,12 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
BytesReference pbr = newBytesReference(length);
if (randomBoolean()) {
int sliceOffset = randomIntBetween(0, pbr.length());
- int sliceLength = randomIntBetween(pbr.length() - sliceOffset, pbr.length() - sliceOffset);
+ int sliceLength = randomIntBetween(0, pbr.length() - sliceOffset);
pbr = pbr.slice(sliceOffset, sliceLength);
}
if (randomBoolean()) {
- pbr = pbr.toBytesArray();
+ pbr = new BytesArray(pbr.toBytesRef());
}
BytesRefIterator iterator = pbr.iterator();
BytesRef ref = null;
@@ -365,29 +361,15 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
while((ref = iterator.next()) != null) {
builder.append(ref);
}
- assertArrayEquals(pbr.toBytes(), BytesRef.deepCopyOf(builder.toBytesRef()).bytes);
- }
-
- public void testArray() throws IOException {
- int[] sizes = {0, randomInt(PAGE_SIZE), PAGE_SIZE, randomIntBetween(2, PAGE_SIZE * randomIntBetween(2, 5))};
-
- for (int i = 0; i < sizes.length; i++) {
- BytesReference pbr = newBytesReference(sizes[i]);
- byte[] array = pbr.array();
- assertNotNull(array);
- assertEquals(sizes[i], array.length);
- assertSame(array, pbr.array());
- }
+ assertArrayEquals(BytesReference.toBytes(pbr), BytesRef.deepCopyOf(builder.toBytesRef()).bytes);
}
public void testArrayOffset() throws IOException {
int length = randomInt(PAGE_SIZE * randomIntBetween(2, 5));
BytesReference pbr = newBytesReference(length);
- if (pbr.hasArray()) {
- assertEquals(0, pbr.arrayOffset());
- } else {
- expectThrows(IllegalStateException.class, () ->
- pbr.arrayOffset());
+ BytesRef singlePageOrNull = getSinglePageOrNull(pbr);
+ if (singlePageOrNull != null) {
+ assertEquals(0, singlePageOrNull.offset);
}
}
@@ -395,20 +377,24 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
int length = randomInt(PAGE_SIZE * randomIntBetween(2, 5));
BytesReference pbr = newBytesReference(length);
int sliceOffset = randomIntBetween(0, pbr.length() - 1); // an offset to the end would be len 0
- int sliceLength = randomIntBetween(pbr.length() - sliceOffset, pbr.length() - sliceOffset);
+ int sliceLength = randomIntBetween(0, pbr.length() - sliceOffset);
BytesReference slice = pbr.slice(sliceOffset, sliceLength);
- if (slice.hasArray()) {
- assertEquals(sliceOffset, slice.arrayOffset());
- } else {
- expectThrows(IllegalStateException.class, () ->
- slice.arrayOffset());
+ BytesRef singlePageOrNull = getSinglePageOrNull(slice);
+ if (singlePageOrNull != null) {
+ if (getSinglePageOrNull(pbr) == null) {
+ // original reference has pages
+ assertEquals(sliceOffset % PAGE_SIZE, singlePageOrNull.offset);
+ } else {
+ // orig ref has no pages ie. BytesArray
+ assertEquals(sliceOffset, singlePageOrNull.offset);
+ }
}
}
public void testToUtf8() throws IOException {
// test empty
BytesReference pbr = newBytesReference(0);
- assertEquals("", pbr.toUtf8());
+ assertEquals("", pbr.utf8ToString());
// TODO: good way to test?
}
@@ -417,7 +403,6 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
BytesReference pbr = newBytesReference(length);
BytesRef ref = pbr.toBytesRef();
assertNotNull(ref);
- assertEquals(pbr.arrayOffset(), ref.offset);
assertEquals(pbr.length(), ref.length);
}
@@ -426,21 +411,13 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
BytesReference pbr = newBytesReference(length);
// get a BytesRef from a slice
int sliceOffset = randomIntBetween(0, pbr.length());
- int sliceLength = randomIntBetween(pbr.length() - sliceOffset, pbr.length() - sliceOffset);
+ int sliceLength = randomIntBetween(0, pbr.length() - sliceOffset);
BytesRef sliceRef = pbr.slice(sliceOffset, sliceLength).toBytesRef();
// note that these are only true if we have <= than a page, otherwise offset/length are shifted
assertEquals(sliceOffset, sliceRef.offset);
assertEquals(sliceLength, sliceRef.length);
}
- public void testCopyBytesRef() throws IOException {
- int length = randomIntBetween(0, PAGE_SIZE * randomIntBetween(2, 5));
- BytesReference pbr = newBytesReference(length);
- BytesRef ref = pbr.copyBytesRef();
- assertNotNull(ref);
- assertEquals(pbr.length(), ref.length);
- }
-
public void testHashCode() throws IOException {
// empty content must have hash 1 (JDK compat)
BytesReference pbr = newBytesReference(0);
@@ -448,40 +425,36 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
// test with content
pbr = newBytesReference(randomIntBetween(0, PAGE_SIZE * randomIntBetween(2, 5)));
- int jdkHash = Arrays.hashCode(pbr.toBytes());
+ int jdkHash = Arrays.hashCode(BytesReference.toBytes(pbr));
int pbrHash = pbr.hashCode();
assertEquals(jdkHash, pbrHash);
// test hashes of slices
int sliceFrom = randomIntBetween(0, pbr.length());
- int sliceLength = randomIntBetween(pbr.length() - sliceFrom, pbr.length() - sliceFrom);
+ int sliceLength = randomIntBetween(0, pbr.length() - sliceFrom);
BytesReference slice = pbr.slice(sliceFrom, sliceLength);
- int sliceJdkHash = Arrays.hashCode(slice.toBytes());
+ int sliceJdkHash = Arrays.hashCode(BytesReference.toBytes(slice));
int sliceHash = slice.hashCode();
assertEquals(sliceJdkHash, sliceHash);
}
- public void testEquals() {
- int length = randomIntBetween(100, PAGE_SIZE * randomIntBetween(2, 5));
- ByteArray ba1 = bigarrays.newByteArray(length, false);
- ByteArray ba2 = bigarrays.newByteArray(length, false);
-
- // copy contents
- for (long i = 0; i < length; i++) {
- ba2.set(i, ba1.get(i));
- }
+ public void testEquals() throws IOException {
+ BytesReference bytesReference = newBytesReference(randomIntBetween(100, PAGE_SIZE * randomIntBetween(2, 5)));
+ BytesReference copy = bytesReference.slice(0, bytesReference.length());
// get refs & compare
- BytesReference pbr = new PagedBytesReference(bigarrays, ba1, length);
- BytesReference pbr2 = new PagedBytesReference(bigarrays, ba2, length);
- assertEquals(pbr, pbr2);
- }
+ assertEquals(copy, bytesReference);
+ int sliceFrom = randomIntBetween(0, bytesReference.length());
+ int sliceLength = randomIntBetween(0, bytesReference.length() - sliceFrom);
+ assertEquals(copy.slice(sliceFrom, sliceLength), bytesReference.slice(sliceFrom, sliceLength));
- public void testEqualsPeerClass() throws IOException {
- int length = randomIntBetween(100, PAGE_SIZE * randomIntBetween(2, 5));
- BytesReference pbr = newBytesReference(length);
- BytesReference ba = new BytesArray(pbr.toBytes());
- assertEquals(pbr, ba);
+ BytesRef bytesRef = BytesRef.deepCopyOf(copy.toBytesRef());
+ assertEquals(new BytesArray(bytesRef), copy);
+
+ int offsetToFlip = randomIntBetween(0, bytesRef.length - 1);
+ int value = ~Byte.toUnsignedInt(bytesRef.bytes[bytesRef.offset+offsetToFlip]);
+ bytesRef.bytes[bytesRef.offset+offsetToFlip] = (byte)value;
+ assertNotEquals(new BytesArray(bytesRef), copy);
}
public void testSliceEquals() {
@@ -491,19 +464,118 @@ public abstract class AbstractBytesReferenceTestCase extends ESTestCase {
// test equality of slices
int sliceFrom = randomIntBetween(0, pbr.length());
- int sliceLength = randomIntBetween(pbr.length() - sliceFrom, pbr.length() - sliceFrom);
+ int sliceLength = randomIntBetween(0, pbr.length() - sliceFrom);
BytesReference slice1 = pbr.slice(sliceFrom, sliceLength);
BytesReference slice2 = pbr.slice(sliceFrom, sliceLength);
- assertArrayEquals(slice1.toBytes(), slice2.toBytes());
+ assertArrayEquals(BytesReference.toBytes(slice1), BytesReference.toBytes(slice2));
// test a slice with same offset but different length,
// unless randomized testing gave us a 0-length slice.
if (sliceLength > 0) {
BytesReference slice3 = pbr.slice(sliceFrom, sliceLength / 2);
- assertFalse(Arrays.equals(slice1.toBytes(), slice3.toBytes()));
+ assertFalse(Arrays.equals(BytesReference.toBytes(slice1), BytesReference.toBytes(slice3)));
}
}
protected abstract BytesReference newBytesReference(int length) throws IOException;
+ public void testCompareTo() throws IOException {
+ final int iters = randomIntBetween(5, 10);
+ for (int i = 0; i < iters; i++) {
+ int length = randomIntBetween(10, PAGE_SIZE * randomIntBetween(2, 8));
+ BytesReference bytesReference = newBytesReference(length);
+ assertTrue(bytesReference.compareTo(new BytesArray("")) > 0);
+ assertTrue(new BytesArray("").compareTo(bytesReference) < 0);
+
+
+ assertEquals(0, bytesReference.compareTo(bytesReference));
+ int sliceFrom = randomIntBetween(0, bytesReference.length());
+ int sliceLength = randomIntBetween(0, bytesReference.length() - sliceFrom);
+ BytesReference slice = bytesReference.slice(sliceFrom, sliceLength);
+
+ assertEquals(bytesReference.toBytesRef().compareTo(slice.toBytesRef()),
+ new BytesArray(bytesReference.toBytesRef(), true).compareTo(new BytesArray(slice.toBytesRef(), true)));
+
+ assertEquals(bytesReference.toBytesRef().compareTo(slice.toBytesRef()),
+ bytesReference.compareTo(slice));
+ assertEquals(slice.toBytesRef().compareTo(bytesReference.toBytesRef()),
+ slice.compareTo(bytesReference));
+
+ assertEquals(0, slice.compareTo(new BytesArray(slice.toBytesRef())));
+ assertEquals(0, new BytesArray(slice.toBytesRef()).compareTo(slice));
+
+ final int crazyLength = length + randomIntBetween(10, PAGE_SIZE * randomIntBetween(2, 8));
+ ReleasableBytesStreamOutput crazyStream = new ReleasableBytesStreamOutput(length, bigarrays);
+ final int offset = randomIntBetween(0, crazyLength - length);
+ for (int j = 0; j < offset; j++) {
+ crazyStream.writeByte((byte) random().nextInt(1 << 8));
+ }
+ bytesReference.writeTo(crazyStream);
+ for (int j = crazyStream.size(); j < crazyLength; j++) {
+ crazyStream.writeByte((byte) random().nextInt(1 << 8));
+ }
+ PagedBytesReference crazyReference = crazyStream.bytes();
+
+ assertFalse(crazyReference.compareTo(bytesReference) == 0);
+ assertEquals(0, crazyReference.slice(offset, length).compareTo(
+ bytesReference));
+ assertEquals(0, bytesReference.compareTo(
+ crazyReference.slice(offset, length)));
+ }
+ }
+
+ public static BytesRef getSinglePageOrNull(BytesReference ref) throws IOException {
+ if (ref.length() > 0) {
+ BytesRefIterator iterator = ref.iterator();
+ BytesRef next = iterator.next();
+ BytesRef retVal = next.clone();
+ if (iterator.next() == null) {
+ return retVal;
+ }
+ } else {
+ return new BytesRef();
+ }
+ return null;
+ }
+
+ public static int getNumPages(BytesReference ref) throws IOException {
+ int num = 0;
+ if (ref.length() > 0) {
+ BytesRefIterator iterator = ref.iterator();
+ while(iterator.next() != null) {
+ num++;
+ }
+ }
+ return num;
+ }
+
+
+ public void testBasicEquals() {
+ final int len = randomIntBetween(0, randomBoolean() ? 10: 100000);
+ final int offset1 = randomInt(5);
+ final byte[] array1 = new byte[offset1 + len + randomInt(5)];
+ random().nextBytes(array1);
+ final int offset2 = randomInt(offset1);
+ final byte[] array2 = Arrays.copyOfRange(array1, offset1 - offset2, array1.length);
+
+ final BytesArray b1 = new BytesArray(array1, offset1, len);
+ final BytesArray b2 = new BytesArray(array2, offset2, len);
+ assertEquals(b1, b2);
+ assertEquals(Arrays.hashCode(BytesReference.toBytes(b1)), b1.hashCode());
+ assertEquals(Arrays.hashCode(BytesReference.toBytes(b2)), b2.hashCode());
+
+ // test same instance
+ assertEquals(b1, b1);
+ assertEquals(b2, b2);
+
+ if (len > 0) {
+ // test different length
+ BytesArray differentLen = new BytesArray(array1, offset1, randomInt(len - 1));
+ assertNotEquals(b1, differentLen);
+
+ // test changed bytes
+ array1[offset1 + randomInt(len - 1)] += 13;
+ assertNotEquals(b1, b2);
+ }
+ }
}
diff --git a/core/src/test/java/org/elasticsearch/common/bytes/BytesArrayTests.java b/core/src/test/java/org/elasticsearch/common/bytes/BytesArrayTests.java
index 61d24ef44c3..fff030200b7 100644
--- a/core/src/test/java/org/elasticsearch/common/bytes/BytesArrayTests.java
+++ b/core/src/test/java/org/elasticsearch/common/bytes/BytesArrayTests.java
@@ -32,10 +32,28 @@ public class BytesArrayTests extends AbstractBytesReferenceTestCase {
out.writeByte((byte) random().nextInt(1 << 8));
}
assertEquals(length, out.size());
- BytesArray ref = out.bytes().toBytesArray();
+ BytesArray ref = new BytesArray(out.bytes().toBytesRef());
assertEquals(length, ref.length());
assertTrue(ref instanceof BytesArray);
assertThat(ref.length(), Matchers.equalTo(length));
return ref;
}
+
+ public void testArray() throws IOException {
+ int[] sizes = {0, randomInt(PAGE_SIZE), PAGE_SIZE, randomIntBetween(2, PAGE_SIZE * randomIntBetween(2, 5))};
+
+ for (int i = 0; i < sizes.length; i++) {
+ BytesArray pbr = (BytesArray) newBytesReference(sizes[i]);
+ byte[] array = pbr.array();
+ assertNotNull(array);
+ assertEquals(sizes[i], array.length);
+ assertSame(array, pbr.array());
+ }
+ }
+
+ public void testArrayOffset() throws IOException {
+ int length = randomInt(PAGE_SIZE * randomIntBetween(2, 5));
+ BytesArray pbr = (BytesArray) newBytesReference(length);
+ assertEquals(0, pbr.offset());
+ }
}
diff --git a/core/src/test/java/org/elasticsearch/common/bytes/BytesReferenceTests.java b/core/src/test/java/org/elasticsearch/common/bytes/BytesReferenceTests.java
deleted file mode 100644
index 60f4983dd19..00000000000
--- a/core/src/test/java/org/elasticsearch/common/bytes/BytesReferenceTests.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * 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.
- */
-
-package org.elasticsearch.common.bytes;
-
-
-import org.elasticsearch.test.ESTestCase;
-
-import java.util.Arrays;
-
-public class BytesReferenceTests extends ESTestCase {
-
- public void testEquals() {
- final int len = randomIntBetween(0, randomBoolean() ? 10: 100000);
- final int offset1 = randomInt(5);
- final byte[] array1 = new byte[offset1 + len + randomInt(5)];
- random().nextBytes(array1);
- final int offset2 = randomInt(offset1);
- final byte[] array2 = Arrays.copyOfRange(array1, offset1 - offset2, array1.length);
-
- final BytesArray b1 = new BytesArray(array1, offset1, len);
- final BytesArray b2 = new BytesArray(array2, offset2, len);
- assertTrue(BytesReference.Helper.bytesEqual(b1, b2));
- assertTrue(BytesReference.Helper.bytesEquals(b1, b2));
- assertEquals(Arrays.hashCode(b1.toBytes()), b1.hashCode());
- assertEquals(BytesReference.Helper.bytesHashCode(b1), BytesReference.Helper.slowHashCode(b2));
-
- // test same instance
- assertTrue(BytesReference.Helper.bytesEqual(b1, b1));
- assertTrue(BytesReference.Helper.bytesEquals(b1, b1));
- assertEquals(BytesReference.Helper.bytesHashCode(b1), BytesReference.Helper.slowHashCode(b1));
-
- if (len > 0) {
- // test different length
- BytesArray differentLen = new BytesArray(array1, offset1, randomInt(len - 1));
- assertFalse(BytesReference.Helper.bytesEqual(b1, differentLen));
-
- // test changed bytes
- array1[offset1 + randomInt(len - 1)] += 13;
- assertFalse(BytesReference.Helper.bytesEqual(b1, b2));
- assertFalse(BytesReference.Helper.bytesEquals(b1, b2));
- }
- }
-
-}
diff --git a/core/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java b/core/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java
index 5a299d82de8..6ae2b3cf943 100644
--- a/core/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java
+++ b/core/src/test/java/org/elasticsearch/common/bytes/PagedBytesReferenceTests.java
@@ -50,15 +50,15 @@ public class PagedBytesReferenceTests extends AbstractBytesReferenceTestCase {
return ref;
}
- public void testToBytesArrayMaterializedPages() throws IOException {
+ public void testToBytesRefMaterializedPages() throws IOException {
// we need a length != (n * pagesize) to avoid page sharing at boundaries
int length = 0;
while ((length % PAGE_SIZE) == 0) {
length = randomIntBetween(PAGE_SIZE, PAGE_SIZE * randomIntBetween(2, 5));
}
BytesReference pbr = newBytesReference(length);
- BytesArray ba = pbr.toBytesArray();
- BytesArray ba2 = pbr.toBytesArray();
+ BytesArray ba = new BytesArray(pbr.toBytesRef());
+ BytesArray ba2 = new BytesArray(pbr.toBytesRef());
assertNotNull(ba);
assertNotNull(ba2);
assertEquals(pbr.length(), ba.length());
@@ -67,23 +67,23 @@ public class PagedBytesReferenceTests extends AbstractBytesReferenceTestCase {
assertNotSame(ba.array(), ba2.array());
}
- public void testArray() throws IOException {
+ public void testSinglePage() throws IOException {
int[] sizes = {0, randomInt(PAGE_SIZE), PAGE_SIZE, randomIntBetween(2, PAGE_SIZE * randomIntBetween(2, 5))};
for (int i = 0; i < sizes.length; i++) {
BytesReference pbr = newBytesReference(sizes[i]);
// verify that array() is cheap for small payloads
if (sizes[i] <= PAGE_SIZE) {
- byte[] array = pbr.array();
+ BytesRef page = getSinglePageOrNull(pbr);
+ assertNotNull(page);
+ byte[] array = page.bytes;
assertNotNull(array);
assertEquals(sizes[i], array.length);
- assertSame(array, pbr.array());
+ assertSame(array, page.bytes);
} else {
- try {
- pbr.array();
- fail("expected IllegalStateException");
- } catch (IllegalStateException isx) {
- // expected
+ BytesRef page = getSinglePageOrNull(pbr);
+ if (pbr.length() > 0) {
+ assertNull(page);
}
}
}
@@ -94,22 +94,42 @@ public class PagedBytesReferenceTests extends AbstractBytesReferenceTestCase {
for (int i = 0; i < sizes.length; i++) {
BytesReference pbr = newBytesReference(sizes[i]);
- byte[] bytes = pbr.toBytes();
+ byte[] bytes = BytesReference.toBytes(pbr);
assertEquals(sizes[i], bytes.length);
// verify that toBytes() is cheap for small payloads
if (sizes[i] <= PAGE_SIZE) {
- assertSame(bytes, pbr.toBytes());
+ assertSame(bytes, BytesReference.toBytes(pbr));
} else {
- assertNotSame(bytes, pbr.toBytes());
+ assertNotSame(bytes, BytesReference.toBytes(pbr));
}
}
}
- public void testHasArray() throws IOException {
+ public void testHasSinglePage() throws IOException {
int length = randomIntBetween(10, PAGE_SIZE * randomIntBetween(1, 3));
BytesReference pbr = newBytesReference(length);
// must return true for <= pagesize
- assertEquals(length <= PAGE_SIZE, pbr.hasArray());
+ assertEquals(length <= PAGE_SIZE, getNumPages(pbr) == 1);
+ }
+
+ public void testEquals() {
+ int length = randomIntBetween(100, PAGE_SIZE * randomIntBetween(2, 5));
+ ByteArray ba1 = bigarrays.newByteArray(length, false);
+ ByteArray ba2 = bigarrays.newByteArray(length, false);
+
+ // copy contents
+ for (long i = 0; i < length; i++) {
+ ba2.set(i, ba1.get(i));
+ }
+
+ // get refs & compare
+ BytesReference pbr = new PagedBytesReference(bigarrays, ba1, length);
+ BytesReference pbr2 = new PagedBytesReference(bigarrays, ba2, length);
+ assertEquals(pbr, pbr2);
+ int offsetToFlip = randomIntBetween(0, length - 1);
+ int value = ~Byte.toUnsignedInt(ba1.get(offsetToFlip));
+ ba2.set(offsetToFlip, (byte)value);
+ assertNotEquals(pbr, pbr2);
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java b/core/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java
index 72866d082ae..0ce95077965 100644
--- a/core/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java
+++ b/core/src/test/java/org/elasticsearch/common/compress/DeflateCompressedXContentTests.java
@@ -91,8 +91,8 @@ public class DeflateCompressedXContentTests extends ESTestCase {
// of different size are being used
assertFalse(b1.equals(b2));
// we used the compressed representation directly and did not recompress
- assertArrayEquals(b1.toBytes(), new CompressedXContent(b1).compressed());
- assertArrayEquals(b2.toBytes(), new CompressedXContent(b2).compressed());
+ assertArrayEquals(BytesReference.toBytes(b1), new CompressedXContent(b1).compressed());
+ assertArrayEquals(BytesReference.toBytes(b2), new CompressedXContent(b2).compressed());
// but compressedstring instances are still equal
assertEquals(new CompressedXContent(b1), new CompressedXContent(b2));
}
diff --git a/core/src/test/java/org/elasticsearch/common/geo/GeoDistanceTests.java b/core/src/test/java/org/elasticsearch/common/geo/GeoDistanceTests.java
index 407c9790dbe..416299f8e7e 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/GeoDistanceTests.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/GeoDistanceTests.java
@@ -46,7 +46,7 @@ public class GeoDistanceTests extends ESTestCase {
GeoDistance geoDistance = randomFrom(GeoDistance.PLANE, GeoDistance.FACTOR, GeoDistance.ARC, GeoDistance.SLOPPY_ARC);
try (BytesStreamOutput out = new BytesStreamOutput()) {
geoDistance.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {;
+ try (StreamInput in = out.bytes().streamInput()) {;
GeoDistance copy = GeoDistance.readFromStream(in);
assertEquals(copy.toString() + " vs. " + geoDistance.toString(), copy, geoDistance);
}
@@ -60,7 +60,7 @@ public class GeoDistanceTests extends ESTestCase {
} else {
out.writeVInt(randomIntBetween(Integer.MIN_VALUE, -1));
}
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
GeoDistance.readFromStream(in);
} catch (IOException e) {
assertThat(e.getMessage(), containsString("Unknown GeoDistance ordinal ["));
diff --git a/core/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java b/core/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java
index 566d2148cae..76376a4d30d 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/GeoJSONShapeParserTests.java
@@ -56,7 +56,7 @@ import static org.elasticsearch.common.geo.builders.ShapeBuilder.SPATIAL_CONTEXT
*/
public class GeoJSONShapeParserTests extends ESTestCase {
- private final static GeometryFactory GEOMETRY_FACTORY = SPATIAL_CONTEXT.getGeometryFactory();
+ private static final GeometryFactory GEOMETRY_FACTORY = SPATIAL_CONTEXT.getGeometryFactory();
public void testParse_simplePoint() throws IOException {
String pointGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "Point")
diff --git a/core/src/test/java/org/elasticsearch/common/geo/ShapeRelationTests.java b/core/src/test/java/org/elasticsearch/common/geo/ShapeRelationTests.java
index 6ee6a4fff83..e4eaa17874c 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/ShapeRelationTests.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/ShapeRelationTests.java
@@ -39,21 +39,21 @@ public class ShapeRelationTests extends ESTestCase {
public void testwriteTo() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
ShapeRelation.INTERSECTS.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(0));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
ShapeRelation.DISJOINT.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(1));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
ShapeRelation.WITHIN.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(2));
}
}
@@ -62,19 +62,19 @@ public class ShapeRelationTests extends ESTestCase {
public void testReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(0);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(ShapeRelation.readFromStream(in), equalTo(ShapeRelation.INTERSECTS));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(1);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(ShapeRelation.readFromStream(in), equalTo(ShapeRelation.DISJOINT));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(2);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(ShapeRelation.readFromStream(in), equalTo(ShapeRelation.WITHIN));
}
}
@@ -83,7 +83,7 @@ public class ShapeRelationTests extends ESTestCase {
public void testInvalidReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(randomIntBetween(3, Integer.MAX_VALUE));
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
ShapeRelation.readFromStream(in);
fail("Expected IOException");
} catch(IOException e) {
diff --git a/core/src/test/java/org/elasticsearch/common/geo/SpatialStrategyTests.java b/core/src/test/java/org/elasticsearch/common/geo/SpatialStrategyTests.java
index c2f29e6ecd7..b6eae97932f 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/SpatialStrategyTests.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/SpatialStrategyTests.java
@@ -38,14 +38,14 @@ public class SpatialStrategyTests extends ESTestCase {
public void testwriteTo() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
SpatialStrategy.TERM.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(0));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
SpatialStrategy.RECURSIVE.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(1));
}
}
@@ -54,13 +54,13 @@ public class SpatialStrategyTests extends ESTestCase {
public void testReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(0);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(SpatialStrategy.readFromStream(in), equalTo(SpatialStrategy.TERM));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(1);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(SpatialStrategy.readFromStream(in), equalTo(SpatialStrategy.RECURSIVE));
}
}
@@ -69,7 +69,7 @@ public class SpatialStrategyTests extends ESTestCase {
public void testInvalidReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(randomIntBetween(2, Integer.MAX_VALUE));
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
SpatialStrategy.readFromStream(in);
fail("Expected IOException");
} catch(IOException e) {
diff --git a/core/src/test/java/org/elasticsearch/common/geo/builders/AbstractShapeBuilderTestCase.java b/core/src/test/java/org/elasticsearch/common/geo/builders/AbstractShapeBuilderTestCase.java
index 9cbd4bb769d..4003a96e26f 100644
--- a/core/src/test/java/org/elasticsearch/common/geo/builders/AbstractShapeBuilderTestCase.java
+++ b/core/src/test/java/org/elasticsearch/common/geo/builders/AbstractShapeBuilderTestCase.java
@@ -137,7 +137,7 @@ public abstract class AbstractShapeBuilderTestCase exte
static ShapeBuilder copyShape(ShapeBuilder original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
return namedWriteableRegistry.getReader(ShapeBuilder.class, original.getWriteableName()).read(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/io/StreamsTests.java b/core/src/test/java/org/elasticsearch/common/io/StreamsTests.java
index 5c6c1e1789b..76b52c08a85 100644
--- a/core/src/test/java/org/elasticsearch/common/io/StreamsTests.java
+++ b/core/src/test/java/org/elasticsearch/common/io/StreamsTests.java
@@ -84,7 +84,7 @@ public class StreamsTests extends ESTestCase {
byte stuff[] = new byte[] { 0, 1, 2, 3 };
BytesRef stuffRef = new BytesRef(stuff, 2, 2);
BytesArray stuffArray = new BytesArray(stuffRef);
- StreamInput input = StreamInput.wrap(stuffArray);
+ StreamInput input = stuffArray.streamInput();
assertEquals(2, input.read());
assertEquals(3, input.read());
assertEquals(-1, input.read());
diff --git a/core/src/test/java/org/elasticsearch/common/io/stream/AbstractWriteableEnumTestCase.java b/core/src/test/java/org/elasticsearch/common/io/stream/AbstractWriteableEnumTestCase.java
index a4d15173a7c..dc57b0c70d4 100644
--- a/core/src/test/java/org/elasticsearch/common/io/stream/AbstractWriteableEnumTestCase.java
+++ b/core/src/test/java/org/elasticsearch/common/io/stream/AbstractWriteableEnumTestCase.java
@@ -60,7 +60,7 @@ public abstract class AbstractWriteableEnumTestCase extends ESTestCase {
protected static void assertWriteToStream(final Writeable writeableEnum, final int ordinal) throws IOException {
try (BytesStreamOutput out = new BytesStreamOutput()) {
writeableEnum.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(ordinal));
}
}
@@ -70,7 +70,7 @@ public abstract class AbstractWriteableEnumTestCase extends ESTestCase {
protected void assertReadFromStream(final int ordinal, final Writeable expected) throws IOException {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(ordinal);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(reader.read(in), equalTo(expected));
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java b/core/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java
index 9fcbb708156..94f07369770 100644
--- a/core/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java
+++ b/core/src/test/java/org/elasticsearch/common/io/stream/BytesStreamsTests.java
@@ -21,6 +21,7 @@ package org.elasticsearch.common.io.stream;
import org.apache.lucene.util.Constants;
import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.common.util.BigArrays;
@@ -48,7 +49,7 @@ public class BytesStreamsTests extends ESTestCase {
// test empty stream to array
assertEquals(0, out.size());
- assertEquals(0, out.bytes().toBytes().length);
+ assertEquals(0, out.bytes().length());
out.close();
}
@@ -63,7 +64,7 @@ public class BytesStreamsTests extends ESTestCase {
// write single byte
out.writeByte(expectedData[0]);
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -80,7 +81,7 @@ public class BytesStreamsTests extends ESTestCase {
}
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -108,14 +109,14 @@ public class BytesStreamsTests extends ESTestCase {
byte[] expectedData = randomizedByteArrayWithSize(expectedSize);
out.writeBytes(expectedData);
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
// bulk-write again with actual bytes
expectedSize = 10;
expectedData = randomizedByteArrayWithSize(expectedSize);
out.writeBytes(expectedData);
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -130,7 +131,7 @@ public class BytesStreamsTests extends ESTestCase {
out.writeBytes(expectedData);
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -149,7 +150,7 @@ public class BytesStreamsTests extends ESTestCase {
// now write the rest - more than fits into the remaining first page
out.writeBytes(expectedData, initialOffset, additionalLength);
assertEquals(expectedData.length, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -168,7 +169,7 @@ public class BytesStreamsTests extends ESTestCase {
// ie. we cross over into a third
out.writeBytes(expectedData, initialOffset, additionalLength);
assertEquals(expectedData.length, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -185,7 +186,7 @@ public class BytesStreamsTests extends ESTestCase {
}
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -202,7 +203,7 @@ public class BytesStreamsTests extends ESTestCase {
}
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -219,7 +220,7 @@ public class BytesStreamsTests extends ESTestCase {
}
assertEquals(expectedSize, out.size());
- assertArrayEquals(expectedData, out.bytes().toBytes());
+ assertArrayEquals(expectedData, BytesReference.toBytes(out.bytes()));
out.close();
}
@@ -235,7 +236,7 @@ public class BytesStreamsTests extends ESTestCase {
out.seek(position += BigArrays.BYTE_PAGE_SIZE + 10);
out.seek(position += BigArrays.BYTE_PAGE_SIZE * 2);
assertEquals(position, out.position());
- assertEquals(position, out.bytes().toBytes().length);
+ assertEquals(position, BytesReference.toBytes(out.bytes()).length);
out.close();
}
@@ -288,8 +289,8 @@ public class BytesStreamsTests extends ESTestCase {
out.writeTimeZone(DateTimeZone.forID("CET"));
out.writeOptionalTimeZone(DateTimeZone.getDefault());
out.writeOptionalTimeZone(null);
- final byte[] bytes = out.bytes().toBytes();
- StreamInput in = StreamInput.wrap(out.bytes().toBytes());
+ final byte[] bytes = BytesReference.toBytes(out.bytes());
+ StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
assertEquals(in.available(), bytes.length);
assertThat(in.readBoolean(), equalTo(false));
assertThat(in.readByte(), equalTo((byte)1));
@@ -328,7 +329,7 @@ public class BytesStreamsTests extends ESTestCase {
namedWriteableRegistry.register(BaseNamedWriteable.class, TestNamedWriteable.NAME, TestNamedWriteable::new);
TestNamedWriteable namedWriteableIn = new TestNamedWriteable(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
out.writeNamedWriteable(namedWriteableIn);
- byte[] bytes = out.bytes().toBytes();
+ byte[] bytes = BytesReference.toBytes(out.bytes());
StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(bytes), namedWriteableRegistry);
assertEquals(in.available(), bytes.length);
BaseNamedWriteable namedWriteableOut = in.readNamedWriteable(BaseNamedWriteable.class);
@@ -348,7 +349,7 @@ public class BytesStreamsTests extends ESTestCase {
public void testNamedWriteableUnknownCategory() throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
out.writeNamedWriteable(new TestNamedWriteable("test1", "test2"));
- StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes().toBytes()), new NamedWriteableRegistry());
+ StreamInput in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), new NamedWriteableRegistry());
//no named writeable registered with given name, can write but cannot read it back
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> in.readNamedWriteable(BaseNamedWriteable.class));
assertThat(e.getMessage(), equalTo("unknown named writeable category [" + BaseNamedWriteable.class.getName() + "]"));
@@ -368,7 +369,7 @@ public class BytesStreamsTests extends ESTestCase {
public void writeTo(StreamOutput out) throws IOException {
}
});
- StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes().toBytes()), namedWriteableRegistry);
+ StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(BytesReference.toBytes(out.bytes())), namedWriteableRegistry);
try {
//no named writeable registered with given name under test category, can write but cannot read it back
in.readNamedWriteable(BaseNamedWriteable.class);
@@ -382,7 +383,7 @@ public class BytesStreamsTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
TestNamedWriteable testNamedWriteable = new TestNamedWriteable("test1", "test2");
out.writeNamedWriteable(testNamedWriteable);
- StreamInput in = StreamInput.wrap(out.bytes().toBytes());
+ StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
try {
in.readNamedWriteable(BaseNamedWriteable.class);
fail("Expected UnsupportedOperationException");
@@ -397,7 +398,7 @@ public class BytesStreamsTests extends ESTestCase {
namedWriteableRegistry.register(BaseNamedWriteable.class, TestNamedWriteable.NAME, (StreamInput in) -> null);
TestNamedWriteable namedWriteableIn = new TestNamedWriteable(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
out.writeNamedWriteable(namedWriteableIn);
- byte[] bytes = out.bytes().toBytes();
+ byte[] bytes = BytesReference.toBytes(out.bytes());
StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(bytes), namedWriteableRegistry);
assertEquals(in.available(), bytes.length);
IOException e = expectThrows(IOException.class, () -> in.readNamedWriteable(BaseNamedWriteable.class));
@@ -407,7 +408,7 @@ public class BytesStreamsTests extends ESTestCase {
public void testOptionalWriteableReaderReturnsNull() throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
out.writeOptionalWriteable(new TestNamedWriteable(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10)));
- StreamInput in = StreamInput.wrap(out.bytes().toBytes());
+ StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
IOException e = expectThrows(IOException.class, () -> in.readOptionalWriteable((StreamInput ignored) -> null));
assertThat(e.getMessage(), endsWith("] returned null which is not allowed and probably means it screwed up the stream."));
}
@@ -423,7 +424,7 @@ public class BytesStreamsTests extends ESTestCase {
});
TestNamedWriteable namedWriteableIn = new TestNamedWriteable(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
out.writeNamedWriteable(namedWriteableIn);
- byte[] bytes = out.bytes().toBytes();
+ byte[] bytes = BytesReference.toBytes(out.bytes());
StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(bytes), namedWriteableRegistry);
assertEquals(in.available(), bytes.length);
AssertionError e = expectThrows(AssertionError.class, () -> in.readNamedWriteable(BaseNamedWriteable.class));
@@ -442,7 +443,7 @@ public class BytesStreamsTests extends ESTestCase {
final BytesStreamOutput out = new BytesStreamOutput();
out.writeStreamableList(expected);
- final StreamInput in = StreamInput.wrap(out.bytes().toBytes());
+ final StreamInput in = StreamInput.wrap(BytesReference.toBytes(out.bytes()));
List loaded = in.readStreamableList(TestStreamable::new);
@@ -458,7 +459,7 @@ public class BytesStreamsTests extends ESTestCase {
out.close();
}
- private static abstract class BaseNamedWriteable implements NamedWriteable {
+ private abstract static class BaseNamedWriteable implements NamedWriteable {
}
@@ -537,7 +538,7 @@ public class BytesStreamsTests extends ESTestCase {
// toByteArray() must fail
try {
- out.bytes().toBytes();
+ BytesReference.toBytes(out.bytes());
fail("expected IllegalStateException: stream closed");
}
catch (IllegalStateException iex1) {
@@ -558,7 +559,7 @@ public class BytesStreamsTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
GeoPoint geoPoint = new GeoPoint(randomDouble(), randomDouble());
out.writeGenericValue(geoPoint);
- StreamInput wrap = StreamInput.wrap(out.bytes());
+ StreamInput wrap = out.bytes().streamInput();
GeoPoint point = (GeoPoint) wrap.readGenericValue();
assertEquals(point, geoPoint);
}
@@ -566,7 +567,7 @@ public class BytesStreamsTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
GeoPoint geoPoint = new GeoPoint(randomDouble(), randomDouble());
out.writeGeoPoint(geoPoint);
- StreamInput wrap = StreamInput.wrap(out.bytes());
+ StreamInput wrap = out.bytes().streamInput();
GeoPoint point = wrap.readGeoPoint();
assertEquals(point, geoPoint);
}
diff --git a/core/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java b/core/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java
index aa6016774b0..06d39398c8e 100644
--- a/core/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java
+++ b/core/src/test/java/org/elasticsearch/common/io/stream/StreamTests.java
@@ -19,13 +19,13 @@
package org.elasticsearch.common.io.stream;
-import org.elasticsearch.common.bytes.ByteBufferBytesReference;
+import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.test.ESTestCase;
import java.io.ByteArrayInputStream;
import java.io.IOException;
-import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
@@ -61,8 +61,8 @@ public class StreamTests extends ESTestCase {
for (Tuple value : values) {
BytesStreamOutput out = new BytesStreamOutput();
out.writeZLong(value.v1());
- assertArrayEquals(Long.toString(value.v1()), value.v2(), out.bytes().toBytes());
- ByteBufferBytesReference bytes = new ByteBufferBytesReference(ByteBuffer.wrap(value.v2()));
+ assertArrayEquals(Long.toString(value.v1()), value.v2(), BytesReference.toBytes(out.bytes()));
+ BytesReference bytes = new BytesArray(value.v2());
assertEquals(Arrays.toString(value.v2()), (long)value.v1(), bytes.streamInput().readZLong());
}
}
@@ -143,7 +143,7 @@ public class StreamTests extends ESTestCase {
assertThat(targetArray, equalTo(sourceArray));
}
- final static class WriteableString implements Writeable {
+ static final class WriteableString implements Writeable {
final String string;
public WriteableString(String string) {
diff --git a/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java b/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java
index 9ae0beadf59..245520d65f3 100644
--- a/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java
+++ b/core/src/test/java/org/elasticsearch/common/network/NetworkModuleTests.java
@@ -95,7 +95,7 @@ public class NetworkModuleTests extends ModuleTestCase {
static class FakeCatRestHandler extends AbstractCatAction {
public FakeCatRestHandler() {
- super(null, null);
+ super(null);
}
@Override
protected void doRequest(RestRequest request, RestChannel channel, NodeClient client) {}
diff --git a/core/src/test/java/org/elasticsearch/common/transport/BoundTransportAddressTests.java b/core/src/test/java/org/elasticsearch/common/transport/BoundTransportAddressTests.java
index 45db5a33d21..1a3fa4db137 100644
--- a/core/src/test/java/org/elasticsearch/common/transport/BoundTransportAddressTests.java
+++ b/core/src/test/java/org/elasticsearch/common/transport/BoundTransportAddressTests.java
@@ -51,7 +51,7 @@ public class BoundTransportAddressTests extends ESTestCase {
// serialize
BytesStreamOutput streamOutput = new BytesStreamOutput();
transportAddress.writeTo(streamOutput);
- StreamInput in = ByteBufferStreamInput.wrap(streamOutput.bytes());
+ StreamInput in = streamOutput.bytes().streamInput();
BoundTransportAddress serializedAddress;
if (randomBoolean()) {
diff --git a/core/src/test/java/org/elasticsearch/common/unit/DistanceUnitTests.java b/core/src/test/java/org/elasticsearch/common/unit/DistanceUnitTests.java
index f9a4d3f22af..7c5463baed2 100644
--- a/core/src/test/java/org/elasticsearch/common/unit/DistanceUnitTests.java
+++ b/core/src/test/java/org/elasticsearch/common/unit/DistanceUnitTests.java
@@ -82,7 +82,7 @@ public class DistanceUnitTests extends ESTestCase {
for (DistanceUnit unit : DistanceUnit.values()) {
try (BytesStreamOutput out = new BytesStreamOutput()) {
unit.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat("Roundtrip serialisation failed.", DistanceUnit.readFromStream(in), equalTo(unit));
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java b/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java
index 2b5a7c00e5d..3f6f1848fd8 100644
--- a/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java
+++ b/core/src/test/java/org/elasticsearch/common/unit/FuzzinessTests.java
@@ -145,7 +145,7 @@ public class FuzzinessTests extends ESTestCase {
private static Fuzziness doSerializeRoundtrip(Fuzziness in) throws IOException {
BytesStreamOutput output = new BytesStreamOutput();
in.writeTo(output);
- StreamInput streamInput = StreamInput.wrap(output.bytes());
+ StreamInput streamInput = output.bytes().streamInput();
return new Fuzziness(streamInput);
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/unit/TimeValueTests.java b/core/src/test/java/org/elasticsearch/common/unit/TimeValueTests.java
index 78afc9e514f..003d78ce42e 100644
--- a/core/src/test/java/org/elasticsearch/common/unit/TimeValueTests.java
+++ b/core/src/test/java/org/elasticsearch/common/unit/TimeValueTests.java
@@ -161,7 +161,7 @@ public class TimeValueTests extends ESTestCase {
value.writeTo(out);
assertEquals(expectedSize, out.size());
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
TimeValue inValue = new TimeValue(in);
assertThat(inValue, equalTo(value));
diff --git a/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java b/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java
index 1a582d48f6b..d6797d4be26 100644
--- a/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java
+++ b/core/src/test/java/org/elasticsearch/common/util/concurrent/ThreadContextTests.java
@@ -154,7 +154,7 @@ public class ThreadContextTests extends ESTestCase {
assertNull(threadContext.getTransient("ctx.foo"));
assertEquals("1", threadContext.getHeader("default"));
- threadContext.readHeaders(StreamInput.wrap(out.bytes()));
+ threadContext.readHeaders(out.bytes().streamInput());
assertEquals("bar", threadContext.getHeader("foo"));
assertNull(threadContext.getTransient("ctx.foo"));
}
@@ -179,14 +179,14 @@ public class ThreadContextTests extends ESTestCase {
{
Settings otherSettings = Settings.builder().put("request.headers.default", "5").build();
ThreadContext otherhreadContext = new ThreadContext(otherSettings);
- otherhreadContext.readHeaders(StreamInput.wrap(out.bytes()));
+ otherhreadContext.readHeaders(out.bytes().streamInput());
assertEquals("bar", otherhreadContext.getHeader("foo"));
assertNull(otherhreadContext.getTransient("ctx.foo"));
assertEquals("1", otherhreadContext.getHeader("default"));
}
}
-
+
public void testSerializeInDifferentContextNoDefaults() throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
{
@@ -202,7 +202,7 @@ public class ThreadContextTests extends ESTestCase {
{
Settings otherSettings = Settings.builder().put("request.headers.default", "5").build();
ThreadContext otherhreadContext = new ThreadContext(otherSettings);
- otherhreadContext.readHeaders(StreamInput.wrap(out.bytes()));
+ otherhreadContext.readHeaders(out.bytes().streamInput());
assertEquals("bar", otherhreadContext.getHeader("foo"));
assertNull(otherhreadContext.getTransient("ctx.foo"));
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java
index 159d8a97be4..a8d26e87ecf 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java
@@ -35,7 +35,7 @@ import org.elasticsearch.test.ESTestCase;
public class ObjectParserTests extends ESTestCase {
- private final static ParseFieldMatcherSupplier STRICT_PARSING = () -> ParseFieldMatcher.STRICT;
+ private static final ParseFieldMatcherSupplier STRICT_PARSING = () -> ParseFieldMatcher.STRICT;
public void testBasics() throws IOException {
XContentParser parser = XContentType.JSON.xContent().createParser(
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/XContentFactoryTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/XContentFactoryTests.java
index 583234461b3..8319873878a 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/XContentFactoryTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/XContentFactoryTests.java
@@ -57,11 +57,10 @@ public class XContentFactoryTests extends ESTestCase {
builder.endObject();
assertThat(XContentFactory.xContentType(builder.bytes()), equalTo(type));
- BytesArray bytesArray = builder.bytes().toBytesArray();
- assertThat(XContentFactory.xContentType(StreamInput.wrap(bytesArray.array(), bytesArray.arrayOffset(), bytesArray.length())), equalTo(type));
+ assertThat(XContentFactory.xContentType(builder.bytes().streamInput()), equalTo(type));
// CBOR is binary, cannot use String
- if (type != XContentType.CBOR) {
+ if (type != XContentType.CBOR && type != XContentType.SMILE) {
assertThat(XContentFactory.xContentType(builder.string()), equalTo(type));
}
}
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java
index 34944e713bd..fe69fc1f05d 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/builder/XContentBuilderTests.java
@@ -94,7 +94,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.startObject();
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"foo\":{\"test\":\"value\"}}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"foo\":{\"test\":\"value\"}}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -102,7 +102,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.rawField("foo1", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"foo\":{\"test\":\"value\"},\"foo1\":{\"test\":\"value\"}}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"foo\":{\"test\":\"value\"},\"foo1\":{\"test\":\"value\"}}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -110,7 +110,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.field("test", "value");
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"}}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"}}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -119,7 +119,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.rawField("foo", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.field("test1", "value1");
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"test1\":\"value1\"}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"test1\":\"value1\"}"));
}
{
XContentBuilder xContentBuilder = XContentFactory.contentBuilder(XContentType.JSON);
@@ -129,7 +129,7 @@ public class XContentBuilderTests extends ESTestCase {
xContentBuilder.rawField("foo1", new BytesArray("{\"test\":\"value\"}"));
xContentBuilder.field("test1", "value1");
xContentBuilder.endObject();
- assertThat(xContentBuilder.bytes().toUtf8(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"foo1\":{\"test\":\"value\"},\"test1\":\"value1\"}"));
+ assertThat(xContentBuilder.bytes().utf8ToString(), equalTo("{\"test\":\"value\",\"foo\":{\"test\":\"value\"},\"foo1\":{\"test\":\"value\"},\"test1\":\"value1\"}"));
}
}
@@ -161,15 +161,14 @@ public class XContentBuilderTests extends ESTestCase {
gen.writeEndObject();
gen.close();
- byte[] data = bos.bytes().toBytes();
- String sData = new String(data, "UTF8");
+ String sData = bos.bytes().utf8ToString();
assertThat(sData, equalTo("{\"name\":\"something\", source : { test : \"value\" },\"name2\":\"something2\"}"));
}
public void testByteConversion() throws Exception {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON);
builder.startObject().field("test_name", (Byte)(byte)120).endObject();
- assertThat(builder.bytes().toUtf8(), equalTo("{\"test_name\":120}"));
+ assertThat(builder.bytes().utf8ToString(), equalTo("{\"test_name\":120}"));
}
public void testDateTypesConversion() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/cbor/JsonVsCborTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/cbor/JsonVsCborTests.java
index bf2dd442b64..efbca114aac 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/cbor/JsonVsCborTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/cbor/JsonVsCborTests.java
@@ -63,7 +63,8 @@ public class JsonVsCborTests extends ESTestCase {
xsonGen.close();
jsonGen.close();
- verifySameTokens(XContentFactory.xContent(XContentType.JSON).createParser(jsonOs.bytes().toBytes()), XContentFactory.xContent(XContentType.CBOR).createParser(xsonOs.bytes().toBytes()));
+ verifySameTokens(XContentFactory.xContent(XContentType.JSON).createParser(jsonOs.bytes()),
+ XContentFactory.xContent(XContentType.CBOR).createParser(xsonOs.bytes()));
}
private void verifySameTokens(XContentParser parser1, XContentParser parser2) throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/smile/JsonVsSmileTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/smile/JsonVsSmileTests.java
index 9e686fe78f1..63b19a63822 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/smile/JsonVsSmileTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/smile/JsonVsSmileTests.java
@@ -63,7 +63,8 @@ public class JsonVsSmileTests extends ESTestCase {
xsonGen.close();
jsonGen.close();
- verifySameTokens(XContentFactory.xContent(XContentType.JSON).createParser(jsonOs.bytes().toBytes()), XContentFactory.xContent(XContentType.SMILE).createParser(xsonOs.bytes().toBytes()));
+ verifySameTokens(XContentFactory.xContent(XContentType.JSON).createParser(jsonOs.bytes()),
+ XContentFactory.xContent(XContentType.SMILE).createParser(xsonOs.bytes()));
}
private void verifySameTokens(XContentParser parser1, XContentParser parser2) throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/AbstractFilteringJsonGeneratorTestCase.java b/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/AbstractFilteringJsonGeneratorTestCase.java
index e3d8735e05e..b8b38a543f6 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/AbstractFilteringJsonGeneratorTestCase.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/AbstractFilteringJsonGeneratorTestCase.java
@@ -27,7 +27,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.test.ESTestCase;
-import java.io.ByteArrayInputStream;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.is;
@@ -45,7 +44,7 @@ public abstract class AbstractFilteringJsonGeneratorTestCase extends ESTestCase
assertNotNull(expected);
// Verify that the result is equal to the expected string
- assertThat(builder.bytes().toUtf8(), is(expected.bytes().toUtf8()));
+ assertThat(builder.bytes().utf8ToString(), is(expected.bytes().utf8ToString()));
}
protected void assertBinary(XContentBuilder expected, XContentBuilder builder) {
@@ -1166,15 +1165,15 @@ public abstract class AbstractFilteringJsonGeneratorTestCase extends ESTestCase
// Test method: rawField(String fieldName, InputStream content)
assertXContentBuilder(expectedRawField,
- newXContentBuilder().startObject().field("foo", 0).rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ newXContentBuilder().startObject().field("foo", 0).rawField("raw", raw.streamInput()).endObject());
assertXContentBuilder(expectedRawFieldFiltered, newXContentBuilder("f*", true).startObject().field("foo", 0)
- .rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ .rawField("raw", raw.streamInput()).endObject());
assertXContentBuilder(expectedRawFieldFiltered, newXContentBuilder("r*", false).startObject().field("foo", 0)
- .rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ .rawField("raw", raw.streamInput()).endObject());
assertXContentBuilder(expectedRawFieldNotFiltered, newXContentBuilder("r*", true).startObject().field("foo", 0)
- .rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ .rawField("raw", raw.streamInput()).endObject());
assertXContentBuilder(expectedRawFieldNotFiltered, newXContentBuilder("f*", false).startObject().field("foo", 0)
- .rawField("raw", new ByteArrayInputStream(raw.toBytes())).endObject());
+ .rawField("raw", raw.streamInput()).endObject());
}
public void testArrays() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathGeneratorFilteringTests.java b/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathGeneratorFilteringTests.java
index dd2fe42eb8e..8dbefedb249 100644
--- a/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathGeneratorFilteringTests.java
+++ b/core/src/test/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathGeneratorFilteringTests.java
@@ -142,7 +142,7 @@ public class FilterPathGeneratorFilteringTests extends ESTestCase {
}
}
}
- assertThat(os.bytes().toUtf8(), equalTo(replaceQuotes(expected)));
+ assertThat(os.bytes().utf8ToString(), equalTo(replaceQuotes(expected)));
}
}
diff --git a/core/src/test/java/org/elasticsearch/deps/jackson/JacksonLocationTests.java b/core/src/test/java/org/elasticsearch/deps/jackson/JacksonLocationTests.java
index 4efedd9154a..c25a0a6503b 100644
--- a/core/src/test/java/org/elasticsearch/deps/jackson/JacksonLocationTests.java
+++ b/core/src/test/java/org/elasticsearch/deps/jackson/JacksonLocationTests.java
@@ -56,8 +56,7 @@ public class JacksonLocationTests extends ESTestCase {
gen.close();
- byte[] data = os.bytes().toBytes();
- JsonParser parser = new JsonFactory().createParser(data);
+ JsonParser parser = new JsonFactory().createParser(os.bytes().streamInput());
assertThat(parser.nextToken(), equalTo(JsonToken.START_OBJECT));
assertThat(parser.nextToken(), equalTo(JsonToken.FIELD_NAME)); // "index"
diff --git a/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java b/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java
index f6aac190c4b..bb38e329103 100644
--- a/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/BlockingClusterStatePublishResponseHandlerTests.java
@@ -40,7 +40,7 @@ import static org.hamcrest.Matchers.not;
public class BlockingClusterStatePublishResponseHandlerTests extends ESTestCase {
- static private class PublishResponder extends AbstractRunnable {
+ private static class PublishResponder extends AbstractRunnable {
final boolean fail;
final DiscoveryNode node;
diff --git a/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java b/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java
index 7f89acd169e..13e19e84978 100644
--- a/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java
+++ b/core/src/test/java/org/elasticsearch/discovery/DiscoveryWithServiceDisruptionsIT.java
@@ -170,7 +170,7 @@ public class DiscoveryWithServiceDisruptionsIT extends ESIntegTestCase {
return nodes;
}
- final static Settings DEFAULT_SETTINGS = Settings.builder()
+ static final Settings DEFAULT_SETTINGS = Settings.builder()
.put(FaultDetection.PING_TIMEOUT_SETTING.getKey(), "1s") // for hitting simulated network failures quickly
.put(FaultDetection.PING_RETRIES_SETTING.getKey(), "1") // for hitting simulated network failures quickly
.put("discovery.zen.join_timeout", "10s") // still long to induce failures but to long so test won't time out
diff --git a/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java b/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java
index 135352343b6..15c8d312952 100644
--- a/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java
+++ b/core/src/test/java/org/elasticsearch/discovery/zen/NodeJoinControllerTests.java
@@ -581,7 +581,7 @@ public class NodeJoinControllerTests extends ESTestCase {
}
}
- final static AtomicInteger joinId = new AtomicInteger();
+ static final AtomicInteger joinId = new AtomicInteger();
private SimpleFuture joinNodeAsync(final DiscoveryNode node) throws InterruptedException {
final SimpleFuture future = new SimpleFuture("join of " + node + " (id [" + joinId.incrementAndGet() + "]");
diff --git a/core/src/test/java/org/elasticsearch/gateway/GatewayServiceTests.java b/core/src/test/java/org/elasticsearch/gateway/GatewayServiceTests.java
index 4f65c5fafdd..1b62f5d330a 100644
--- a/core/src/test/java/org/elasticsearch/gateway/GatewayServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/gateway/GatewayServiceTests.java
@@ -19,7 +19,6 @@
package org.elasticsearch.gateway;
-import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
@@ -40,7 +39,7 @@ public class GatewayServiceTests extends ESTestCase {
.put("http.enabled", "false")
.put("discovery.type", "local")
.put(settings.build()).build(),
- null, clusterService, null, null, null, null, new NoopDiscovery(), null, null);
+ null, clusterService, null, null, null, new NoopDiscovery(), null, null);
}
public void testDefaultRecoverAfterTime() throws IOException {
diff --git a/core/src/test/java/org/elasticsearch/gateway/RecoverAfterNodesIT.java b/core/src/test/java/org/elasticsearch/gateway/RecoverAfterNodesIT.java
index d6e8d61a7a6..1e35bcdd469 100644
--- a/core/src/test/java/org/elasticsearch/gateway/RecoverAfterNodesIT.java
+++ b/core/src/test/java/org/elasticsearch/gateway/RecoverAfterNodesIT.java
@@ -36,7 +36,7 @@ import static org.hamcrest.Matchers.hasItem;
@ClusterScope(scope = Scope.TEST, numDataNodes = 0)
public class RecoverAfterNodesIT extends ESIntegTestCase {
- private final static TimeValue BLOCK_WAIT_TIMEOUT = TimeValue.timeValueSeconds(10);
+ private static final TimeValue BLOCK_WAIT_TIMEOUT = TimeValue.timeValueSeconds(10);
public Set waitForNoBlocksOnNode(TimeValue timeout, Client nodeClient) throws InterruptedException {
long start = System.currentTimeMillis();
diff --git a/core/src/test/java/org/elasticsearch/http/HttpServerTests.java b/core/src/test/java/org/elasticsearch/http/HttpServerTests.java
index 21bf69fd8d3..5413467c2a4 100644
--- a/core/src/test/java/org/elasticsearch/http/HttpServerTests.java
+++ b/core/src/test/java/org/elasticsearch/http/HttpServerTests.java
@@ -20,7 +20,6 @@ package org.elasticsearch.http;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.breaker.CircuitBreaker;
-import org.elasticsearch.common.bytes.ByteBufferBytesReference;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
@@ -205,7 +204,7 @@ public class HttpServerTests extends ESTestCase {
private TestRestRequest(String path, String content) {
this.path = path;
- this.content = new ByteBufferBytesReference(ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8)));
+ this.content = new BytesArray(content);
}
@Override
diff --git a/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java b/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java
index 2769534aee0..91e9bb2c016 100644
--- a/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java
+++ b/core/src/test/java/org/elasticsearch/index/IndexModuleTests.java
@@ -193,7 +193,6 @@ public class IndexModuleTests extends ESTestCase {
IndexSettings indexSettings = IndexSettingsModule.newIndexSettings(index, settings);
IndexModule module = new IndexModule(indexSettings, null,
new AnalysisRegistry(environment, emptyMap(), emptyMap(), emptyMap(), emptyMap()));
- Consumer listener = (s) -> {};
module.addIndexEventListener(eventListener);
IndexService indexService = module.newIndexService(nodeEnvironment, deleter, nodeServicesProvider, indicesQueryCache, mapperRegistry,
new IndicesFieldDataCache(settings, this.listener));
diff --git a/core/src/test/java/org/elasticsearch/index/IndexRequestBuilderIT.java b/core/src/test/java/org/elasticsearch/index/IndexRequestBuilderIT.java
index c41051ec59c..f95e8408a87 100644
--- a/core/src/test/java/org/elasticsearch/index/IndexRequestBuilderIT.java
+++ b/core/src/test/java/org/elasticsearch/index/IndexRequestBuilderIT.java
@@ -22,6 +22,7 @@ package org.elasticsearch.index;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.test.ESIntegTestCase;
import org.elasticsearch.test.hamcrest.ElasticsearchAssertions;
@@ -43,7 +44,7 @@ public class IndexRequestBuilderIT extends ESIntegTestCase {
client().prepareIndex("test", "test").setSource("{\"test_field\" : \"foobar\"}"),
client().prepareIndex("test", "test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}")),
client().prepareIndex("test", "test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}")),
- client().prepareIndex("test", "test").setSource(new BytesArray("{\"test_field\" : \"foobar\"}").toBytes()),
+ client().prepareIndex("test", "test").setSource(BytesReference.toBytes(new BytesArray("{\"test_field\" : \"foobar\"}"))),
client().prepareIndex("test", "test").setSource(map)
};
indexRandom(true, builders);
diff --git a/core/src/test/java/org/elasticsearch/index/IndexServiceTests.java b/core/src/test/java/org/elasticsearch/index/IndexServiceTests.java
index 97258b12a3b..22324e1ff2b 100644
--- a/core/src/test/java/org/elasticsearch/index/IndexServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/index/IndexServiceTests.java
@@ -77,7 +77,6 @@ public class IndexServiceTests extends ESSingleNodeTestCase {
public void testFilteringAliases() throws Exception {
IndexService indexService = createIndex("test", Settings.EMPTY);
- IndexShard shard = indexService.getShard(0);
add(indexService, "cats", filter(termQuery("animal", "cat")));
add(indexService, "dogs", filter(termQuery("animal", "dog")));
add(indexService, "all", null);
@@ -101,7 +100,6 @@ public class IndexServiceTests extends ESSingleNodeTestCase {
public void testAliasFilters() throws Exception {
IndexService indexService = createIndex("test", Settings.EMPTY);
- IndexShard shard = indexService.getShard(0);
add(indexService, "cats", filter(termQuery("animal", "cat")));
add(indexService, "dogs", filter(termQuery("animal", "dog")));
@@ -118,7 +116,6 @@ public class IndexServiceTests extends ESSingleNodeTestCase {
public void testRemovedAliasFilter() throws Exception {
IndexService indexService = createIndex("test", Settings.EMPTY);
- IndexShard shard = indexService.getShard(0);
add(indexService, "cats", filter(termQuery("animal", "cat")));
remove(indexService, "cats");
@@ -132,7 +129,6 @@ public class IndexServiceTests extends ESSingleNodeTestCase {
public void testUnknownAliasFilter() throws Exception {
IndexService indexService = createIndex("test", Settings.EMPTY);
- IndexShard shard = indexService.getShard(0);
add(indexService, "cats", filter(termQuery("animal", "cat")));
add(indexService, "dogs", filter(termQuery("animal", "dog")));
diff --git a/core/src/test/java/org/elasticsearch/index/SettingsListenerIT.java b/core/src/test/java/org/elasticsearch/index/SettingsListenerIT.java
index 000d2509ea8..8e2b8f68963 100644
--- a/core/src/test/java/org/elasticsearch/index/SettingsListenerIT.java
+++ b/core/src/test/java/org/elasticsearch/index/SettingsListenerIT.java
@@ -45,8 +45,6 @@ public class SettingsListenerIT extends ESIntegTestCase {
public static class SettingsListenerPlugin extends Plugin {
private final SettingsTestingService service = new SettingsTestingService();
- private static final Setting SETTING = Setting.intSetting("index.test.new.setting", 0,
- Property.Dynamic, Property.IndexScope);
@Override
public List> getSettings() {
diff --git a/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java b/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java
index a0396b7abc6..0ecf8462651 100644
--- a/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java
+++ b/core/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java
@@ -539,7 +539,7 @@ public class InternalEngineTests extends ESTestCase {
public void testCommitStats() {
Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
engine.index(new Engine.Index(newUid("1"), doc));
@@ -716,7 +716,7 @@ public class InternalEngineTests extends ESTestCase {
// create a document
Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
engine.index(new Engine.Index(newUid("1"), doc));
@@ -729,7 +729,7 @@ public class InternalEngineTests extends ESTestCase {
// but, we can still get it (in realtime)
Engine.GetResult getResult = engine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
- assertThat(getResult.source().source.toBytesArray(), equalTo(B_1.toBytesArray()));
+ assertThat(getResult.source().source, equalTo(B_1));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
@@ -755,7 +755,7 @@ public class InternalEngineTests extends ESTestCase {
// now do an update
document = testDocument();
document.add(new TextField("value", "test1", Field.Store.YES));
- document.add(new Field(SourceFieldMapper.NAME, B_2.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_2), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_2, null);
engine.index(new Engine.Index(newUid("1"), doc));
@@ -769,7 +769,7 @@ public class InternalEngineTests extends ESTestCase {
// but, we can still get it (in realtime)
getResult = engine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
- assertThat(getResult.source().source.toBytesArray(), equalTo(B_2.toBytesArray()));
+ assertThat(getResult.source().source, equalTo(B_2));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
@@ -808,7 +808,7 @@ public class InternalEngineTests extends ESTestCase {
// add it back
document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
engine.index(new Engine.Index(newUid("1"), doc, Versions.MATCH_DELETED));
diff --git a/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java b/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java
index ef443d1e102..39112ed602e 100644
--- a/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java
+++ b/core/src/test/java/org/elasticsearch/index/engine/ShadowEngineTests.java
@@ -500,7 +500,7 @@ public class ShadowEngineTests extends ESTestCase {
public void testShadowEngineIgnoresWriteOperations() throws Exception {
// create a document
ParseContext.Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
try {
replicaEngine.index(new Engine.Index(newUid("1"), doc));
@@ -538,7 +538,7 @@ public class ShadowEngineTests extends ESTestCase {
// Now, add a document to the primary so we can test shadow engine deletes
document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
primaryEngine.index(new Engine.Index(newUid("1"), doc));
primaryEngine.flush();
@@ -593,7 +593,7 @@ public class ShadowEngineTests extends ESTestCase {
// create a document
ParseContext.Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
primaryEngine.index(new Engine.Index(newUid("1"), doc));
@@ -612,7 +612,7 @@ public class ShadowEngineTests extends ESTestCase {
// but, we can still get it (in realtime)
Engine.GetResult getResult = primaryEngine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
- assertThat(getResult.source().source.toBytesArray(), equalTo(B_1.toBytesArray()));
+ assertThat(getResult.source().source, equalTo(B_1));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
@@ -649,7 +649,7 @@ public class ShadowEngineTests extends ESTestCase {
// now do an update
document = testDocument();
document.add(new TextField("value", "test1", Field.Store.YES));
- document.add(new Field(SourceFieldMapper.NAME, B_2.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_2), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_2, null);
primaryEngine.index(new Engine.Index(newUid("1"), doc));
@@ -663,7 +663,7 @@ public class ShadowEngineTests extends ESTestCase {
// but, we can still get it (in realtime)
getResult = primaryEngine.get(new Engine.Get(true, newUid("1")));
assertThat(getResult.exists(), equalTo(true));
- assertThat(getResult.source().source.toBytesArray(), equalTo(B_2.toBytesArray()));
+ assertThat(getResult.source().source, equalTo(B_2));
assertThat(getResult.docIdAndVersion(), nullValue());
getResult.release();
@@ -720,7 +720,7 @@ public class ShadowEngineTests extends ESTestCase {
// add it back
document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
primaryEngine.index(new Engine.Index(newUid("1"), doc));
@@ -971,7 +971,7 @@ public class ShadowEngineTests extends ESTestCase {
// create a document
ParseContext.Document document = testDocumentWithTextField();
- document.add(new Field(SourceFieldMapper.NAME, B_1.toBytes(), SourceFieldMapper.Defaults.FIELD_TYPE));
+ document.add(new Field(SourceFieldMapper.NAME, BytesReference.toBytes(B_1), SourceFieldMapper.Defaults.FIELD_TYPE));
ParsedDocument doc = testParsedDocument("1", "1", "test", null, -1, -1, document, B_1, null);
pEngine.index(new Engine.Index(newUid("1"), doc));
pEngine.flush(true, true);
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java b/core/src/test/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java
index 68e59527982..37d0436c9db 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java
@@ -32,7 +32,7 @@ import java.util.List;
public abstract class FieldTypeTestCase extends ESTestCase {
/** Abstraction for mutating a property of a MappedFieldType */
- public static abstract class Modifier {
+ public abstract static class Modifier {
/** The name of the property that is being modified. Used in test failure messages. */
public final String property;
/** true if this modifier only makes types incompatible in strict mode, false otherwise */
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/all/SimpleAllMapperTests.java b/core/src/test/java/org/elasticsearch/index/mapper/all/SimpleAllMapperTests.java
index 165b49d3145..817dc6e50df 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/all/SimpleAllMapperTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/all/SimpleAllMapperTests.java
@@ -24,6 +24,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
@@ -292,17 +293,17 @@ public class SimpleAllMapperTests extends ESSingleNodeTestCase {
}
DocumentMapperParser parser = createIndex("test").mapperService().documentMapperParser();
- String mapping = mappingBuilder.endObject().endObject().bytes().toUtf8();
+ String mapping = mappingBuilder.endObject().endObject().bytes().utf8ToString();
logger.info("Mapping: {}", mapping);
DocumentMapper docMapper = parser.parse("test", new CompressedXContent(mapping));
String builtMapping = docMapper.mappingSource().string();
// reparse it
DocumentMapper builtDocMapper = parser.parse("test", new CompressedXContent(builtMapping));
- byte[] json = jsonBuilder().startObject()
+ byte[] json = BytesReference.toBytes(jsonBuilder().startObject()
.field("foo", "bar")
.field("foobar", "foobar")
- .endObject().bytes().toBytes();
+ .endObject().bytes());
Document doc = builtDocMapper.parse("test", "test", "1", new BytesArray(json)).rootDoc();
IndexableField[] fields = doc.getFields("_all");
if (enabled) {
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/binary/BinaryMappingTests.java b/core/src/test/java/org/elasticsearch/index/mapper/binary/BinaryMappingTests.java
index fc8e2ba1872..4bf1d0c68f7 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/binary/BinaryMappingTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/binary/BinaryMappingTests.java
@@ -21,6 +21,7 @@ package org.elasticsearch.index.mapper.binary;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.bytes.BytesArray;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.compress.CompressorFactory;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
@@ -79,7 +80,7 @@ public class BinaryMappingTests extends ESSingleNodeTestCase {
try (StreamOutput compressed = CompressorFactory.COMPRESSOR.streamOutput(out)) {
new BytesArray(binaryValue1).writeTo(compressed);
}
- final byte[] binaryValue2 = out.bytes().toBytes();
+ final byte[] binaryValue2 = BytesReference.toBytes(out.bytes());
assertTrue(CompressorFactory.isCompressed(new BytesArray(binaryValue2)));
for (byte[] value : Arrays.asList(binaryValue1, binaryValue2)) {
diff --git a/core/src/test/java/org/elasticsearch/index/mapper/timestamp/TimestampMappingTests.java b/core/src/test/java/org/elasticsearch/index/mapper/timestamp/TimestampMappingTests.java
index 78da5abb746..8f38e2be576 100644
--- a/core/src/test/java/org/elasticsearch/index/mapper/timestamp/TimestampMappingTests.java
+++ b/core/src/test/java/org/elasticsearch/index/mapper/timestamp/TimestampMappingTests.java
@@ -297,7 +297,7 @@ public class TimestampMappingTests extends ESSingleNodeTestCase {
out.close();
BytesReference bytes = out.bytes();
- MappingMetaData metaData = MappingMetaData.PROTO.readFrom(StreamInput.wrap(bytes));
+ MappingMetaData metaData = MappingMetaData.PROTO.readFrom(bytes.streamInput());
assertThat(metaData, is(expected));
}
@@ -314,7 +314,7 @@ public class TimestampMappingTests extends ESSingleNodeTestCase {
out.close();
BytesReference bytes = out.bytes();
- MappingMetaData metaData = MappingMetaData.PROTO.readFrom(StreamInput.wrap(bytes));
+ MappingMetaData metaData = MappingMetaData.PROTO.readFrom(bytes.streamInput());
assertThat(metaData, is(expected));
}
@@ -331,7 +331,7 @@ public class TimestampMappingTests extends ESSingleNodeTestCase {
out.close();
BytesReference bytes = out.bytes();
- MappingMetaData metaData = MappingMetaData.PROTO.readFrom(StreamInput.wrap(bytes));
+ MappingMetaData metaData = MappingMetaData.PROTO.readFrom(bytes.streamInput());
assertThat(metaData, is(expected));
}
diff --git a/core/src/test/java/org/elasticsearch/index/query/CombineFunctionTests.java b/core/src/test/java/org/elasticsearch/index/query/CombineFunctionTests.java
index 695330c21e2..667efbc8bac 100644
--- a/core/src/test/java/org/elasticsearch/index/query/CombineFunctionTests.java
+++ b/core/src/test/java/org/elasticsearch/index/query/CombineFunctionTests.java
@@ -40,41 +40,41 @@ public class CombineFunctionTests extends ESTestCase {
public void testWriteTo() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
CombineFunction.MULTIPLY.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(0));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
CombineFunction.REPLACE.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(1));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
CombineFunction.SUM.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(2));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
CombineFunction.AVG.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(3));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
CombineFunction.MIN.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(4));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
CombineFunction.MAX.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(5));
}
}
@@ -83,37 +83,37 @@ public class CombineFunctionTests extends ESTestCase {
public void testReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(0);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(CombineFunction.readFromStream(in), equalTo(CombineFunction.MULTIPLY));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(1);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(CombineFunction.readFromStream(in), equalTo(CombineFunction.REPLACE));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(2);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(CombineFunction.readFromStream(in), equalTo(CombineFunction.SUM));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(3);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(CombineFunction.readFromStream(in), equalTo(CombineFunction.AVG));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(4);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(CombineFunction.readFromStream(in), equalTo(CombineFunction.MIN));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(5);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(CombineFunction.readFromStream(in), equalTo(CombineFunction.MAX));
}
}
diff --git a/core/src/test/java/org/elasticsearch/index/query/InnerHitBuilderTests.java b/core/src/test/java/org/elasticsearch/index/query/InnerHitBuilderTests.java
index 6460d8505ee..090aa906456 100644
--- a/core/src/test/java/org/elasticsearch/index/query/InnerHitBuilderTests.java
+++ b/core/src/test/java/org/elasticsearch/index/query/InnerHitBuilderTests.java
@@ -381,7 +381,7 @@ public class InnerHitBuilderTests extends ESTestCase {
private static InnerHitBuilder serializedCopy(InnerHitBuilder original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
return new InnerHitBuilder(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/index/query/MoreLikeThisQueryBuilderTests.java b/core/src/test/java/org/elasticsearch/index/query/MoreLikeThisQueryBuilderTests.java
index 91a42d70809..3c5bfed86dd 100644
--- a/core/src/test/java/org/elasticsearch/index/query/MoreLikeThisQueryBuilderTests.java
+++ b/core/src/test/java/org/elasticsearch/index/query/MoreLikeThisQueryBuilderTests.java
@@ -33,7 +33,6 @@ import org.elasticsearch.action.termvectors.TermVectorsRequest;
import org.elasticsearch.action.termvectors.TermVectorsResponse;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
-import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.lucene.search.MoreLikeThisQuery;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
@@ -208,7 +207,7 @@ public class MoreLikeThisQueryBuilderTests extends AbstractQueryTestCase indexMapping = Collections.singletonMap("type", "{ \"type\": {} }");
- protected final static RecoveryTargetService.RecoveryListener recoveryListener = new RecoveryTargetService.RecoveryListener() {
+ private final Index index = new Index("test", "uuid");
+ private final ShardId shardId = new ShardId(index, 0);
+ private final Map indexMapping = Collections.singletonMap("type", "{ \"type\": {} }");
+ protected static final RecoveryTargetService.RecoveryListener recoveryListener = new RecoveryTargetService.RecoveryListener() {
@Override
public void onRecoveryDone(RecoveryState state) {
diff --git a/core/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java b/core/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java
index 40a23ee66cf..862be713030 100644
--- a/core/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java
+++ b/core/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java
@@ -653,7 +653,7 @@ public class IndexShardTests extends ESSingleNodeTestCase {
if (randomBoolean() || true) { // try to serialize it to ensure values survive the serialization
BytesStreamOutput out = new BytesStreamOutput();
stats.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
stats = ShardStats.readShardStats(in);
}
XContentBuilder builder = XContentFactory.jsonBuilder();
@@ -1442,7 +1442,7 @@ public class IndexShardTests extends ESSingleNodeTestCase {
DiscoveryNode localNode = new DiscoveryNode("foo", DummyTransportAddress.INSTANCE, emptyMap(), emptySet(), Version.CURRENT);
newShard.markAsRecovering("for testing", new RecoveryState(newShard.shardId(), routing.primary(), RecoveryState.Type.REPLICA, localNode, localNode));
List operations = new ArrayList<>();
- operations.add(new Translog.Index("testtype", "1", jsonBuilder().startObject().field("foo", "bar").endObject().bytes().toBytes()));
+ operations.add(new Translog.Index("testtype", "1", BytesReference.toBytes(jsonBuilder().startObject().field("foo", "bar").endObject().bytes())));
newShard.prepareForIndexRecovery();
newShard.recoveryState().getTranslog().totalOperations(operations.size());
newShard.skipTranslogRecovery();
@@ -1500,7 +1500,7 @@ public class IndexShardTests extends ESSingleNodeTestCase {
// Shard is still inactive since we haven't started recovering yet
assertFalse(newShard.isActive());
List operations = new ArrayList<>();
- operations.add(new Translog.Index("testtype", "1", jsonBuilder().startObject().field("foo", "bar").endObject().bytes().toBytes()));
+ operations.add(new Translog.Index("testtype", "1", BytesReference.toBytes(jsonBuilder().startObject().field("foo", "bar").endObject().bytes())));
newShard.prepareForIndexRecovery();
newShard.skipTranslogRecovery();
// Shard is still inactive since we haven't started recovering yet
diff --git a/core/src/test/java/org/elasticsearch/index/snapshots/blobstore/FileInfoTests.java b/core/src/test/java/org/elasticsearch/index/snapshots/blobstore/FileInfoTests.java
index 70eacaafedb..abaebb88c5e 100644
--- a/core/src/test/java/org/elasticsearch/index/snapshots/blobstore/FileInfoTests.java
+++ b/core/src/test/java/org/elasticsearch/index/snapshots/blobstore/FileInfoTests.java
@@ -21,6 +21,7 @@ package org.elasticsearch.index.snapshots.blobstore;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Version;
import org.elasticsearch.ElasticsearchParseException;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
@@ -52,7 +53,7 @@ public class FileInfoTests extends ESTestCase {
BlobStoreIndexShardSnapshot.FileInfo info = new BlobStoreIndexShardSnapshot.FileInfo("_foobar", meta, size);
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON).prettyPrint();
BlobStoreIndexShardSnapshot.FileInfo.toXContent(info, builder, ToXContent.EMPTY_PARAMS);
- byte[] xcontent = shuffleXContent(builder).bytes().toBytes();
+ byte[] xcontent = BytesReference.toBytes(shuffleXContent(builder).bytes());
final BlobStoreIndexShardSnapshot.FileInfo parsedInfo;
try (XContentParser parser = XContentFactory.xContent(XContentType.JSON).createParser(xcontent)) {
@@ -111,7 +112,7 @@ public class FileInfoTests extends ESTestCase {
builder.field(FileInfo.WRITTEN_BY, Version.LATEST.toString());
builder.field(FileInfo.CHECKSUM, "666");
builder.endObject();
- byte[] xContent = builder.bytes().toBytes();
+ byte[] xContent = BytesReference.toBytes(builder.bytes());
if (failure == null) {
// No failures should read as usual
diff --git a/core/src/test/java/org/elasticsearch/index/store/CorruptedFileIT.java b/core/src/test/java/org/elasticsearch/index/store/CorruptedFileIT.java
index 6508336d9f8..84d50c6620f 100644
--- a/core/src/test/java/org/elasticsearch/index/store/CorruptedFileIT.java
+++ b/core/src/test/java/org/elasticsearch/index/store/CorruptedFileIT.java
@@ -22,6 +22,7 @@ import com.carrotsearch.hppc.cursors.IntObjectCursor;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.apache.lucene.index.CheckIndex;
import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.util.BytesRef;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.node.stats.NodeStats;
import org.elasticsearch.action.admin.cluster.node.stats.NodesStatsResponse;
@@ -210,7 +211,7 @@ public class CorruptedFileIT extends ESIntegTestCase {
out.flush();
CheckIndex.Status status = checkIndex.checkIndex();
if (!status.clean) {
- logger.warn("check index [failure]\n{}", new String(os.bytes().toBytes(), StandardCharsets.UTF_8));
+ logger.warn("check index [failure]\n{}", os.bytes().utf8ToString());
throw new IOException("index check failure");
}
}
@@ -346,7 +347,7 @@ public class CorruptedFileIT extends ESIntegTestCase {
public void sendRequest(DiscoveryNode node, long requestId, String action, TransportRequest request, TransportRequestOptions options) throws IOException, TransportException {
if (corrupt.get() && action.equals(RecoveryTargetService.Actions.FILE_CHUNK)) {
RecoveryFileChunkRequest req = (RecoveryFileChunkRequest) request;
- byte[] array = req.content().array();
+ byte[] array = BytesRef.deepCopyOf(req.content().toBytesRef()).bytes;
int i = randomIntBetween(0, req.content().length() - 1);
array[i] = (byte) ~array[i]; // flip one byte in the content
hasCorrupted.countDown();
@@ -419,10 +420,12 @@ public class CorruptedFileIT extends ESIntegTestCase {
if (action.equals(RecoveryTargetService.Actions.FILE_CHUNK)) {
RecoveryFileChunkRequest req = (RecoveryFileChunkRequest) request;
if (truncate && req.length() > 1) {
- BytesArray array = new BytesArray(req.content().array(), req.content().arrayOffset(), (int) req.length() - 1);
+ BytesRef bytesRef = req.content().toBytesRef();
+ BytesArray array = new BytesArray(bytesRef.bytes, bytesRef.offset, (int) req.length() - 1);
request = new RecoveryFileChunkRequest(req.recoveryId(), req.shardId(), req.metadata(), req.position(), array, req.lastChunk(), req.totalTranslogOps(), req.sourceThrottleTimeInNanos());
} else {
- byte[] array = req.content().array();
+ assert req.content().toBytesRef().bytes == req.content().toBytesRef().bytes : "no internal reference!!";
+ final byte[] array = req.content().toBytesRef().bytes;
int i = randomIntBetween(0, req.content().length() - 1);
array[i] = (byte) ~array[i]; // flip one byte in the content
}
diff --git a/core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java b/core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java
index c72a6ecef27..01eead9c96b 100644
--- a/core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java
+++ b/core/src/test/java/org/elasticsearch/index/translog/TranslogTests.java
@@ -60,9 +60,7 @@ import java.nio.charset.Charset;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
-import java.nio.file.OpenOption;
import java.nio.file.Path;
-import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Collection;
@@ -217,24 +215,24 @@ public class TranslogTests extends ESTestCase {
Translog.Location loc2 = translog.add(new Translog.Index("test", "2", new byte[]{2}));
assertThat(loc2, greaterThan(loc1));
assertThat(translog.getLastWriteLocation(), greaterThan(loc2));
- assertThat(translog.read(loc1).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{1})));
- assertThat(translog.read(loc2).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{2})));
+ assertThat(translog.read(loc1).getSource().source, equalTo(new BytesArray(new byte[]{1})));
+ assertThat(translog.read(loc2).getSource().source, equalTo(new BytesArray(new byte[]{2})));
Translog.Location lastLocBeforeSync = translog.getLastWriteLocation();
translog.sync();
assertEquals(lastLocBeforeSync, translog.getLastWriteLocation());
- assertThat(translog.read(loc1).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{1})));
- assertThat(translog.read(loc2).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{2})));
+ assertThat(translog.read(loc1).getSource().source, equalTo(new BytesArray(new byte[]{1})));
+ assertThat(translog.read(loc2).getSource().source, equalTo(new BytesArray(new byte[]{2})));
Translog.Location loc3 = translog.add(new Translog.Index("test", "2", new byte[]{3}));
assertThat(loc3, greaterThan(loc2));
assertThat(translog.getLastWriteLocation(), greaterThan(loc3));
- assertThat(translog.read(loc3).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{3})));
+ assertThat(translog.read(loc3).getSource().source, equalTo(new BytesArray(new byte[]{3})));
lastLocBeforeSync = translog.getLastWriteLocation();
translog.sync();
assertEquals(lastLocBeforeSync, translog.getLastWriteLocation());
- assertThat(translog.read(loc3).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{3})));
+ assertThat(translog.read(loc3).getSource().source, equalTo(new BytesArray(new byte[]{3})));
translog.prepareCommit();
/*
* The commit adds to the lastWriteLocation even though is isn't really a write. This is just an implementation artifact but it can
@@ -242,7 +240,7 @@ public class TranslogTests extends ESTestCase {
* and less than the location of the next write operation.
*/
assertThat(translog.getLastWriteLocation(), greaterThan(lastLocBeforeSync));
- assertThat(translog.read(loc3).getSource().source.toBytesArray(), equalTo(new BytesArray(new byte[]{3})));
+ assertThat(translog.read(loc3).getSource().source, equalTo(new BytesArray(new byte[]{3})));
translog.commit();
assertNull(translog.read(loc1));
assertNull(translog.read(loc2));
@@ -274,7 +272,7 @@ public class TranslogTests extends ESTestCase {
Translog.Index index = (Translog.Index) snapshot.next();
assertThat(index != null, equalTo(true));
- assertThat(index.source().toBytes(), equalTo(new byte[]{1}));
+ assertThat(BytesReference.toBytes(index.source()), equalTo(new byte[]{1}));
Translog.Delete delete = (Translog.Delete) snapshot.next();
assertThat(delete != null, equalTo(true));
@@ -303,7 +301,7 @@ public class TranslogTests extends ESTestCase {
if (randomBoolean()) {
BytesStreamOutput out = new BytesStreamOutput();
stats.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
stats = new TranslogStats();
stats.readFrom(in);
}
@@ -350,7 +348,7 @@ public class TranslogTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
total.writeTo(out);
TranslogStats copy = new TranslogStats();
- copy.readFrom(StreamInput.wrap(out.bytes()));
+ copy.readFrom(out.bytes().streamInput());
assertEquals(6, copy.estimatedNumberOfOperations());
assertEquals(431, copy.getTranslogSizeInBytes());
@@ -827,7 +825,7 @@ public class TranslogTests extends ESTestCase {
assertEquals(max.generation, translog.currentFileGeneration());
final Translog.Operation read = translog.read(max);
- assertEquals(read.getSource().source.toUtf8(), Integer.toString(count));
+ assertEquals(read.getSource().source.utf8ToString(), Integer.toString(count));
}
public static Translog.Location max(Translog.Location a, Translog.Location b) {
@@ -859,7 +857,7 @@ public class TranslogTests extends ESTestCase {
Translog.Location location = locations.get(op);
if (op <= lastSynced) {
final Translog.Operation read = reader.read(location);
- assertEquals(Integer.toString(op), read.getSource().source.toUtf8());
+ assertEquals(Integer.toString(op), read.getSource().source.utf8ToString());
} else {
try {
reader.read(location);
@@ -995,7 +993,7 @@ public class TranslogTests extends ESTestCase {
assertEquals("expected operation" + i + " to be in the previous translog but wasn't", translog.currentFileGeneration() - 1, locations.get(i).generation);
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
- assertEquals(i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals(i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
@@ -1030,7 +1028,7 @@ public class TranslogTests extends ESTestCase {
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
- assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
if (randomBoolean()) { // recover twice
@@ -1043,7 +1041,7 @@ public class TranslogTests extends ESTestCase {
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
- assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
@@ -1084,7 +1082,7 @@ public class TranslogTests extends ESTestCase {
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
- assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
@@ -1099,7 +1097,7 @@ public class TranslogTests extends ESTestCase {
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
- assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
@@ -1143,7 +1141,7 @@ public class TranslogTests extends ESTestCase {
for (int i = 0; i < upTo; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null synced: " + sync, next);
- assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals("payload missmatch, synced: " + sync, i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
@@ -1157,7 +1155,7 @@ public class TranslogTests extends ESTestCase {
ops.add(test);
}
Translog.writeOperations(out, ops);
- final List readOperations = Translog.readOperations(StreamInput.wrap(out.bytes()));
+ final List readOperations = Translog.readOperations(out.bytes().streamInput());
assertEquals(ops.size(), readOperations.size());
assertEquals(ops, readOperations);
}
@@ -1218,7 +1216,7 @@ public class TranslogTests extends ESTestCase {
for (int i = firstUncommitted; i < translogOperations; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("" + i, next);
- assertEquals(Integer.parseInt(next.getSource().source.toUtf8()), i);
+ assertEquals(Integer.parseInt(next.getSource().source.utf8ToString()), i);
}
assertNull(snapshot.next());
}
@@ -1392,7 +1390,7 @@ public class TranslogTests extends ESTestCase {
assertEquals("expected operation" + i + " to be in the previous translog but wasn't", tlog.currentFileGeneration() - 1, locations.get(i).generation);
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
- assertEquals(i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals(i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
@@ -1716,7 +1714,7 @@ public class TranslogTests extends ESTestCase {
for (int i = 0; i < 1; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
- assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
tlog.add(new Translog.Index("test", "" + 1, Integer.toString(1).getBytes(Charset.forName("UTF-8"))));
}
@@ -1727,7 +1725,7 @@ public class TranslogTests extends ESTestCase {
for (int i = 0; i < 2; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
- assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
}
}
@@ -1771,7 +1769,7 @@ public class TranslogTests extends ESTestCase {
for (int i = 0; i < 1; i++) {
Translog.Operation next = snapshot.next();
assertNotNull("operation " + i + " must be non-null", next);
- assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.toUtf8()));
+ assertEquals("payload missmatch", i, Integer.parseInt(next.getSource().source.utf8ToString()));
}
tlog.add(new Translog.Index("test", "" + 1, Integer.toString(1).getBytes(Charset.forName("UTF-8"))));
}
@@ -1870,7 +1868,7 @@ public class TranslogTests extends ESTestCase {
assertEquals(syncedDocs.size(), snapshot.totalOperations());
for (int i = 0; i < syncedDocs.size(); i++) {
Translog.Operation next = snapshot.next();
- assertEquals(syncedDocs.get(i), next.getSource().source.toUtf8());
+ assertEquals(syncedDocs.get(i), next.getSource().source.utf8ToString());
assertNotNull("operation " + i + " must be non-null", next);
}
}
diff --git a/core/src/test/java/org/elasticsearch/indices/IndexingMemoryControllerTests.java b/core/src/test/java/org/elasticsearch/indices/IndexingMemoryControllerTests.java
index 1f1b758f349..995beb1742c 100644
--- a/core/src/test/java/org/elasticsearch/indices/IndexingMemoryControllerTests.java
+++ b/core/src/test/java/org/elasticsearch/indices/IndexingMemoryControllerTests.java
@@ -70,8 +70,7 @@ public class IndexingMemoryControllerTests extends ESSingleNodeTestCase {
super(Settings.builder()
.put("indices.memory.interval", "200h") // disable it
.put(settings)
- .build(),
- null, null, 100 * 1024 * 1024); // fix jvm mem size to 100mb
+ .build(), null, null);
}
public void deleteShard(IndexShard shard) {
diff --git a/core/src/test/java/org/elasticsearch/indices/IndicesRequestCacheTests.java b/core/src/test/java/org/elasticsearch/indices/IndicesRequestCacheTests.java
index 1cca3bb7215..d43217d9785 100644
--- a/core/src/test/java/org/elasticsearch/indices/IndicesRequestCacheTests.java
+++ b/core/src/test/java/org/elasticsearch/indices/IndicesRequestCacheTests.java
@@ -62,7 +62,7 @@ public class IndicesRequestCacheTests extends ESTestCase {
// initial cache
TestEntity entity = new TestEntity(requestCacheStats, reader, indexShard, 0);
BytesReference value = cache.getOrCompute(entity, reader, termQuery.buildAsBytes());
- assertEquals("foo", StreamInput.wrap(value).readString());
+ assertEquals("foo", value.streamInput().readString());
assertEquals(0, requestCacheStats.stats().getHitCount());
assertEquals(1, requestCacheStats.stats().getMissCount());
assertEquals(0, requestCacheStats.stats().getEvictions());
@@ -72,7 +72,7 @@ public class IndicesRequestCacheTests extends ESTestCase {
// cache hit
entity = new TestEntity(requestCacheStats, reader, indexShard, 0);
value = cache.getOrCompute(entity, reader, termQuery.buildAsBytes());
- assertEquals("foo", StreamInput.wrap(value).readString());
+ assertEquals("foo", value.streamInput().readString());
assertEquals(1, requestCacheStats.stats().getHitCount());
assertEquals(1, requestCacheStats.stats().getMissCount());
assertEquals(0, requestCacheStats.stats().getEvictions());
@@ -117,7 +117,7 @@ public class IndicesRequestCacheTests extends ESTestCase {
// initial cache
TestEntity entity = new TestEntity(requestCacheStats, reader, indexShard, 0);
BytesReference value = cache.getOrCompute(entity, reader, termQuery.buildAsBytes());
- assertEquals("foo", StreamInput.wrap(value).readString());
+ assertEquals("foo", value.streamInput().readString());
assertEquals(0, requestCacheStats.stats().getHitCount());
assertEquals(1, requestCacheStats.stats().getMissCount());
assertEquals(0, requestCacheStats.stats().getEvictions());
@@ -130,7 +130,7 @@ public class IndicesRequestCacheTests extends ESTestCase {
// cache the second
TestEntity secondEntity = new TestEntity(requestCacheStats, secondReader, indexShard, 0);
value = cache.getOrCompute(secondEntity, secondReader, termQuery.buildAsBytes());
- assertEquals("bar", StreamInput.wrap(value).readString());
+ assertEquals("bar", value.streamInput().readString());
assertEquals(0, requestCacheStats.stats().getHitCount());
assertEquals(2, requestCacheStats.stats().getMissCount());
assertEquals(0, requestCacheStats.stats().getEvictions());
@@ -141,7 +141,7 @@ public class IndicesRequestCacheTests extends ESTestCase {
secondEntity = new TestEntity(requestCacheStats, secondReader, indexShard, 0);
value = cache.getOrCompute(secondEntity, secondReader, termQuery.buildAsBytes());
- assertEquals("bar", StreamInput.wrap(value).readString());
+ assertEquals("bar", value.streamInput().readString());
assertEquals(1, requestCacheStats.stats().getHitCount());
assertEquals(2, requestCacheStats.stats().getMissCount());
assertEquals(0, requestCacheStats.stats().getEvictions());
@@ -150,7 +150,7 @@ public class IndicesRequestCacheTests extends ESTestCase {
entity = new TestEntity(requestCacheStats, reader, indexShard, 0);
value = cache.getOrCompute(entity, reader, termQuery.buildAsBytes());
- assertEquals("foo", StreamInput.wrap(value).readString());
+ assertEquals("foo", value.streamInput().readString());
assertEquals(2, requestCacheStats.stats().getHitCount());
assertEquals(2, requestCacheStats.stats().getMissCount());
assertEquals(0, requestCacheStats.stats().getEvictions());
@@ -209,9 +209,9 @@ public class IndicesRequestCacheTests extends ESTestCase {
TestEntity secondEntity = new TestEntity(requestCacheStats, secondReader, indexShard, 0);
BytesReference value1 = cache.getOrCompute(entity, reader, termQuery.buildAsBytes());
- assertEquals("foo", StreamInput.wrap(value1).readString());
+ assertEquals("foo", value1.streamInput().readString());
BytesReference value2 = cache.getOrCompute(secondEntity, secondReader, termQuery.buildAsBytes());
- assertEquals("bar", StreamInput.wrap(value2).readString());
+ assertEquals("bar", value2.streamInput().readString());
size = requestCacheStats.stats().getMemorySize();
IOUtils.close(reader, secondReader, writer, dir, cache);
}
@@ -240,12 +240,12 @@ public class IndicesRequestCacheTests extends ESTestCase {
TestEntity thirddEntity = new TestEntity(requestCacheStats, thirdReader, indexShard, 0);
BytesReference value1 = cache.getOrCompute(entity, reader, termQuery.buildAsBytes());
- assertEquals("foo", StreamInput.wrap(value1).readString());
+ assertEquals("foo", value1.streamInput().readString());
BytesReference value2 = cache.getOrCompute(secondEntity, secondReader, termQuery.buildAsBytes());
- assertEquals("bar", StreamInput.wrap(value2).readString());
+ assertEquals("bar", value2.streamInput().readString());
logger.info("Memory size: {}", requestCacheStats.stats().getMemorySize());
BytesReference value3 = cache.getOrCompute(thirddEntity, thirdReader, termQuery.buildAsBytes());
- assertEquals("baz", StreamInput.wrap(value3).readString());
+ assertEquals("baz", value3.streamInput().readString());
assertEquals(2, cache.count());
assertEquals(1, requestCacheStats.stats().getEvictions());
IOUtils.close(reader, secondReader, thirdReader, writer, dir, cache);
@@ -277,12 +277,12 @@ public class IndicesRequestCacheTests extends ESTestCase {
TestEntity thirddEntity = new TestEntity(requestCacheStats, thirdReader, differentIdentity, 0);
BytesReference value1 = cache.getOrCompute(entity, reader, termQuery.buildAsBytes());
- assertEquals("foo", StreamInput.wrap(value1).readString());
+ assertEquals("foo", value1.streamInput().readString());
BytesReference value2 = cache.getOrCompute(secondEntity, secondReader, termQuery.buildAsBytes());
- assertEquals("bar", StreamInput.wrap(value2).readString());
+ assertEquals("bar", value2.streamInput().readString());
logger.info("Memory size: {}", requestCacheStats.stats().getMemorySize());
BytesReference value3 = cache.getOrCompute(thirddEntity, thirdReader, termQuery.buildAsBytes());
- assertEquals("baz", StreamInput.wrap(value3).readString());
+ assertEquals("baz", value3.streamInput().readString());
assertEquals(3, cache.count());
final long hitCount = requestCacheStats.stats().getHitCount();
// clear all for the indexShard Idendity even though is't still open
@@ -292,7 +292,7 @@ public class IndicesRequestCacheTests extends ESTestCase {
// third has not been validated since it's a different identity
value3 = cache.getOrCompute(thirddEntity, thirdReader, termQuery.buildAsBytes());
assertEquals(hitCount + 1, requestCacheStats.stats().getHitCount());
- assertEquals("baz", StreamInput.wrap(value3).readString());
+ assertEquals("baz", value3.streamInput().readString());
IOUtils.close(reader, secondReader, thirdReader, writer, dir, cache);
diff --git a/core/src/test/java/org/elasticsearch/indices/TermsLookupTests.java b/core/src/test/java/org/elasticsearch/indices/TermsLookupTests.java
index 59d86ddce67..fea69133377 100644
--- a/core/src/test/java/org/elasticsearch/indices/TermsLookupTests.java
+++ b/core/src/test/java/org/elasticsearch/indices/TermsLookupTests.java
@@ -70,7 +70,7 @@ public class TermsLookupTests extends ESTestCase {
TermsLookup termsLookup = randomTermsLookup();
try (BytesStreamOutput output = new BytesStreamOutput()) {
termsLookup.writeTo(output);
- try (StreamInput in = StreamInput.wrap(output.bytes())) {
+ try (StreamInput in = output.bytes().streamInput()) {
TermsLookup deserializedLookup = new TermsLookup(in);
assertEquals(deserializedLookup, termsLookup);
assertEquals(deserializedLookup.hashCode(), termsLookup.hashCode());
diff --git a/core/src/test/java/org/elasticsearch/indices/cluster/AbstractIndicesClusterStateServiceTestCase.java b/core/src/test/java/org/elasticsearch/indices/cluster/AbstractIndicesClusterStateServiceTestCase.java
index 69bee510710..4bf12bd9138 100644
--- a/core/src/test/java/org/elasticsearch/indices/cluster/AbstractIndicesClusterStateServiceTestCase.java
+++ b/core/src/test/java/org/elasticsearch/indices/cluster/AbstractIndicesClusterStateServiceTestCase.java
@@ -181,7 +181,8 @@ public abstract class AbstractIndicesClusterStateServiceTestCase extends ESTestC
}
@Override
- public @Nullable MockIndexService indexService(Index index) {
+ @Nullable
+ public MockIndexService indexService(Index index) {
return indices.get(index.getUUID());
}
diff --git a/core/src/test/java/org/elasticsearch/indices/recovery/RecoveryTargetTests.java b/core/src/test/java/org/elasticsearch/indices/recovery/RecoveryTargetTests.java
index 8552db2d376..bcd614121b6 100644
--- a/core/src/test/java/org/elasticsearch/indices/recovery/RecoveryTargetTests.java
+++ b/core/src/test/java/org/elasticsearch/indices/recovery/RecoveryTargetTests.java
@@ -57,8 +57,8 @@ import static org.hamcrest.Matchers.lessThanOrEqualTo;
public class RecoveryTargetTests extends ESTestCase {
abstract class Streamer extends Thread {
private T lastRead;
- final private AtomicBoolean shouldStop;
- final private T source;
+ private final AtomicBoolean shouldStop;
+ private final T source;
final AtomicReference error = new AtomicReference<>();
final Version streamVersion;
@@ -84,7 +84,7 @@ public class RecoveryTargetTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
source.writeTo(out);
out.close();
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
T obj = deserialize(in);
lastRead = obj;
return obj;
diff --git a/core/src/test/java/org/elasticsearch/indices/stats/IndexStatsIT.java b/core/src/test/java/org/elasticsearch/indices/stats/IndexStatsIT.java
index 6bce95af184..8e88aff523c 100644
--- a/core/src/test/java/org/elasticsearch/indices/stats/IndexStatsIT.java
+++ b/core/src/test/java/org/elasticsearch/indices/stats/IndexStatsIT.java
@@ -647,7 +647,7 @@ public class IndexStatsIT extends ESIntegTestCase {
flags.writeTo(out);
out.close();
BytesReference bytes = out.bytes();
- CommonStatsFlags readStats = CommonStatsFlags.readCommonStatsFlags(StreamInput.wrap(bytes));
+ CommonStatsFlags readStats = CommonStatsFlags.readCommonStatsFlags(bytes.streamInput());
for (Flag flag : values) {
assertThat(flags.isSet(flag), equalTo(readStats.isSet(flag)));
}
@@ -661,7 +661,7 @@ public class IndexStatsIT extends ESIntegTestCase {
flags.writeTo(out);
out.close();
BytesReference bytes = out.bytes();
- CommonStatsFlags readStats = CommonStatsFlags.readCommonStatsFlags(StreamInput.wrap(bytes));
+ CommonStatsFlags readStats = CommonStatsFlags.readCommonStatsFlags(bytes.streamInput());
for (Flag flag : values) {
assertThat(flags.isSet(flag), equalTo(readStats.isSet(flag)));
}
diff --git a/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java b/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java
index e558f0f2a12..96af4ef3671 100644
--- a/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java
+++ b/core/src/test/java/org/elasticsearch/indices/store/IndicesStoreTests.java
@@ -57,7 +57,7 @@ import static org.elasticsearch.test.VersionUtils.randomVersion;
/**
*/
public class IndicesStoreTests extends ESTestCase {
- private final static ShardRoutingState[] NOT_STARTED_STATES;
+ private static final ShardRoutingState[] NOT_STARTED_STATES;
static {
Set set = new HashSet<>();
diff --git a/core/src/test/java/org/elasticsearch/ingest/IngestStatsTests.java b/core/src/test/java/org/elasticsearch/ingest/IngestStatsTests.java
index 119e94580ad..9974dd568a8 100644
--- a/core/src/test/java/org/elasticsearch/ingest/IngestStatsTests.java
+++ b/core/src/test/java/org/elasticsearch/ingest/IngestStatsTests.java
@@ -62,7 +62,7 @@ public class IngestStatsTests extends ESTestCase {
private IngestStats serialize(IngestStats stats) throws IOException {
BytesStreamOutput out = new BytesStreamOutput();
stats.writeTo(out);
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
return new IngestStats(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/ingest/PipelineExecutionServiceTests.java b/core/src/test/java/org/elasticsearch/ingest/PipelineExecutionServiceTests.java
index 8bf6f77a026..fcc6e04c6c1 100644
--- a/core/src/test/java/org/elasticsearch/ingest/PipelineExecutionServiceTests.java
+++ b/core/src/test/java/org/elasticsearch/ingest/PipelineExecutionServiceTests.java
@@ -134,8 +134,25 @@ public class PipelineExecutionServiceTests extends ESTestCase {
verify(completionHandler, times(1)).accept(true);
}
+ public void testExecuteEmptyPipeline() throws Exception {
+ CompoundProcessor processor = mock(CompoundProcessor.class);
+ when(store.get("_id")).thenReturn(new Pipeline("_id", "_description", processor));
+ when(processor.getProcessors()).thenReturn(Collections.emptyList());
+
+ IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id");
+ @SuppressWarnings("unchecked")
+ Consumer failureHandler = mock(Consumer.class);
+ @SuppressWarnings("unchecked")
+ Consumer completionHandler = mock(Consumer.class);
+ executionService.executeIndexRequest(indexRequest, failureHandler, completionHandler);
+ verify(processor, never()).execute(any());
+ verify(failureHandler, never()).accept(any());
+ verify(completionHandler, times(1)).accept(true);
+ }
+
public void testExecutePropagateAllMetaDataUpdates() throws Exception {
CompoundProcessor processor = mock(CompoundProcessor.class);
+ when(processor.getProcessors()).thenReturn(Collections.singletonList(mock(Processor.class)));
doAnswer((InvocationOnMock invocationOnMock) -> {
IngestDocument ingestDocument = (IngestDocument) invocationOnMock.getArguments()[0];
for (IngestDocument.MetaData metaData : IngestDocument.MetaData.values()) {
@@ -171,6 +188,7 @@ public class PipelineExecutionServiceTests extends ESTestCase {
public void testExecuteFailure() throws Exception {
CompoundProcessor processor = mock(CompoundProcessor.class);
+ when(processor.getProcessors()).thenReturn(Collections.singletonList(mock(Processor.class)));
when(store.get("_id")).thenReturn(new Pipeline("_id", "_description", processor));
IndexRequest indexRequest = new IndexRequest("_index", "_type", "_id").source(Collections.emptyMap()).setPipeline("_id");
doThrow(new RuntimeException()).when(processor).execute(eqID("_index", "_type", "_id", Collections.emptyMap()));
@@ -313,6 +331,7 @@ public class PipelineExecutionServiceTests extends ESTestCase {
}
CompoundProcessor processor = mock(CompoundProcessor.class);
+ when(processor.getProcessors()).thenReturn(Collections.singletonList(mock(Processor.class)));
Exception error = new RuntimeException();
doThrow(error).when(processor).execute(any());
when(store.get(pipelineId)).thenReturn(new Pipeline(pipelineId, null, processor));
@@ -356,8 +375,8 @@ public class PipelineExecutionServiceTests extends ESTestCase {
assertThat(ingestStats.getTotalStats().getIngestFailedCount(), equalTo(0L));
assertThat(ingestStats.getTotalStats().getIngestTimeInMillis(), equalTo(0L));
- when(store.get("_id1")).thenReturn(new Pipeline("_id1", null, new CompoundProcessor()));
- when(store.get("_id2")).thenReturn(new Pipeline("_id2", null, new CompoundProcessor()));
+ when(store.get("_id1")).thenReturn(new Pipeline("_id1", null, new CompoundProcessor(mock(Processor.class))));
+ when(store.get("_id2")).thenReturn(new Pipeline("_id2", null, new CompoundProcessor(mock(Processor.class))));
Map configurationMap = new HashMap<>();
configurationMap.put("_id1", new PipelineConfiguration("_id1", new BytesArray("{}")));
diff --git a/core/src/test/java/org/elasticsearch/ingest/PipelineFactoryTests.java b/core/src/test/java/org/elasticsearch/ingest/PipelineFactoryTests.java
index f601d11c878..b09d772729c 100644
--- a/core/src/test/java/org/elasticsearch/ingest/PipelineFactoryTests.java
+++ b/core/src/test/java/org/elasticsearch/ingest/PipelineFactoryTests.java
@@ -31,6 +31,7 @@ import java.util.List;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
+import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.Mockito.mock;
@@ -69,6 +70,17 @@ public class PipelineFactoryTests extends ESTestCase {
}
}
+ public void testCreateWithEmptyProcessorsField() throws Exception {
+ Map pipelineConfig = new HashMap<>();
+ pipelineConfig.put(Pipeline.DESCRIPTION_KEY, "_description");
+ pipelineConfig.put(Pipeline.PROCESSORS_KEY, Collections.emptyList());
+ Pipeline.Factory factory = new Pipeline.Factory();
+ Pipeline pipeline = factory.create("_id", pipelineConfig, null);
+ assertThat(pipeline.getId(), equalTo("_id"));
+ assertThat(pipeline.getDescription(), equalTo("_description"));
+ assertThat(pipeline.getProcessors(), is(empty()));
+ }
+
public void testCreateWithPipelineOnFailure() throws Exception {
Map processorConfig = new HashMap<>();
Map pipelineConfig = new HashMap<>();
diff --git a/core/src/test/java/org/elasticsearch/nodesinfo/NodeInfoStreamingTests.java b/core/src/test/java/org/elasticsearch/nodesinfo/NodeInfoStreamingTests.java
index 0d07bcf0981..739dcd8b2c6 100644
--- a/core/src/test/java/org/elasticsearch/nodesinfo/NodeInfoStreamingTests.java
+++ b/core/src/test/java/org/elasticsearch/nodesinfo/NodeInfoStreamingTests.java
@@ -70,7 +70,7 @@ public class NodeInfoStreamingTests extends ESTestCase {
out.setVersion(version);
nodeInfo.writeTo(out);
out.close();
- StreamInput in = StreamInput.wrap(out.bytes());
+ StreamInput in = out.bytes().streamInput();
in.setVersion(version);
NodeInfo readNodeInfo = NodeInfo.readNodeInfo(in);
assertExpectedUnchanged(nodeInfo, readNodeInfo);
@@ -81,11 +81,6 @@ public class NodeInfoStreamingTests extends ESTestCase {
assertThat(nodeInfo.getBuild().toString(), equalTo(readNodeInfo.getBuild().toString()));
assertThat(nodeInfo.getHostname(), equalTo(readNodeInfo.getHostname()));
assertThat(nodeInfo.getVersion(), equalTo(readNodeInfo.getVersion()));
- assertThat(nodeInfo.getServiceAttributes().size(), equalTo(readNodeInfo.getServiceAttributes().size()));
- for (Map.Entry entry : nodeInfo.getServiceAttributes().entrySet()) {
- assertNotNull(readNodeInfo.getServiceAttributes().get(entry.getKey()));
- assertThat(readNodeInfo.getServiceAttributes().get(entry.getKey()), equalTo(entry.getValue()));
- }
compareJsonOutput(nodeInfo.getHttp(), readNodeInfo.getHttp());
compareJsonOutput(nodeInfo.getJvm(), readNodeInfo.getJvm());
compareJsonOutput(nodeInfo.getProcess(), readNodeInfo.getProcess());
@@ -149,6 +144,7 @@ public class NodeInfoStreamingTests extends ESTestCase {
// pick a random long that sometimes exceeds an int:
indexingBuffer = new ByteSizeValue(random().nextLong() & ((1L<<40)-1));
}
- return new NodeInfo(VersionUtils.randomVersion(random()), build, node, serviceAttributes, settings, osInfo, process, jvm, threadPoolInfo, transport, htttpInfo, plugins, ingestInfo, indexingBuffer);
+ return new NodeInfo(VersionUtils.randomVersion(random()), build, node, settings, osInfo, process, jvm,
+ threadPoolInfo, transport, htttpInfo, plugins, ingestInfo, indexingBuffer);
}
}
diff --git a/core/src/test/java/org/elasticsearch/recovery/RecoveriesCollectionTests.java b/core/src/test/java/org/elasticsearch/recovery/RecoveriesCollectionTests.java
index 2564b31488b..740a027aecb 100644
--- a/core/src/test/java/org/elasticsearch/recovery/RecoveriesCollectionTests.java
+++ b/core/src/test/java/org/elasticsearch/recovery/RecoveriesCollectionTests.java
@@ -47,7 +47,7 @@ import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.lessThan;
public class RecoveriesCollectionTests extends ESSingleNodeTestCase {
- final static RecoveryTargetService.RecoveryListener listener = new RecoveryTargetService.RecoveryListener() {
+ static final RecoveryTargetService.RecoveryListener listener = new RecoveryTargetService.RecoveryListener() {
@Override
public void onRecoveryDone(RecoveryState state) {
diff --git a/core/src/test/java/org/elasticsearch/recovery/RelocationIT.java b/core/src/test/java/org/elasticsearch/recovery/RelocationIT.java
index 620dfeb94c2..fd5da198ed2 100644
--- a/core/src/test/java/org/elasticsearch/recovery/RelocationIT.java
+++ b/core/src/test/java/org/elasticsearch/recovery/RelocationIT.java
@@ -22,6 +22,7 @@ package org.elasticsearch.recovery;
import com.carrotsearch.hppc.IntHashSet;
import com.carrotsearch.hppc.procedures.IntProcedure;
import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.English;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
@@ -93,8 +94,6 @@ import static org.hamcrest.Matchers.startsWith;
public class RelocationIT extends ESIntegTestCase {
private final TimeValue ACCEPTABLE_RELOCATION_TIME = new TimeValue(5, TimeUnit.MINUTES);
-
-
@Override
protected Collection> nodePlugins() {
return pluginList(MockTransportService.TestPlugin.class, MockIndexEventListener.TestPlugin.class);
@@ -505,7 +504,8 @@ public class RelocationIT extends ESIntegTestCase {
if (chunkRequest.name().startsWith(IndexFileNames.SEGMENTS)) {
// corrupting the segments_N files in order to make sure future recovery re-send files
logger.debug("corrupting [{}] to {}. file name: [{}]", action, node, chunkRequest.name());
- byte[] array = chunkRequest.content().array();
+ assert chunkRequest.content().toBytesRef().bytes == chunkRequest.content().toBytesRef().bytes : "no internal reference!!";
+ byte[] array = chunkRequest.content().toBytesRef().bytes;
array[0] = (byte) ~array[0]; // flip one byte in the content
corruptionCount.countDown();
}
diff --git a/core/src/test/java/org/elasticsearch/rest/BytesRestResponseTests.java b/core/src/test/java/org/elasticsearch/rest/BytesRestResponseTests.java
index aa3b11e6250..6bb1716cb0f 100644
--- a/core/src/test/java/org/elasticsearch/rest/BytesRestResponseTests.java
+++ b/core/src/test/java/org/elasticsearch/rest/BytesRestResponseTests.java
@@ -36,7 +36,6 @@ import java.io.IOException;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Mockito.mock;
@@ -64,7 +63,7 @@ public class BytesRestResponseTests extends ESTestCase {
Throwable t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar"));
BytesRestResponse response = new BytesRestResponse(channel, t);
- String text = response.content().toUtf8();
+ String text = response.content().utf8ToString();
assertThat(text, containsString("ElasticsearchException[an error occurred reading data]"));
assertThat(text, not(containsString("FileNotFoundException")));
assertThat(text, not(containsString("/foo/bar")));
@@ -77,7 +76,7 @@ public class BytesRestResponseTests extends ESTestCase {
Throwable t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar"));
BytesRestResponse response = new BytesRestResponse(channel, t);
- String text = response.content().toUtf8();
+ String text = response.content().utf8ToString();
assertThat(text, containsString("{\"type\":\"exception\",\"reason\":\"an error occurred reading data\"}"));
assertThat(text, containsString("{\"type\":\"file_not_found_exception\",\"reason\":\"/foo/bar\"}"));
}
@@ -88,7 +87,7 @@ public class BytesRestResponseTests extends ESTestCase {
Throwable t = new Throwable("an error occurred reading data", new FileNotFoundException("/foo/bar"));
BytesRestResponse response = new BytesRestResponse(channel, t);
- String text = response.content().toUtf8();
+ String text = response.content().utf8ToString();
assertThat(text, not(containsString("Throwable[an error occurred reading data]")));
assertThat(text, not(containsString("FileNotFoundException[/foo/bar]")));
assertThat(text, not(containsString("error_trace")));
@@ -102,7 +101,7 @@ public class BytesRestResponseTests extends ESTestCase {
Throwable t = new Throwable("an error occurred reading data", new FileNotFoundException("/foo/bar"));
BytesRestResponse response = new BytesRestResponse(channel, t);
- String text = response.content().toUtf8();
+ String text = response.content().utf8ToString();
assertThat(text, containsString("\"type\":\"throwable\",\"reason\":\"an error occurred reading data\""));
assertThat(text, containsString("{\"type\":\"file_not_found_exception\""));
assertThat(text, containsString("\"stack_trace\":\"[an error occurred reading data]"));
@@ -114,13 +113,13 @@ public class BytesRestResponseTests extends ESTestCase {
{
Throwable t = new ElasticsearchException("an error occurred reading data", new FileNotFoundException("/foo/bar"));
BytesRestResponse response = new BytesRestResponse(channel, t);
- String text = response.content().toUtf8();
+ String text = response.content().utf8ToString();
assertThat(text, containsString("{\"root_cause\":[{\"type\":\"exception\",\"reason\":\"an error occurred reading data\"}]"));
}
{
Throwable t = new FileNotFoundException("/foo/bar");
BytesRestResponse response = new BytesRestResponse(channel, t);
- String text = response.content().toUtf8();
+ String text = response.content().utf8ToString();
assertThat(text, containsString("{\"root_cause\":[{\"type\":\"file_not_found_exception\",\"reason\":\"/foo/bar\"}]"));
}
}
@@ -130,7 +129,7 @@ public class BytesRestResponseTests extends ESTestCase {
RestChannel channel = new SimpleExceptionRestChannel(request);
BytesRestResponse response = new BytesRestResponse(channel, null);
- String text = response.content().toUtf8();
+ String text = response.content().utf8ToString();
assertThat(text, containsString("\"error\":\"unknown\""));
assertThat(text, not(containsString("error_trace")));
}
@@ -144,7 +143,7 @@ public class BytesRestResponseTests extends ESTestCase {
new SearchShardTarget("node_1", new Index("foo", "_na_"), 2));
SearchPhaseExecutionException ex = new SearchPhaseExecutionException("search", "all shards failed", new ShardSearchFailure[] {failure, failure1});
BytesRestResponse response = new BytesRestResponse(channel, new RemoteTransportException("foo", ex));
- String text = response.content().toUtf8();
+ String text = response.content().utf8ToString();
String expected = "{\"error\":{\"root_cause\":[{\"type\":\"parsing_exception\",\"reason\":\"foobar\",\"line\":1,\"col\":2}],\"type\":\"search_phase_execution_exception\",\"reason\":\"all shards failed\",\"phase\":\"search\",\"grouped\":true,\"failed_shards\":[{\"shard\":1,\"index\":\"foo\",\"node\":\"node_1\",\"reason\":{\"type\":\"parsing_exception\",\"reason\":\"foobar\",\"line\":1,\"col\":2}}]},\"status\":400}";
assertEquals(expected.trim(), text.trim());
String stackTrace = ExceptionsHelper.stackTrace(ex);
@@ -160,7 +159,7 @@ public class BytesRestResponseTests extends ESTestCase {
// if we try to decode the path, this will throw an IllegalArgumentException again
final BytesRestResponse response = new BytesRestResponse(channel, e);
assertNotNull(response.content());
- final String content = response.content().toUtf8();
+ final String content = response.content().utf8ToString();
assertThat(content, containsString("\"type\":\"illegal_argument_exception\""));
assertThat(content, containsString("\"reason\":\"partial escape sequence at end of string: %a\""));
assertThat(content, containsString("\"status\":" + 400));
@@ -171,7 +170,7 @@ public class BytesRestResponseTests extends ESTestCase {
final RestChannel channel = new DetailedExceptionRestChannel(request);
final BytesRestResponse response = new BytesRestResponse(channel, new ElasticsearchException("simulated"));
assertNotNull(response.content());
- final String content = response.content().toUtf8();
+ final String content = response.content().utf8ToString();
assertThat(content, containsString("\"type\":\"exception\""));
assertThat(content, containsString("\"reason\":\"simulated\""));
assertThat(content, containsString("\"status\":" + 500));
diff --git a/core/src/test/java/org/elasticsearch/rest/action/cat/RestIndicesActionTests.java b/core/src/test/java/org/elasticsearch/rest/action/cat/RestIndicesActionTests.java
new file mode 100644
index 00000000000..db2148b9f61
--- /dev/null
+++ b/core/src/test/java/org/elasticsearch/rest/action/cat/RestIndicesActionTests.java
@@ -0,0 +1,162 @@
+/*
+ * 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.
+ */
+
+package org.elasticsearch.rest.action.cat;
+
+import org.elasticsearch.Version;
+import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
+import org.elasticsearch.action.admin.indices.stats.CommonStats;
+import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse;
+import org.elasticsearch.action.admin.indices.stats.IndicesStatsTests;
+import org.elasticsearch.action.admin.indices.stats.ShardStats;
+import org.elasticsearch.cluster.ClusterName;
+import org.elasticsearch.cluster.ClusterState;
+import org.elasticsearch.cluster.metadata.IndexMetaData;
+import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
+import org.elasticsearch.cluster.metadata.MetaData;
+import org.elasticsearch.cluster.routing.ShardRouting;
+import org.elasticsearch.cluster.routing.UnassignedInfo;
+import org.elasticsearch.common.Table;
+import org.elasticsearch.common.UUIDs;
+import org.elasticsearch.common.settings.Settings;
+import org.elasticsearch.common.unit.TimeValue;
+import org.elasticsearch.index.Index;
+import org.elasticsearch.index.cache.query.QueryCacheStats;
+import org.elasticsearch.index.cache.request.RequestCacheStats;
+import org.elasticsearch.index.engine.SegmentsStats;
+import org.elasticsearch.index.fielddata.FieldDataStats;
+import org.elasticsearch.index.flush.FlushStats;
+import org.elasticsearch.index.get.GetStats;
+import org.elasticsearch.index.merge.MergeStats;
+import org.elasticsearch.index.refresh.RefreshStats;
+import org.elasticsearch.index.search.stats.SearchStats;
+import org.elasticsearch.index.shard.DocsStats;
+import org.elasticsearch.index.shard.IndexingStats;
+import org.elasticsearch.index.shard.ShardId;
+import org.elasticsearch.index.shard.ShardPath;
+import org.elasticsearch.index.store.StoreStats;
+import org.elasticsearch.index.warmer.WarmerStats;
+import org.elasticsearch.rest.RestController;
+import org.elasticsearch.search.suggest.completion.CompletionStats;
+import org.elasticsearch.test.ESTestCase;
+
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.List;
+
+import static java.util.Collections.emptyList;
+import static org.hamcrest.Matchers.equalTo;
+
+/**
+ * Tests for {@link RestIndicesAction}
+ */
+public class RestIndicesActionTests extends ESTestCase {
+
+ public void testBuildTable() {
+ final Settings settings = Settings.EMPTY;
+ final RestController restController = new RestController(settings);
+ final RestIndicesAction action = new RestIndicesAction(settings, restController, new IndexNameExpressionResolver(settings));
+
+ // build a (semi-)random table
+ final int numIndices = randomIntBetween(0, 5);
+ Index[] indices = new Index[numIndices];
+ for (int i = 0; i < numIndices; i++) {
+ indices[i] = new Index(randomAsciiOfLength(5), UUIDs.randomBase64UUID());
+ }
+
+ final MetaData.Builder metaDataBuilder = MetaData.builder();
+ for (final Index index : indices) {
+ metaDataBuilder.put(IndexMetaData.builder(index.getName())
+ .settings(Settings.builder()
+ .put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT)
+ .put(IndexMetaData.SETTING_INDEX_UUID, index.getUUID()))
+ .creationDate(System.currentTimeMillis())
+ .numberOfShards(1)
+ .numberOfReplicas(1)
+ .state(IndexMetaData.State.OPEN));
+ }
+ final MetaData metaData = metaDataBuilder.build();
+
+ final ClusterState clusterState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.getDefault(Settings.EMPTY))
+ .metaData(metaData)
+ .build();
+ final String[] indicesStr = new String[indices.length];
+ for (int i = 0; i < indices.length; i++) {
+ indicesStr[i] = indices[i].getName();
+ }
+ final ClusterHealthResponse clusterHealth = new ClusterHealthResponse(
+ clusterState.getClusterName().value(), indicesStr, clusterState, 0, 0, 0, TimeValue.timeValueMillis(1000L)
+ );
+
+ final Table table = action.buildTable(null, indices, clusterHealth, randomIndicesStatsResponse(indices), metaData);
+
+ // now, verify the table is correct
+ int count = 0;
+ List headers = table.getHeaders();
+ assertThat(headers.get(count++).value, equalTo("health"));
+ assertThat(headers.get(count++).value, equalTo("status"));
+ assertThat(headers.get(count++).value, equalTo("index"));
+ assertThat(headers.get(count++).value, equalTo("uuid"));
+
+ List> rows = table.getRows();
+ assertThat(rows.size(), equalTo(indices.length));
+ // TODO: more to verify (e.g. randomize cluster health, num primaries, num replicas, etc)
+ for (int i = 0; i < rows.size(); i++) {
+ count = 0;
+ final List row = rows.get(i);
+ assertThat(row.get(count++).value, equalTo("red*")); // all are red because cluster state doesn't have routing entries
+ assertThat(row.get(count++).value, equalTo("open")); // all are OPEN for now
+ assertThat(row.get(count++).value, equalTo(indices[i].getName()));
+ assertThat(row.get(count++).value, equalTo(indices[i].getUUID()));
+ }
+ }
+
+ private IndicesStatsResponse randomIndicesStatsResponse(final Index[] indices) {
+ List shardStats = new ArrayList<>();
+ for (final Index index : indices) {
+ for (int i = 0; i < 2; i++) {
+ ShardId shardId = new ShardId(index, i);
+ Path path = createTempDir().resolve("indices").resolve(index.getUUID()).resolve(String.valueOf(i));
+ ShardRouting shardRouting = ShardRouting.newUnassigned(shardId, null, i == 0,
+ new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, null));
+ shardRouting = shardRouting.initialize("node-0", null, ShardRouting.UNAVAILABLE_EXPECTED_SHARD_SIZE);
+ shardRouting = shardRouting.moveToStarted();
+ CommonStats stats = new CommonStats();
+ stats.fieldData = new FieldDataStats();
+ stats.queryCache = new QueryCacheStats();
+ stats.docs = new DocsStats();
+ stats.store = new StoreStats();
+ stats.indexing = new IndexingStats();
+ stats.search = new SearchStats();
+ stats.segments = new SegmentsStats();
+ stats.merge = new MergeStats();
+ stats.refresh = new RefreshStats();
+ stats.completion = new CompletionStats();
+ stats.requestCache = new RequestCacheStats();
+ stats.get = new GetStats();
+ stats.flush = new FlushStats();
+ stats.warmer = new WarmerStats();
+ shardStats.add(new ShardStats(shardRouting, new ShardPath(false, path, path, shardId), stats, null));
+ }
+ }
+ return IndicesStatsTests.newIndicesStatsResponse(
+ shardStats.toArray(new ShardStats[shardStats.size()]), shardStats.size(), shardStats.size(), 0, emptyList()
+ );
+ }
+}
diff --git a/core/src/test/java/org/elasticsearch/rest/action/main/RestMainActionTests.java b/core/src/test/java/org/elasticsearch/rest/action/main/RestMainActionTests.java
index ebb7dd255aa..ffefa074df7 100644
--- a/core/src/test/java/org/elasticsearch/rest/action/main/RestMainActionTests.java
+++ b/core/src/test/java/org/elasticsearch/rest/action/main/RestMainActionTests.java
@@ -95,6 +95,6 @@ public class RestMainActionTests extends ESTestCase {
}
mainResponse.toXContent(responseBuilder, ToXContent.EMPTY_PARAMS);
BytesReference xcontentBytes = responseBuilder.bytes();
- assertTrue(BytesReference.Helper.bytesEqual(xcontentBytes, response.content()));
+ assertEquals(xcontentBytes, response.content());
}
}
diff --git a/core/src/test/java/org/elasticsearch/rest/action/support/RestTableTests.java b/core/src/test/java/org/elasticsearch/rest/action/support/RestTableTests.java
index a7e17785d48..3dfae8cc4f8 100644
--- a/core/src/test/java/org/elasticsearch/rest/action/support/RestTableTests.java
+++ b/core/src/test/java/org/elasticsearch/rest/action/support/RestTableTests.java
@@ -169,7 +169,7 @@ public class RestTableTests extends ESTestCase {
private void assertResponse(Map headers, String mediaType, String body) throws Exception {
RestResponse response = assertResponseContentType(headers, mediaType);
- assertThat(response.content().toUtf8(), equalTo(body));
+ assertThat(response.content().utf8ToString(), equalTo(body));
}
private List getHeaderNames(List headers) {
diff --git a/core/src/test/java/org/elasticsearch/script/StoredScriptsIT.java b/core/src/test/java/org/elasticsearch/script/StoredScriptsIT.java
index d8d6b0f5409..658a3bf5658 100644
--- a/core/src/test/java/org/elasticsearch/script/StoredScriptsIT.java
+++ b/core/src/test/java/org/elasticsearch/script/StoredScriptsIT.java
@@ -29,8 +29,8 @@ import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcke
public class StoredScriptsIT extends ESIntegTestCase {
- private final static int SCRIPT_MAX_SIZE_IN_BYTES = 64;
- private final static String LANG = MockScriptEngine.NAME;
+ private static final int SCRIPT_MAX_SIZE_IN_BYTES = 64;
+ private static final String LANG = MockScriptEngine.NAME;
@Override
protected Settings nodeSettings(int nodeOrdinal) {
diff --git a/core/src/test/java/org/elasticsearch/search/DocValueFormatTests.java b/core/src/test/java/org/elasticsearch/search/DocValueFormatTests.java
index 2ca255ea1a3..192f40d4b2b 100644
--- a/core/src/test/java/org/elasticsearch/search/DocValueFormatTests.java
+++ b/core/src/test/java/org/elasticsearch/search/DocValueFormatTests.java
@@ -43,13 +43,13 @@ public class DocValueFormatTests extends ESTestCase {
BytesStreamOutput out = new BytesStreamOutput();
out.writeNamedWriteable(DocValueFormat.BOOLEAN);
- StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes()), registry);
+ StreamInput in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), registry);
assertSame(DocValueFormat.BOOLEAN, in.readNamedWriteable(DocValueFormat.class));
DocValueFormat.Decimal decimalFormat = new DocValueFormat.Decimal("###.##");
out = new BytesStreamOutput();
out.writeNamedWriteable(decimalFormat);
- in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes()), registry);
+ in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), registry);
DocValueFormat vf = in.readNamedWriteable(DocValueFormat.class);
assertEquals(DocValueFormat.Decimal.class, vf.getClass());
assertEquals("###.##", ((DocValueFormat.Decimal) vf).pattern);
@@ -57,7 +57,7 @@ public class DocValueFormatTests extends ESTestCase {
DocValueFormat.DateTime dateFormat = new DocValueFormat.DateTime(Joda.forPattern("epoch_second"), DateTimeZone.forOffsetHours(1));
out = new BytesStreamOutput();
out.writeNamedWriteable(dateFormat);
- in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes()), registry);
+ in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), registry);
vf = in.readNamedWriteable(DocValueFormat.class);
assertEquals(DocValueFormat.DateTime.class, vf.getClass());
assertEquals("epoch_second", ((DocValueFormat.DateTime) vf).formatter.format());
@@ -65,17 +65,17 @@ public class DocValueFormatTests extends ESTestCase {
out = new BytesStreamOutput();
out.writeNamedWriteable(DocValueFormat.GEOHASH);
- in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes()), registry);
+ in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), registry);
assertSame(DocValueFormat.GEOHASH, in.readNamedWriteable(DocValueFormat.class));
out = new BytesStreamOutput();
out.writeNamedWriteable(DocValueFormat.IP);
- in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes()), registry);
+ in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), registry);
assertSame(DocValueFormat.IP, in.readNamedWriteable(DocValueFormat.class));
out = new BytesStreamOutput();
out.writeNamedWriteable(DocValueFormat.RAW);
- in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes()), registry);
+ in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), registry);
assertSame(DocValueFormat.RAW, in.readNamedWriteable(DocValueFormat.class));
}
diff --git a/core/src/test/java/org/elasticsearch/search/MultiValueModeTests.java b/core/src/test/java/org/elasticsearch/search/MultiValueModeTests.java
index a4837e382ac..5caba0fb441 100644
--- a/core/src/test/java/org/elasticsearch/search/MultiValueModeTests.java
+++ b/core/src/test/java/org/elasticsearch/search/MultiValueModeTests.java
@@ -753,35 +753,35 @@ public class MultiValueModeTests extends ESTestCase {
public void testWriteTo() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
MultiValueMode.SUM.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(0));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
MultiValueMode.AVG.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(1));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
MultiValueMode.MEDIAN.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(2));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
MultiValueMode.MIN.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(3));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
MultiValueMode.MAX.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(4));
}
}
@@ -790,35 +790,35 @@ public class MultiValueModeTests extends ESTestCase {
public void testReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(0);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(MultiValueMode.readMultiValueModeFrom(in), equalTo(MultiValueMode.SUM));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(1);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(MultiValueMode.readMultiValueModeFrom(in), equalTo(MultiValueMode.AVG));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(2);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(MultiValueMode.readMultiValueModeFrom(in), equalTo(MultiValueMode.MEDIAN));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(3);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(MultiValueMode.readMultiValueModeFrom(in), equalTo(MultiValueMode.MIN));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(4);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(MultiValueMode.readMultiValueModeFrom(in), equalTo(MultiValueMode.MAX));
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/aggregations/BaseAggregationTestCase.java b/core/src/test/java/org/elasticsearch/search/aggregations/BaseAggregationTestCase.java
index a4103e7ee56..ddde1fd9eb6 100644
--- a/core/src/test/java/org/elasticsearch/search/aggregations/BaseAggregationTestCase.java
+++ b/core/src/test/java/org/elasticsearch/search/aggregations/BaseAggregationTestCase.java
@@ -215,7 +215,7 @@ public abstract class BaseAggregationTestCase categoryToControl = new HashMap<>();
+ private static final Map categoryToControl = new HashMap<>();
@Override
public void setupSuiteScopeCluster() throws Exception {
diff --git a/core/src/test/java/org/elasticsearch/search/aggregations/metrics/percentiles/PercentilesMethodTests.java b/core/src/test/java/org/elasticsearch/search/aggregations/metrics/percentiles/PercentilesMethodTests.java
index 36c4caae12d..97d5cf1f9ee 100644
--- a/core/src/test/java/org/elasticsearch/search/aggregations/metrics/percentiles/PercentilesMethodTests.java
+++ b/core/src/test/java/org/elasticsearch/search/aggregations/metrics/percentiles/PercentilesMethodTests.java
@@ -38,14 +38,14 @@ public class PercentilesMethodTests extends ESTestCase {
public void testwriteTo() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
PercentilesMethod.TDIGEST.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(0));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
PercentilesMethod.HDR.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(1));
}
}
@@ -54,13 +54,13 @@ public class PercentilesMethodTests extends ESTestCase {
public void testReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(0);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(PercentilesMethod.readFromStream(in), equalTo(PercentilesMethod.TDIGEST));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(1);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(PercentilesMethod.readFromStream(in), equalTo(PercentilesMethod.HDR));
}
}
@@ -69,7 +69,7 @@ public class PercentilesMethodTests extends ESTestCase {
public void testInvalidReadFrom() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.writeVInt(randomIntBetween(2, Integer.MAX_VALUE));
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
PercentilesMethod.readFromStream(in);
fail("Expected IOException");
} catch(IOException e) {
diff --git a/core/src/test/java/org/elasticsearch/search/aggregations/pipeline/bucketmetrics/ExtendedStatsBucketTests.java b/core/src/test/java/org/elasticsearch/search/aggregations/pipeline/bucketmetrics/ExtendedStatsBucketTests.java
index e1441b0dc54..390501d2002 100644
--- a/core/src/test/java/org/elasticsearch/search/aggregations/pipeline/bucketmetrics/ExtendedStatsBucketTests.java
+++ b/core/src/test/java/org/elasticsearch/search/aggregations/pipeline/bucketmetrics/ExtendedStatsBucketTests.java
@@ -22,7 +22,6 @@ package org.elasticsearch.search.aggregations.pipeline.bucketmetrics;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
-import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucketPipelineAggregator;
import org.elasticsearch.search.aggregations.pipeline.bucketmetrics.stats.extended.ExtendedStatsBucketPipelineAggregationBuilder;
import static org.hamcrest.Matchers.equalTo;
@@ -51,7 +50,7 @@ public class ExtendedStatsBucketTests extends AbstractBucketMetricsTestCase CONTEXT_FACTORY = new ContextFactory() {
diff --git a/core/src/test/java/org/elasticsearch/search/functionscore/QueryRescorerIT.java b/core/src/test/java/org/elasticsearch/search/functionscore/QueryRescorerIT.java
index 14d0fc959c3..4ba1b902fef 100644
--- a/core/src/test/java/org/elasticsearch/search/functionscore/QueryRescorerIT.java
+++ b/core/src/test/java/org/elasticsearch/search/functionscore/QueryRescorerIT.java
@@ -355,7 +355,7 @@ public class QueryRescorerIT extends ESIntegTestCase {
// and shard id are equal during merging shard results.
// This comparator uses a custom tie in case the scores are equal, so that both regular hits and rescored hits
// are sorted equally. This is fine since tests only care about the fact the scores should be equal, not ordering.
- private final static Comparator searchHitsComparator = new Comparator() {
+ private static final Comparator searchHitsComparator = new Comparator() {
@Override
public int compare(SearchHit hit1, SearchHit hit2) {
int cmp = Float.compare(hit2.getScore(), hit1.getScore());
diff --git a/core/src/test/java/org/elasticsearch/search/highlight/HighlightBuilderTests.java b/core/src/test/java/org/elasticsearch/search/highlight/HighlightBuilderTests.java
index 930a7b220e0..1e3c5453fd7 100644
--- a/core/src/test/java/org/elasticsearch/search/highlight/HighlightBuilderTests.java
+++ b/core/src/test/java/org/elasticsearch/search/highlight/HighlightBuilderTests.java
@@ -484,14 +484,14 @@ public class HighlightBuilderTests extends ESTestCase {
public void testOrderSerialization() throws Exception {
try (BytesStreamOutput out = new BytesStreamOutput()) {
Order.NONE.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(0));
}
}
try (BytesStreamOutput out = new BytesStreamOutput()) {
Order.SCORE.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat(in.readVInt(), equalTo(1));
}
}
@@ -738,7 +738,7 @@ public class HighlightBuilderTests extends ESTestCase {
private static HighlightBuilder serializedCopy(HighlightBuilder original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
return new HighlightBuilder(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/internal/InternalSearchHitTests.java b/core/src/test/java/org/elasticsearch/search/internal/InternalSearchHitTests.java
index 77fc2f0e6a9..dedd47d3e43 100644
--- a/core/src/test/java/org/elasticsearch/search/internal/InternalSearchHitTests.java
+++ b/core/src/test/java/org/elasticsearch/search/internal/InternalSearchHitTests.java
@@ -67,7 +67,7 @@ public class InternalSearchHitTests extends ESTestCase {
context.streamShardTarget(InternalSearchHits.StreamContext.ShardTargetType.STREAM);
BytesStreamOutput output = new BytesStreamOutput();
hits.writeTo(output, context);
- InputStream input = new ByteArrayInputStream(output.bytes().toBytes());
+ InputStream input = output.bytes().streamInput();
context = new InternalSearchHits.StreamContext();
context.streamShardTarget(InternalSearchHits.StreamContext.ShardTargetType.STREAM);
InternalSearchHits results = InternalSearchHits.readSearchHits(new InputStreamStreamInput(input), context);
diff --git a/core/src/test/java/org/elasticsearch/search/matchedqueries/MatchedQueriesIT.java b/core/src/test/java/org/elasticsearch/search/matchedqueries/MatchedQueriesIT.java
index ef7a4ecc7ce..300c4f141b0 100644
--- a/core/src/test/java/org/elasticsearch/search/matchedqueries/MatchedQueriesIT.java
+++ b/core/src/test/java/org/elasticsearch/search/matchedqueries/MatchedQueriesIT.java
@@ -362,8 +362,8 @@ public class MatchedQueriesIT extends ESIntegTestCase {
refresh();
QueryBuilder[] queries = new QueryBuilder[]{
- wrapperQuery(matchQuery("content", "amet").queryName("abc").buildAsBytes().toUtf8()),
- constantScoreQuery(wrapperQuery(termQuery("content", "amet").queryName("abc").buildAsBytes().toUtf8()))
+ wrapperQuery(matchQuery("content", "amet").queryName("abc").buildAsBytes().utf8ToString()),
+ constantScoreQuery(wrapperQuery(termQuery("content", "amet").queryName("abc").buildAsBytes().utf8ToString()))
};
for (QueryBuilder query : queries) {
SearchResponse searchResponse = client().prepareSearch()
diff --git a/core/src/test/java/org/elasticsearch/search/rescore/QueryRescoreBuilderTests.java b/core/src/test/java/org/elasticsearch/search/rescore/QueryRescoreBuilderTests.java
index 7c3690dcf35..28eb56bdcaf 100644
--- a/core/src/test/java/org/elasticsearch/search/rescore/QueryRescoreBuilderTests.java
+++ b/core/src/test/java/org/elasticsearch/search/rescore/QueryRescoreBuilderTests.java
@@ -340,7 +340,7 @@ public class QueryRescoreBuilderTests extends ESTestCase {
private static RescoreBuilder> serializedCopy(RescoreBuilder> original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
output.writeNamedWriteable(original);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
return in.readNamedWriteable(RescoreBuilder.class);
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/searchafter/SearchAfterBuilderTests.java b/core/src/test/java/org/elasticsearch/search/searchafter/SearchAfterBuilderTests.java
index 3c675926328..7f9b9761feb 100644
--- a/core/src/test/java/org/elasticsearch/search/searchafter/SearchAfterBuilderTests.java
+++ b/core/src/test/java/org/elasticsearch/search/searchafter/SearchAfterBuilderTests.java
@@ -164,7 +164,7 @@ public class SearchAfterBuilderTests extends ESTestCase {
private static SearchAfterBuilder serializedCopy(SearchAfterBuilder original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
return new SearchAfterBuilder(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/slice/SliceBuilderTests.java b/core/src/test/java/org/elasticsearch/search/slice/SliceBuilderTests.java
index 217f97ace0a..a0ce8f02ea3 100644
--- a/core/src/test/java/org/elasticsearch/search/slice/SliceBuilderTests.java
+++ b/core/src/test/java/org/elasticsearch/search/slice/SliceBuilderTests.java
@@ -99,7 +99,7 @@ public class SliceBuilderTests extends ESTestCase {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
try (StreamInput in =
- new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
return new SliceBuilder(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/sort/AbstractSortTestCase.java b/core/src/test/java/org/elasticsearch/search/sort/AbstractSortTestCase.java
index b494fa4d1e6..8d46372aa42 100644
--- a/core/src/test/java/org/elasticsearch/search/sort/AbstractSortTestCase.java
+++ b/core/src/test/java/org/elasticsearch/search/sort/AbstractSortTestCase.java
@@ -272,7 +272,7 @@ public abstract class AbstractSortTestCase> extends EST
private T copyItem(T original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
return (T) namedWriteableRegistry.getReader(SortBuilder.class, original.getWriteableName()).read(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/sort/SortOrderTests.java b/core/src/test/java/org/elasticsearch/search/sort/SortOrderTests.java
index 2de48decbd8..208b4ed1b53 100644
--- a/core/src/test/java/org/elasticsearch/search/sort/SortOrderTests.java
+++ b/core/src/test/java/org/elasticsearch/search/sort/SortOrderTests.java
@@ -37,7 +37,7 @@ public class SortOrderTests extends ESTestCase {
for (SortOrder unit : SortOrder.values()) {
try (BytesStreamOutput out = new BytesStreamOutput()) {
unit.writeTo(out);
- try (StreamInput in = StreamInput.wrap(out.bytes())) {
+ try (StreamInput in = out.bytes().streamInput()) {
assertThat("Roundtrip serialisation failed.", SortOrder.readFromStream(in), equalTo(unit));
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/suggest/AbstractSuggestionBuilderTestCase.java b/core/src/test/java/org/elasticsearch/search/suggest/AbstractSuggestionBuilderTestCase.java
index cd6c34497f7..b67036e1152 100644
--- a/core/src/test/java/org/elasticsearch/search/suggest/AbstractSuggestionBuilderTestCase.java
+++ b/core/src/test/java/org/elasticsearch/search/suggest/AbstractSuggestionBuilderTestCase.java
@@ -215,7 +215,7 @@ public abstract class AbstractSuggestionBuilderTestCase extends ESTestCase {
private M copyModel(M original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), provideNamedWritableRegistry())) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), provideNamedWritableRegistry())) {
return readFrom(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/suggest/phrase/DirectCandidateGeneratorTests.java b/core/src/test/java/org/elasticsearch/search/suggest/phrase/DirectCandidateGeneratorTests.java
index 3fd3850b98a..846d3193f6d 100644
--- a/core/src/test/java/org/elasticsearch/search/suggest/phrase/DirectCandidateGeneratorTests.java
+++ b/core/src/test/java/org/elasticsearch/search/suggest/phrase/DirectCandidateGeneratorTests.java
@@ -206,7 +206,7 @@ public class DirectCandidateGeneratorTests extends ESTestCase{
private static DirectCandidateGeneratorBuilder serializedCopy(DirectCandidateGeneratorBuilder original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = StreamInput.wrap(output.bytes())) {
+ try (StreamInput in = output.bytes().streamInput()) {
return new DirectCandidateGeneratorBuilder(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/search/suggest/phrase/SmoothingModelTestCase.java b/core/src/test/java/org/elasticsearch/search/suggest/phrase/SmoothingModelTestCase.java
index f167eefa43d..c7b883b583b 100644
--- a/core/src/test/java/org/elasticsearch/search/suggest/phrase/SmoothingModelTestCase.java
+++ b/core/src/test/java/org/elasticsearch/search/suggest/phrase/SmoothingModelTestCase.java
@@ -180,7 +180,7 @@ public abstract class SmoothingModelTestCase extends ESTestCase {
static SmoothingModel copyModel(SmoothingModel original) throws IOException {
try (BytesStreamOutput output = new BytesStreamOutput()) {
original.writeTo(output);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(output.bytes()), namedWriteableRegistry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(output.bytes().streamInput(), namedWriteableRegistry)) {
return namedWriteableRegistry.getReader(SmoothingModel.class, original.getWriteableName()).read(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java b/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java
index 19c508e2bb1..15623825887 100644
--- a/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java
+++ b/core/src/test/java/org/elasticsearch/snapshots/DedicatedClusterSnapshotRestoreIT.java
@@ -646,8 +646,8 @@ public class DedicatedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTest
@Override
public void sendResponse(RestResponse response) {
try {
- assertThat(response.content().toUtf8(), containsString("notsecretusername"));
- assertThat(response.content().toUtf8(), not(containsString("verysecretpassword")));
+ assertThat(response.content().utf8ToString(), containsString("notsecretusername"));
+ assertThat(response.content().utf8ToString(), not(containsString("verysecretpassword")));
} catch (AssertionError ex) {
getRepoError.set(ex);
}
@@ -667,8 +667,8 @@ public class DedicatedClusterSnapshotRestoreIT extends AbstractSnapshotIntegTest
@Override
public void sendResponse(RestResponse response) {
try {
- assertThat(response.content().toUtf8(), containsString("notsecretusername"));
- assertThat(response.content().toUtf8(), not(containsString("verysecretpassword")));
+ assertThat(response.content().utf8ToString(), containsString("notsecretusername"));
+ assertThat(response.content().utf8ToString(), not(containsString("verysecretpassword")));
} catch (AssertionError ex) {
clusterStateError.set(ex);
}
diff --git a/core/src/test/java/org/elasticsearch/snapshots/SnapshotRequestsTests.java b/core/src/test/java/org/elasticsearch/snapshots/SnapshotRequestsTests.java
index 38d858c49aa..c178b2a6f83 100644
--- a/core/src/test/java/org/elasticsearch/snapshots/SnapshotRequestsTests.java
+++ b/core/src/test/java/org/elasticsearch/snapshots/SnapshotRequestsTests.java
@@ -22,6 +22,7 @@ package org.elasticsearch.snapshots;
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest;
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest;
import org.elasticsearch.action.support.IndicesOptions;
+import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.test.ESTestCase;
@@ -75,7 +76,7 @@ public class SnapshotRequestsTests extends ESTestCase {
builder.endArray();
}
- byte[] bytes = builder.endObject().bytes().toBytes();
+ byte[] bytes = BytesReference.toBytes(builder.endObject().bytes());
request.source(bytes);
@@ -134,7 +135,7 @@ public class SnapshotRequestsTests extends ESTestCase {
builder.endArray();
}
- byte[] bytes = builder.endObject().bytes().toBytes();
+ byte[] bytes = BytesReference.toBytes(builder.endObject().bytes());
request.source(bytes);
diff --git a/core/src/test/java/org/elasticsearch/snapshots/SnapshotTests.java b/core/src/test/java/org/elasticsearch/snapshots/SnapshotTests.java
index cb297785e4b..41cfa3d4141 100644
--- a/core/src/test/java/org/elasticsearch/snapshots/SnapshotTests.java
+++ b/core/src/test/java/org/elasticsearch/snapshots/SnapshotTests.java
@@ -20,12 +20,10 @@
package org.elasticsearch.snapshots;
import org.elasticsearch.common.UUIDs;
-import org.elasticsearch.common.io.stream.ByteBufferStreamInput;
import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.test.ESTestCase;
import java.io.IOException;
-import java.nio.ByteBuffer;
import static org.hamcrest.CoreMatchers.equalTo;
@@ -50,8 +48,7 @@ public class SnapshotTests extends ESTestCase {
final Snapshot original = new Snapshot(randomAsciiOfLength(randomIntBetween(2, 8)), snapshotId);
final BytesStreamOutput out = new BytesStreamOutput();
original.writeTo(out);
- final ByteBufferStreamInput in = new ByteBufferStreamInput(ByteBuffer.wrap(out.bytes().toBytes()));
- assertThat(new Snapshot(in), equalTo(original));
+ assertThat(new Snapshot(out.bytes().streamInput()), equalTo(original));
}
}
diff --git a/core/src/test/java/org/elasticsearch/tasks/PersistedTaskInfoTests.java b/core/src/test/java/org/elasticsearch/tasks/PersistedTaskInfoTests.java
index bfbb2dff4c7..5b507436129 100644
--- a/core/src/test/java/org/elasticsearch/tasks/PersistedTaskInfoTests.java
+++ b/core/src/test/java/org/elasticsearch/tasks/PersistedTaskInfoTests.java
@@ -37,7 +37,7 @@ import java.util.Map;
import java.util.TreeMap;
/**
- * Round trip tests for {@link PersistedTaskInfo} and those classes that it includes like {@link TaskInfo} and {@link RawTaskStatus}.
+ * Round trip tests for {@link PersistedTaskInfo} and those classes that it includes like {@link TaskInfo} and {@link RawTaskStatus}.
*/
public class PersistedTaskInfoTests extends ESTestCase {
public void testBinaryRoundTrip() throws IOException {
@@ -47,7 +47,7 @@ public class PersistedTaskInfoTests extends ESTestCase {
PersistedTaskInfo read;
try (BytesStreamOutput out = new BytesStreamOutput()) {
result.writeTo(out);
- try (StreamInput in = new NamedWriteableAwareStreamInput(StreamInput.wrap(out.bytes()), registry)) {
+ try (StreamInput in = new NamedWriteableAwareStreamInput(out.bytes().streamInput(), registry)) {
read = new PersistedTaskInfo(in);
}
} catch (IOException e) {
diff --git a/core/src/test/java/org/elasticsearch/tasks/TaskIdTests.java b/core/src/test/java/org/elasticsearch/tasks/TaskIdTests.java
index b13de26b976..f7990cfacb7 100644
--- a/core/src/test/java/org/elasticsearch/tasks/TaskIdTests.java
+++ b/core/src/test/java/org/elasticsearch/tasks/TaskIdTests.java
@@ -57,7 +57,7 @@ public class TaskIdTests extends ESTestCase {
taskId.writeTo(out);
BytesReference bytes = out.bytes();
assertEquals(expectedSize, bytes.length());
- try (StreamInput in = StreamInput.wrap(bytes)) {
+ try (StreamInput in = bytes.streamInput()) {
return TaskId.readFromStream(in);
}
}
diff --git a/core/src/test/java/org/elasticsearch/test/MockLogAppender.java b/core/src/test/java/org/elasticsearch/test/MockLogAppender.java
index 9e4a881b25b..8f10ccd6537 100644
--- a/core/src/test/java/org/elasticsearch/test/MockLogAppender.java
+++ b/core/src/test/java/org/elasticsearch/test/MockLogAppender.java
@@ -34,7 +34,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
*/
public class MockLogAppender extends AppenderSkeleton {
- private final static String COMMON_PREFIX = System.getProperty("es.logger.prefix", "org.elasticsearch.");
+ private static final String COMMON_PREFIX = System.getProperty("es.logger.prefix", "org.elasticsearch.");
private List expectations;
@@ -75,7 +75,7 @@ public class MockLogAppender extends AppenderSkeleton {
void assertMatched();
}
- public static abstract class AbstractEventExpectation implements LoggingExpectation {
+ public abstract static class AbstractEventExpectation implements LoggingExpectation {
protected final String name;
protected final String logger;
protected final Level level;
diff --git a/core/src/test/java/org/elasticsearch/threadpool/ThreadPoolSerializationTests.java b/core/src/test/java/org/elasticsearch/threadpool/ThreadPoolSerializationTests.java
index 486b0635c64..14cf10b8f31 100644
--- a/core/src/test/java/org/elasticsearch/threadpool/ThreadPoolSerializationTests.java
+++ b/core/src/test/java/org/elasticsearch/threadpool/ThreadPoolSerializationTests.java
@@ -58,7 +58,7 @@ public class ThreadPoolSerializationTests extends ESTestCase {
output.setVersion(Version.CURRENT);
info.writeTo(output);
- StreamInput input = StreamInput.wrap(output.bytes());
+ StreamInput input = output.bytes().streamInput();
ThreadPool.Info newInfo = new ThreadPool.Info();
newInfo.readFrom(input);
@@ -70,7 +70,7 @@ public class ThreadPoolSerializationTests extends ESTestCase {
output.setVersion(Version.CURRENT);
info.writeTo(output);
- StreamInput input = StreamInput.wrap(output.bytes());
+ StreamInput input = output.bytes().streamInput();
ThreadPool.Info newInfo = new ThreadPool.Info();
newInfo.readFrom(input);
@@ -125,7 +125,7 @@ public class ThreadPoolSerializationTests extends ESTestCase {
output.setVersion(Version.CURRENT);
info.writeTo(output);
- StreamInput input = StreamInput.wrap(output.bytes());
+ StreamInput input = output.bytes().streamInput();
ThreadPool.Info newInfo = new ThreadPool.Info();
newInfo.readFrom(input);
diff --git a/core/src/test/java/org/elasticsearch/transport/netty/ChannelBufferBytesReferenceTests.java b/core/src/test/java/org/elasticsearch/transport/netty/ChannelBufferBytesReferenceTests.java
index a284f6ea911..bc10458378f 100644
--- a/core/src/test/java/org/elasticsearch/transport/netty/ChannelBufferBytesReferenceTests.java
+++ b/core/src/test/java/org/elasticsearch/transport/netty/ChannelBufferBytesReferenceTests.java
@@ -18,11 +18,10 @@
*/
package org.elasticsearch.transport.netty;
+import org.apache.lucene.util.BytesRef;
import org.elasticsearch.common.bytes.AbstractBytesReferenceTestCase;
-import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput;
-import org.elasticsearch.transport.netty.NettyUtils;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
@@ -38,17 +37,16 @@ public class ChannelBufferBytesReferenceTests extends AbstractBytesReferenceTest
assertEquals(out.size(), length);
BytesReference ref = out.bytes();
assertEquals(ref.length(), length);
- BytesArray bytesArray = ref.toBytesArray();
- return NettyUtils.toBytesReference(ChannelBuffers.wrappedBuffer(bytesArray.array(), bytesArray.arrayOffset(),
- bytesArray.length()));
+ BytesRef bytesRef = ref.toBytesRef();
+ final ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(bytesRef.bytes, bytesRef.offset, bytesRef.length);
+ return NettyUtils.toBytesReference(channelBuffer);
}
public void testSliceOnAdvancedBuffer() throws IOException {
BytesReference bytesReference = newBytesReference(randomIntBetween(10, 3 * PAGE_SIZE));
- BytesArray bytesArray = bytesReference.toBytesArray();
-
- ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(bytesArray.array(), bytesArray.arrayOffset(),
- bytesArray.length());
+ BytesRef bytesRef = bytesReference.toBytesRef();
+ ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(bytesRef.bytes, bytesRef.offset,
+ bytesRef.length);
int numBytesToRead = randomIntBetween(1, 5);
for (int i = 0; i < numBytesToRead; i++) {
channelBuffer.readByte();
@@ -56,7 +54,25 @@ public class ChannelBufferBytesReferenceTests extends AbstractBytesReferenceTest
BytesReference other = NettyUtils.toBytesReference(channelBuffer);
BytesReference slice = bytesReference.slice(numBytesToRead, bytesReference.length() - numBytesToRead);
assertEquals(other, slice);
-
assertEquals(other.slice(3, 1), slice.slice(3, 1));
}
+
+ public void testImmutable() throws IOException {
+ BytesReference bytesReference = newBytesReference(randomIntBetween(10, 3 * PAGE_SIZE));
+ BytesRef bytesRef = BytesRef.deepCopyOf(bytesReference.toBytesRef());
+ ChannelBuffer channelBuffer = ChannelBuffers.wrappedBuffer(bytesRef.bytes, bytesRef.offset,
+ bytesRef.length);
+ ChannelBufferBytesReference channelBufferBytesReference = new ChannelBufferBytesReference(channelBuffer, bytesRef.length);
+ assertEquals(channelBufferBytesReference, bytesReference);
+ channelBuffer.readInt(); // this advances the index of the channel buffer
+ assertEquals(channelBufferBytesReference, bytesReference);
+ assertEquals(bytesRef, channelBufferBytesReference.toBytesRef());
+
+ BytesRef unicodeBytes = new BytesRef(randomUnicodeOfCodepointLength(100));
+ channelBuffer = ChannelBuffers.wrappedBuffer(unicodeBytes.bytes, unicodeBytes.offset, unicodeBytes.length);
+ channelBufferBytesReference = new ChannelBufferBytesReference(channelBuffer, unicodeBytes.length);
+ String utf8ToString = channelBufferBytesReference.utf8ToString();
+ channelBuffer.readInt(); // this advances the index of the channel buffer
+ assertEquals(utf8ToString, channelBufferBytesReference.utf8ToString());
+ }
}
diff --git a/core/src/test/java/org/elasticsearch/transport/netty/NettyUtilsTests.java b/core/src/test/java/org/elasticsearch/transport/netty/NettyUtilsTests.java
index fa8f30249bb..aa1db4a44c7 100644
--- a/core/src/test/java/org/elasticsearch/transport/netty/NettyUtilsTests.java
+++ b/core/src/test/java/org/elasticsearch/transport/netty/NettyUtilsTests.java
@@ -18,6 +18,8 @@
*/
package org.elasticsearch.transport.netty;
+import org.apache.lucene.util.BytesRef;
+import org.elasticsearch.common.bytes.AbstractBytesReferenceTestCase;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.ReleasableBytesStreamOutput;
@@ -47,7 +49,7 @@ public class NettyUtilsTests extends ESTestCase {
BytesReference slice = ref.slice(sliceOffset, sliceLength);
ChannelBuffer channelBuffer = NettyUtils.toChannelBuffer(slice);
BytesReference bytesReference = NettyUtils.toBytesReference(channelBuffer);
- assertArrayEquals(slice.toBytes(), bytesReference.toBytes());
+ assertArrayEquals(BytesReference.toBytes(slice), BytesReference.toBytes(bytesReference));
}
public void testToChannelBufferWithSliceAfter() throws IOException {
@@ -56,7 +58,8 @@ public class NettyUtilsTests extends ESTestCase {
int sliceLength = randomIntBetween(ref.length() - sliceOffset, ref.length() - sliceOffset);
ChannelBuffer channelBuffer = NettyUtils.toChannelBuffer(ref);
BytesReference bytesReference = NettyUtils.toBytesReference(channelBuffer);
- assertArrayEquals(ref.slice(sliceOffset, sliceLength).toBytes(), bytesReference.slice(sliceOffset, sliceLength).toBytes());
+ assertArrayEquals(BytesReference.toBytes(ref.slice(sliceOffset, sliceLength)),
+ BytesReference.toBytes(bytesReference.slice(sliceOffset, sliceLength)));
}
public void testToChannelBuffer() throws IOException {
@@ -65,10 +68,10 @@ public class NettyUtilsTests extends ESTestCase {
BytesReference bytesReference = NettyUtils.toBytesReference(channelBuffer);
if (ref instanceof ChannelBufferBytesReference) {
assertEquals(channelBuffer, ((ChannelBufferBytesReference) ref).toChannelBuffer());
- } else if (ref.hasArray() == false) { // we gather the buffers into a channel buffer
+ } else if (AbstractBytesReferenceTestCase.getNumPages(ref) > 1) { // we gather the buffers into a channel buffer
assertTrue(channelBuffer instanceof CompositeChannelBuffer);
}
- assertArrayEquals(ref.toBytes(), bytesReference.toBytes());
+ assertArrayEquals(BytesReference.toBytes(ref), BytesReference.toBytes(bytesReference));
}
private BytesReference getRandomizedBytesReference(int length) throws IOException {
@@ -81,13 +84,14 @@ public class NettyUtilsTests extends ESTestCase {
BytesReference ref = out.bytes();
assertEquals(ref.length(), length);
if (randomBoolean()) {
- return ref.toBytesArray();
+ return new BytesArray(ref.toBytesRef());
} else if (randomBoolean()) {
- BytesArray bytesArray = ref.toBytesArray();
- return NettyUtils.toBytesReference(ChannelBuffers.wrappedBuffer(bytesArray.array(), bytesArray.arrayOffset(),
- bytesArray.length()));
+ BytesRef bytesRef = ref.toBytesRef();
+ return NettyUtils.toBytesReference(ChannelBuffers.wrappedBuffer(bytesRef.bytes, bytesRef.offset,
+ bytesRef.length));
} else {
return ref;
}
}
+
}
diff --git a/core/src/test/java/org/elasticsearch/ttl/SimpleTTLIT.java b/core/src/test/java/org/elasticsearch/ttl/SimpleTTLIT.java
index 9e08ecde6fa..583d8a0288d 100644
--- a/core/src/test/java/org/elasticsearch/ttl/SimpleTTLIT.java
+++ b/core/src/test/java/org/elasticsearch/ttl/SimpleTTLIT.java
@@ -59,7 +59,7 @@ import static org.hamcrest.Matchers.nullValue;
@ClusterScope(scope= Scope.SUITE, supportsDedicatedMasters = false, numDataNodes = 1)
public class SimpleTTLIT extends ESIntegTestCase {
- static private final long PURGE_INTERVAL = 200;
+ private static final long PURGE_INTERVAL = 200;
@Override
protected int numberOfShards() {
diff --git a/core/src/test/java/org/elasticsearch/update/UpdateNoopIT.java b/core/src/test/java/org/elasticsearch/update/UpdateNoopIT.java
index b4b5eefc832..f14d91465f6 100644
--- a/core/src/test/java/org/elasticsearch/update/UpdateNoopIT.java
+++ b/core/src/test/java/org/elasticsearch/update/UpdateNoopIT.java
@@ -240,12 +240,12 @@ public class UpdateNoopIT extends ESIntegTestCase {
private void updateAndCheckSource(long expectedVersion, Boolean detectNoop, XContentBuilder xContentBuilder) {
UpdateResponse updateResponse = update(detectNoop, expectedVersion, xContentBuilder);
- assertEquals(updateResponse.getGetResult().sourceRef().toUtf8(), xContentBuilder.bytes().toUtf8());
+ assertEquals(updateResponse.getGetResult().sourceRef().utf8ToString(), xContentBuilder.bytes().utf8ToString());
}
private UpdateResponse update(Boolean detectNoop, long expectedVersion, XContentBuilder xContentBuilder) {
UpdateRequestBuilder updateRequest = client().prepareUpdate("test", "type1", "1")
- .setDoc(xContentBuilder.bytes().toUtf8())
+ .setDoc(xContentBuilder.bytes().utf8ToString())
.setDocAsUpsert(true)
.setFields("_source");
if (detectNoop != null) {
diff --git a/docs/plugins/ingest-useragent.asciidoc b/docs/plugins/ingest-useragent.asciidoc
new file mode 100644
index 00000000000..8868a4cf711
--- /dev/null
+++ b/docs/plugins/ingest-useragent.asciidoc
@@ -0,0 +1,74 @@
+[[ingest-useragent]]
+=== Ingest Useragent Processor Plugin
+
+The Useragent processor extracts details from the user agent string a browser sends with its web requests.
+This processor adds this information by default under the `useragent` field.
+
+The ingest-useragent plugin ships by default with the regexes.yaml made available by uap-java with an Apache 2.0 license. For more details see https://github.com/ua-parser/uap-core.
+
+[[ingest-useragent-install]]
+[float]
+==== Installation
+
+This plugin can be installed using the plugin manager:
+
+[source,sh]
+----------------------------------------------------------------
+sudo bin/elasticsearch-plugin install ingest-useragent
+----------------------------------------------------------------
+
+The plugin must be installed on every node in the cluster, and each node must
+be restarted after installation.
+
+[[ingest-useragent-remove]]
+[float]
+==== Removal
+
+The plugin can be removed with the following command:
+
+[source,sh]
+----------------------------------------------------------------
+sudo bin/elasticsearch-plugin remove ingest-useragent
+----------------------------------------------------------------
+
+The node must be stopped before removing the plugin.
+
+[[using-ingest-useragent]]
+==== Using the Useragent Processor in a Pipeline
+
+[[ingest-useragent-options]]
+.Useragent options
+[options="header"]
+|======
+| Name | Required | Default | Description
+| `field` | yes | - | The field containing the user agent string.
+| `target_field` | no | useragent | The field that will be filled with the user agent details.
+| `regex_file` | no | - | The name of the file in the `config/ingest-useragent` directory containing the regular expressions for parsing the user agent string. Both the directory and the file have to be created before starting Elasticsearch. If not specified, ingest-useragent will use the regexes.yaml from uap-core it ships with (see below).
+| `properties` | no | [`name`, `major`, `minor`, `patch`, `build`, `os`, `os_name`, `os_major`, `os_minor`, `device`] | Controls what properties are added to `target_field`.
+|======
+
+Here is an example that adds the user agent details to the `useragent` field based on the `agent` field:
+
+[source,js]
+--------------------------------------------------
+{
+ "description" : "...",
+ "processors" : [
+ {
+ "useragent" : {
+ "field" : "agent"
+ }
+ }
+ ]
+}
+--------------------------------------------------
+
+===== Using a custom regex file
+To use a custom regex file for parsing the user agents, that file has to be put into the `config/ingest-useragent` directory and
+has to have a `.yaml` filename extension. The file has to be present at node startup, any changes to it or any new files added
+while the node is running will not have any effect.
+
+In practice, it will make most sense for any custom regex file to be a variant of the default file, either a more recent version
+or a customised version.
+
+The default file included in `ingest-useragent` is the `regexes.yaml` from uap-core: https://github.com/ua-parser/uap-core/blob/master/regexes.yaml
diff --git a/docs/reference/aggregations/bucket/terms-aggregation.asciidoc b/docs/reference/aggregations/bucket/terms-aggregation.asciidoc
index 3c1f4ae860a..959b93611d8 100644
--- a/docs/reference/aggregations/bucket/terms-aggregation.asciidoc
+++ b/docs/reference/aggregations/bucket/terms-aggregation.asciidoc
@@ -9,8 +9,8 @@ Example:
--------------------------------------------------
{
"aggs" : {
- "genders" : {
- "terms" : { "field" : "gender" }
+ "genres" : {
+ "terms" : { "field" : "genre" }
}
}
}
@@ -24,16 +24,20 @@ Response:
...
"aggregations" : {
- "genders" : {
+ "genres" : {
"doc_count_error_upper_bound": 0, <1>
"sum_other_doc_count": 0, <2>
"buckets" : [ <3>
{
- "key" : "male",
+ "key" : "jazz",
"doc_count" : 10
},
{
- "key" : "female",
+ "key" : "rock",
+ "doc_count" : 10
+ },
+ {
+ "key" : "electronic",
"doc_count" : 10
},
]
@@ -247,9 +251,9 @@ Ordering the buckets by their `doc_count` in an ascending manner:
--------------------------------------------------
{
"aggs" : {
- "genders" : {
+ "genres" : {
"terms" : {
- "field" : "gender",
+ "field" : "genre",
"order" : { "_count" : "asc" }
}
}
@@ -263,9 +267,9 @@ Ordering the buckets alphabetically by their terms in an ascending manner:
--------------------------------------------------
{
"aggs" : {
- "genders" : {
+ "genres" : {
"terms" : {
- "field" : "gender",
+ "field" : "genre",
"order" : { "_term" : "asc" }
}
}
@@ -280,13 +284,13 @@ Ordering the buckets by single value metrics sub-aggregation (identified by the
--------------------------------------------------
{
"aggs" : {
- "genders" : {
+ "genres" : {
"terms" : {
- "field" : "gender",
- "order" : { "avg_height" : "desc" }
+ "field" : "genre",
+ "order" : { "avg_play_count" : "desc" }
},
"aggs" : {
- "avg_height" : { "avg" : { "field" : "height" } }
+ "avg_play_count" : { "avg" : { "field" : "play_count" } }
}
}
}
@@ -299,13 +303,13 @@ Ordering the buckets by multi value metrics sub-aggregation (identified by the a
--------------------------------------------------
{
"aggs" : {
- "genders" : {
+ "genres" : {
"terms" : {
- "field" : "gender",
- "order" : { "height_stats.avg" : "desc" }
+ "field" : "genre",
+ "order" : { "playback_stats.avg" : "desc" }
},
"aggs" : {
- "height_stats" : { "stats" : { "field" : "height" } }
+ "playback_stats" : { "stats" : { "field" : "play_count" } }
}
}
}
@@ -343,14 +347,14 @@ PATH := []*[height_stats.avg" : "desc" }
+ "field" : "artist.country",
+ "order" : { "rock>playback_stats.avg" : "desc" }
},
"aggs" : {
- "females" : {
- "filter" : { "term" : { "gender" : "female" }},
+ "rock" : {
+ "filter" : { "term" : { "genre" : "rock" }},
"aggs" : {
- "height_stats" : { "stats" : { "field" : "height" }}
+ "playback_stats" : { "stats" : { "field" : "play_count" }}
}
}
}
@@ -359,7 +363,7 @@ PATH := []*[height_stats.avg" : "desc" }, { "_count" : "desc" } ]
+ "field" : "artist.country",
+ "order" : [ { "rock>playback_stats.avg" : "desc" }, { "_count" : "desc" } ]
},
"aggs" : {
- "females" : {
- "filter" : { "term" : { "gender" : { "female" }}},
+ "rock" : {
+ "filter" : { "term" : { "genre" : { "rock" }}},
"aggs" : {
- "height_stats" : { "stats" : { "field" : "height" }}
+ "playback_stats" : { "stats" : { "field" : "play_count" }}
}
}
}
@@ -385,7 +389,7 @@ Multiple criteria can be used to order the buckets by providing an array of orde
}
--------------------------------------------------
-The above will sort the countries buckets based on the average height among the female population and then by
+The above will sort the artist's countries buckets based on the average play count among the rock songs and then by
their `doc_count` in descending order.
NOTE: In the event that two buckets share the same values for all order criteria the bucket's term value is used as a
@@ -439,10 +443,10 @@ Generating the terms using a script:
--------------------------------------------------
{
"aggs" : {
- "genders" : {
+ "genres" : {
"terms" : {
"script" : {
- "inline": "doc['gender'].value"
+ "inline": "doc['genre'].value"
"lang": "painless"
}
}
@@ -457,12 +461,12 @@ This will interpret the `script` parameter as an `inline` script with the defaul
--------------------------------------------------
{
"aggs" : {
- "genders" : {
+ "genres" : {
"terms" : {
"script" : {
"file": "my_script",
"params": {
- "field": "gender"
+ "field": "genre"
}
}
}
@@ -480,11 +484,11 @@ TIP: for indexed scripts replace the `file` parameter with an `id` parameter.
--------------------------------------------------
{
"aggs" : {
- "genders" : {
+ "genres" : {
"terms" : {
- "field" : "gender",
+ "field" : "gendre",
"script" : {
- "inline" : "'Gender: ' +_value"
+ "inline" : "'Genre: ' +_value"
"lang" : "painless"
}
}
diff --git a/docs/reference/ingest/ingest-node.asciidoc b/docs/reference/ingest/ingest-node.asciidoc
index b03ed641de7..ec4f9c30e66 100644
--- a/docs/reference/ingest/ingest-node.asciidoc
+++ b/docs/reference/ingest/ingest-node.asciidoc
@@ -46,7 +46,6 @@ PUT _ingest/pipeline/my-pipeline-id
"value": "bar"
}
}
- // other processors
]
}
--------------------------------------------------
@@ -83,7 +82,6 @@ Example response:
"value": "bar"
}
}
- // other processors
]
}
} ]
diff --git a/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/InternalMatrixStats.java b/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/InternalMatrixStats.java
index edef75389c8..20be7e72888 100644
--- a/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/InternalMatrixStats.java
+++ b/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/InternalMatrixStats.java
@@ -36,8 +36,8 @@ import java.util.Map;
*/
public class InternalMatrixStats extends InternalMetricsAggregation implements MatrixStats {
- public final static Type TYPE = new Type("matrix_stats");
- public final static AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
+ public static final Type TYPE = new Type("matrix_stats");
+ public static final AggregationStreams.Stream STREAM = new AggregationStreams.Stream() {
@Override
public InternalMatrixStats readResult(StreamInput in) throws IOException {
InternalMatrixStats result = new InternalMatrixStats();
diff --git a/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/MatrixStatsResults.java b/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/MatrixStatsResults.java
index 96b7b74ab4e..1ae29e65761 100644
--- a/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/MatrixStatsResults.java
+++ b/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/matrix/stats/MatrixStatsResults.java
@@ -34,9 +34,9 @@ import java.util.Map;
*/
class MatrixStatsResults implements Writeable {
/** object holding results - computes results in place */
- final protected RunningStats results;
+ protected final RunningStats results;
/** pearson product correlation coefficients */
- final protected Map> correlation;
+ protected final Map> correlation;
/** Base ctor */
public MatrixStatsResults() {
diff --git a/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/support/MultiValuesSourceAggregationBuilder.java b/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/support/MultiValuesSourceAggregationBuilder.java
index 51e5ce1cf27..e3aa171fe3d 100644
--- a/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/support/MultiValuesSourceAggregationBuilder.java
+++ b/modules/aggs-matrix-stats/src/main/java/org/elasticsearch/search/aggregations/support/MultiValuesSourceAggregationBuilder.java
@@ -52,7 +52,7 @@ public abstract class MultiValuesSourceAggregationBuilder>
+ public abstract static class LeafOnly>
extends MultiValuesSourceAggregationBuilder {
protected LeafOnly(String name, Type type, ValuesSourceType valuesSourceType, ValueType targetValueType) {
diff --git a/modules/aggs-matrix-stats/src/test/java/org/elasticsearch/search/aggregations/matrix/stats/BaseMatrixStatsTestCase.java b/modules/aggs-matrix-stats/src/test/java/org/elasticsearch/search/aggregations/matrix/stats/BaseMatrixStatsTestCase.java
index b1296bb1146..2e4fa4313bd 100644
--- a/modules/aggs-matrix-stats/src/test/java/org/elasticsearch/search/aggregations/matrix/stats/BaseMatrixStatsTestCase.java
+++ b/modules/aggs-matrix-stats/src/test/java/org/elasticsearch/search/aggregations/matrix/stats/BaseMatrixStatsTestCase.java
@@ -34,8 +34,8 @@ public abstract class BaseMatrixStatsTestCase extends ESTestCase {
protected final ArrayList fieldA = new ArrayList<>(numObs);
protected final ArrayList fieldB = new ArrayList<>(numObs);
protected final MultiPassStats actualStats = new MultiPassStats();
- protected final static String fieldAKey = "fieldA";
- protected final static String fieldBKey = "fieldB";
+ protected static final String fieldAKey = "fieldA";
+ protected static final String fieldBKey = "fieldB";
@Before
public void setup() {
diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/AbstractStringProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/AbstractStringProcessor.java
index d99bcb550a9..079ff73846a 100644
--- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/AbstractStringProcessor.java
+++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/AbstractStringProcessor.java
@@ -53,7 +53,7 @@ abstract class AbstractStringProcessor extends AbstractProcessor {
protected abstract String process(String value);
- static abstract class Factory implements Processor.Factory {
+ abstract static class Factory implements Processor.Factory {
protected final String processorType;
protected Factory(String processorType) {
diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/GrokProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/GrokProcessor.java
index fe607e12b6e..44528bdac82 100644
--- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/GrokProcessor.java
+++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/GrokProcessor.java
@@ -114,7 +114,7 @@ public final class GrokProcessor extends AbstractProcessor {
return combinedPattern;
}
- public final static class Factory implements Processor.Factory {
+ public static final class Factory implements Processor.Factory {
private final Map builtinPatterns;
diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/JoinProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/JoinProcessor.java
index 7a8916cd439..6b4327f726d 100644
--- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/JoinProcessor.java
+++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/JoinProcessor.java
@@ -70,7 +70,7 @@ public final class JoinProcessor extends AbstractProcessor {
return TYPE;
}
- public final static class Factory implements Processor.Factory {
+ public static final class Factory implements Processor.Factory {
@Override
public JoinProcessor create(Map registry, String processorTag,
Map config) throws Exception {
diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/LowercaseProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/LowercaseProcessor.java
index e7a8f3f3e6a..a0ae8e13158 100644
--- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/LowercaseProcessor.java
+++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/LowercaseProcessor.java
@@ -44,7 +44,7 @@ public final class LowercaseProcessor extends AbstractStringProcessor {
return TYPE;
}
- public final static class Factory extends AbstractStringProcessor.Factory {
+ public static final class Factory extends AbstractStringProcessor.Factory {
public Factory() {
super(TYPE);
diff --git a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/SortProcessor.java b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/SortProcessor.java
index 0eb3843f666..411b22adef0 100644
--- a/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/SortProcessor.java
+++ b/modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/SortProcessor.java
@@ -111,7 +111,7 @@ public final class SortProcessor extends AbstractProcessor {
return TYPE;
}
- public final static class Factory implements Processor.Factory {
+ public static final class Factory implements Processor.Factory {
@Override
public SortProcessor create(Map registry, String processorTag,
diff --git a/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/SearchFieldsTests.java b/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/SearchFieldsTests.java
index 28894c5c1cc..d3871e90510 100644
--- a/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/SearchFieldsTests.java
+++ b/modules/lang-groovy/src/test/java/org/elasticsearch/messy/tests/SearchFieldsTests.java
@@ -465,7 +465,7 @@ public class SearchFieldsTests extends ESIntegTestCase {
String dateTime = Joda.forPattern("dateOptionalTime").printer().print(new DateTime(2012, 3, 22, 0, 0, DateTimeZone.UTC));
assertThat(searchResponse.getHits().getAt(0).fields().get("date_field").value(), equalTo((Object) dateTime));
assertThat(searchResponse.getHits().getAt(0).fields().get("boolean_field").value(), equalTo((Object) Boolean.TRUE));
- assertThat(((BytesReference) searchResponse.getHits().getAt(0).fields().get("binary_field").value()).toBytesArray(), equalTo((BytesReference) new BytesArray("testing text".getBytes("UTF8"))));
+ assertThat(((BytesReference) searchResponse.getHits().getAt(0).fields().get("binary_field").value()), equalTo((BytesReference) new BytesArray("testing text".getBytes("UTF8"))));
}
diff --git a/modules/lang-mustache/src/main/java/org/elasticsearch/rest/action/search/template/RestSearchTemplateAction.java b/modules/lang-mustache/src/main/java/org/elasticsearch/rest/action/search/template/RestSearchTemplateAction.java
index 131443da887..e12137ee3c5 100644
--- a/modules/lang-mustache/src/main/java/org/elasticsearch/rest/action/search/template/RestSearchTemplateAction.java
+++ b/modules/lang-mustache/src/main/java/org/elasticsearch/rest/action/search/template/RestSearchTemplateAction.java
@@ -73,7 +73,7 @@ public class RestSearchTemplateAction extends BaseRestHandler {
request.setScriptType(ScriptService.ScriptType.INLINE);
if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
try (XContentBuilder builder = XContentFactory.contentBuilder(parser.contentType())) {
- request.setScript(builder.copyCurrentStructure(parser).bytes().toUtf8());
+ request.setScript(builder.copyCurrentStructure(parser).bytes().utf8ToString());
} catch (IOException e) {
throw new ParsingException(parser.getTokenLocation(), "Could not parse inline template", e);
}
diff --git a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java
index ceb187bcc63..8419730dc1c 100644
--- a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java
+++ b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomMustacheFactory.java
@@ -92,7 +92,7 @@ public class CustomMustacheFactory extends DefaultMustacheFactory {
/**
* Base class for custom Mustache functions
*/
- static abstract class CustomCode extends IterableCode {
+ abstract static class CustomCode extends IterableCode {
private final String code;
diff --git a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomReflectionObjectHandler.java b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomReflectionObjectHandler.java
index 45d3d8c182d..dd3055ba8e8 100644
--- a/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomReflectionObjectHandler.java
+++ b/modules/lang-mustache/src/main/java/org/elasticsearch/script/mustache/CustomReflectionObjectHandler.java
@@ -49,7 +49,7 @@ final class CustomReflectionObjectHandler extends ReflectionObjectHandler {
}
}
- final static class ArrayMap extends AbstractMap