Replace NOT operator with explicit false check (#68124)

Part 3.

We have an in-house rule to compare explicitly against `false` instead
of using the logical not operator (`!`). However, this hasn't
historically been enforced, meaning that there are many violations in
the source at present.

We now have a Checkstyle rule that can detect these cases, but before we
can turn it on, we need to fix the existing violations. This is being
done over a series of PRs, since there are a lot to fix.
This commit is contained in:
Rory Hunter 2021-01-29 13:51:41 +00:00 committed by Rory Hunter
parent 78c6d73a65
commit 6c8ed22e95
101 changed files with 196 additions and 192 deletions

View file

@ -97,7 +97,7 @@ public class HotThreadsIT extends ESIntegTestCase {
} }
success = true; success = true;
} finally { } finally {
if (!success) { if (success == false) {
hasErrors.set(true); hasErrors.set(true);
} }
latch.countDown(); latch.countDown();

View file

@ -529,7 +529,7 @@ public class BulkWithUpdatesIT extends ESIntegTestCase {
int successes = 0; int successes = 0;
for (BulkResponse response : responses) { for (BulkResponse response : responses) {
if (!response.hasFailures()) { if (response.hasFailures() == false) {
successes++; successes++;
} }
} }

View file

@ -219,11 +219,11 @@ public class GetTermVectorsIT extends AbstractTermVectorsTestCase {
} }
public static String termVectorOptionsToString(FieldType fieldType) { public static String termVectorOptionsToString(FieldType fieldType) {
if (!fieldType.storeTermVectors()) { if (fieldType.storeTermVectors() == false) {
return "no"; return "no";
} else if (!fieldType.storeTermVectorOffsets() && !fieldType.storeTermVectorPositions()) { } else if (fieldType.storeTermVectorOffsets() == false && fieldType.storeTermVectorPositions() == false) {
return "yes"; return "yes";
} else if (fieldType.storeTermVectorOffsets() && !fieldType.storeTermVectorPositions()) { } else if (fieldType.storeTermVectorOffsets() && fieldType.storeTermVectorPositions() == false) {
return "with_offsets"; return "with_offsets";
} else { } else {
StringBuilder builder = new StringBuilder("with"); StringBuilder builder = new StringBuilder("with");

View file

@ -49,7 +49,7 @@ public class SimpleAllocationIT extends ESIntegTestCase {
ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState(); ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState();
assertThat(state.getRoutingNodes().unassigned().size(), equalTo(0)); assertThat(state.getRoutingNodes().unassigned().size(), equalTo(0));
for (RoutingNode node : state.getRoutingNodes()) { for (RoutingNode node : state.getRoutingNodes()) {
if (!node.isEmpty()) { if (node.isEmpty() == false) {
assertThat(node.size(), equalTo(2)); assertThat(node.size(), equalTo(2));
} }
} }
@ -60,7 +60,7 @@ public class SimpleAllocationIT extends ESIntegTestCase {
assertThat(state.getRoutingNodes().unassigned().size(), equalTo(0)); assertThat(state.getRoutingNodes().unassigned().size(), equalTo(0));
for (RoutingNode node : state.getRoutingNodes()) { for (RoutingNode node : state.getRoutingNodes()) {
if (!node.isEmpty()) { if (node.isEmpty() == false) {
assertThat(node.size(), equalTo(1)); assertThat(node.size(), equalTo(1));
} }
} }
@ -79,7 +79,7 @@ public class SimpleAllocationIT extends ESIntegTestCase {
assertThat(state.getRoutingNodes().unassigned().size(), equalTo(0)); assertThat(state.getRoutingNodes().unassigned().size(), equalTo(0));
for (RoutingNode node : state.getRoutingNodes()) { for (RoutingNode node : state.getRoutingNodes()) {
if (!node.isEmpty()) { if (node.isEmpty() == false) {
assertThat(node.size(), equalTo(4)); assertThat(node.size(), equalTo(4));
} }
} }

View file

@ -46,8 +46,7 @@ public class RecoverAfterNodesIT extends ESIntegTestCase {
do { do {
blocks = nodeClient.admin().cluster().prepareState().setLocal(true).execute().actionGet() blocks = nodeClient.admin().cluster().prepareState().setLocal(true).execute().actionGet()
.getState().blocks().global(ClusterBlockLevel.METADATA_WRITE); .getState().blocks().global(ClusterBlockLevel.METADATA_WRITE);
} } while (blocks.isEmpty() == false && (System.currentTimeMillis() - start) < timeout.millis());
while (!blocks.isEmpty() && (System.currentTimeMillis() - start) < timeout.millis());
return blocks; return blocks;
} }

View file

@ -210,14 +210,14 @@ public class CorruptedFileIT extends ESIntegTestCase {
Store store = indexShard.store(); Store store = indexShard.store();
store.incRef(); store.incRef();
try { try {
if (!Lucene.indexExists(store.directory()) && indexShard.state() == IndexShardState.STARTED) { if (Lucene.indexExists(store.directory()) == false && indexShard.state() == IndexShardState.STARTED) {
return; return;
} }
BytesStreamOutput os = new BytesStreamOutput(); BytesStreamOutput os = new BytesStreamOutput();
PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8.name()); PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8.name());
CheckIndex.Status status = store.checkIndex(out); CheckIndex.Status status = store.checkIndex(out);
out.flush(); out.flush();
if (!status.clean) { if (status.clean == false) {
logger.warn("check index [failure]\n{}", os.bytes().utf8ToString()); logger.warn("check index [failure]\n{}", os.bytes().utf8ToString());
throw new IOException("index check failure"); throw new IOException("index check failure");
} }

View file

@ -126,8 +126,8 @@ public class ExceptionRetryIT extends ESIntegTestCase {
long dupCounter = 0; long dupCounter = 0;
boolean found_duplicate_already = false; boolean found_duplicate_already = false;
for (int i = 0; i < searchResponse.getHits().getHits().length; i++) { for (int i = 0; i < searchResponse.getHits().getHits().length; i++) {
if (!uniqueIds.add(searchResponse.getHits().getHits()[i].getId())) { if (uniqueIds.add(searchResponse.getHits().getHits()[i].getId()) == false) {
if (!found_duplicate_already) { if (found_duplicate_already == false) {
SearchResponse dupIdResponse = client().prepareSearch("index").setQuery(termQuery("_id", SearchResponse dupIdResponse = client().prepareSearch("index").setQuery(termQuery("_id",
searchResponse.getHits().getHits()[i].getId())).setExplain(true).get(); searchResponse.getHits().getHits()[i].getId())).setExplain(true).get();
assertThat(dupIdResponse.getHits().getTotalHits().value, greaterThan(1L)); assertThat(dupIdResponse.getHits().getTotalHits().value, greaterThan(1L));

View file

@ -59,7 +59,7 @@ public class PreBuiltAnalyzerIntegrationIT extends ESIntegTestCase {
String name = preBuiltAnalyzer.name().toLowerCase(Locale.ROOT); String name = preBuiltAnalyzer.name().toLowerCase(Locale.ROOT);
Version randomVersion = randomVersion(random()); Version randomVersion = randomVersion(random());
if (!loadedAnalyzers.containsKey(preBuiltAnalyzer)) { if (loadedAnalyzers.containsKey(preBuiltAnalyzer) == false) {
loadedAnalyzers.put(preBuiltAnalyzer, new ArrayList<Version>()); loadedAnalyzers.put(preBuiltAnalyzer, new ArrayList<Version>());
} }
loadedAnalyzers.get(preBuiltAnalyzer).add(randomVersion); loadedAnalyzers.get(preBuiltAnalyzer).add(randomVersion);

View file

@ -383,7 +383,7 @@ public class CircuitBreakerServiceIT extends ESIntegTestCase {
// can either fail directly with an exception or the response contains exceptions (depending on client) // can either fail directly with an exception or the response contains exceptions (depending on client)
try { try {
BulkResponse response = client.bulk(bulkRequest).actionGet(); BulkResponse response = client.bulk(bulkRequest).actionGet();
if (!response.hasFailures()) { if (response.hasFailures() == false) {
fail("Should have thrown CircuitBreakingException"); fail("Should have thrown CircuitBreakingException");
} else { } else {
// each item must have failed with CircuitBreakingException // each item must have failed with CircuitBreakingException

View file

@ -408,7 +408,7 @@ public class IndexStatsIT extends ESIntegTestCase {
// make sure we see throttling kicking in: // make sure we see throttling kicking in:
boolean done = false; boolean done = false;
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
while (!done) { while (done == false) {
for(int i=0; i<100; i++) { for(int i=0; i<100; i++) {
// Provoke slowish merging by making many unique terms: // Provoke slowish merging by making many unique terms:
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
@ -1143,7 +1143,7 @@ public class IndexStatsIT extends ESIntegTestCase {
executionFailures.get().add(e); executionFailures.get().add(e);
latch.countDown(); latch.countDown();
} }
while (!stop.get()) { while (stop.get() == false) {
final String id = Integer.toString(idGenerator.incrementAndGet()); final String id = Integer.toString(idGenerator.incrementAndGet());
final IndexResponse response = final IndexResponse response =
client() client()
@ -1171,7 +1171,7 @@ public class IndexStatsIT extends ESIntegTestCase {
final IndicesStatsRequest request = new IndicesStatsRequest(); final IndicesStatsRequest request = new IndicesStatsRequest();
request.all(); request.all();
request.indices(new String[0]); request.indices(new String[0]);
while (!stop.get()) { while (stop.get() == false) {
try { try {
final IndicesStatsResponse response = client().admin().indices().stats(request).get(); final IndicesStatsResponse response = client().admin().indices().stats(request).get();
if (response.getFailedShards() > 0) { if (response.getFailedShards() > 0) {

View file

@ -115,11 +115,11 @@ public class MinDocCountIT extends AbstractTermsTestCase {
String stringTerm; String stringTerm;
do { do {
stringTerm = RandomStrings.randomAsciiOfLength(random(), 8); stringTerm = RandomStrings.randomAsciiOfLength(random(), 8);
} while (!stringTerms.add(stringTerm)); } while (stringTerms.add(stringTerm) == false);
long longTerm; long longTerm;
do { do {
longTerm = randomInt(cardinality * 2); longTerm = randomInt(cardinality * 2);
} while (!longTerms.add(longTerm)); } while (longTerms.add(longTerm) == false);
double doubleTerm = longTerm * Math.PI; double doubleTerm = longTerm * Math.PI;
ZonedDateTime time = ZonedDateTime.of(2014, 1, ((int) longTerm % 20) + 1, 0, 0, 0, 0, ZoneOffset.UTC); ZonedDateTime time = ZonedDateTime.of(2014, 1, ((int) longTerm % 20) + 1, 0, 0, 0, 0, ZoneOffset.UTC);

View file

@ -606,10 +606,10 @@ public class DerivativeIT extends ESIntegTestCase {
} else if (cause instanceof SearchPhaseExecutionException) { } else if (cause instanceof SearchPhaseExecutionException) {
SearchPhaseExecutionException spee = (SearchPhaseExecutionException) e; SearchPhaseExecutionException spee = (SearchPhaseExecutionException) e;
Throwable rootCause = spee.getRootCause(); Throwable rootCause = spee.getRootCause();
if (!(rootCause instanceof IllegalArgumentException)) { if ((rootCause instanceof IllegalArgumentException) == false) {
throw e; throw e;
} }
} else if (!(cause instanceof IllegalArgumentException)) { } else if ((cause instanceof IllegalArgumentException) == false) {
throw e; throw e;
} }
} }

View file

@ -458,10 +458,10 @@ public class ExtendedStatsBucketIT extends ESIntegTestCase {
} else if (cause instanceof SearchPhaseExecutionException) { } else if (cause instanceof SearchPhaseExecutionException) {
SearchPhaseExecutionException spee = (SearchPhaseExecutionException) ex; SearchPhaseExecutionException spee = (SearchPhaseExecutionException) ex;
Throwable rootCause = spee.getRootCause(); Throwable rootCause = spee.getRootCause();
if (!(rootCause instanceof IllegalArgumentException)) { if ((rootCause instanceof IllegalArgumentException) == false) {
throw ex; throw ex;
} }
} else if (!(cause instanceof IllegalArgumentException)) { } else if ((cause instanceof IllegalArgumentException) == false) {
throw ex; throw ex;
} }
} }

View file

@ -416,10 +416,10 @@ public class PercentilesBucketIT extends ESIntegTestCase {
} else if (cause instanceof SearchPhaseExecutionException) { } else if (cause instanceof SearchPhaseExecutionException) {
SearchPhaseExecutionException spee = (SearchPhaseExecutionException) e; SearchPhaseExecutionException spee = (SearchPhaseExecutionException) e;
Throwable rootCause = spee.getRootCause(); Throwable rootCause = spee.getRootCause();
if (!(rootCause instanceof IllegalArgumentException)) { if ((rootCause instanceof IllegalArgumentException) == false) {
throw e; throw e;
} }
} else if (!(cause instanceof IllegalArgumentException)) { } else if ((cause instanceof IllegalArgumentException) == false) {
throw e; throw e;
} }
} }
@ -450,10 +450,10 @@ public class PercentilesBucketIT extends ESIntegTestCase {
} else if (cause instanceof SearchPhaseExecutionException) { } else if (cause instanceof SearchPhaseExecutionException) {
SearchPhaseExecutionException spee = (SearchPhaseExecutionException) e; SearchPhaseExecutionException spee = (SearchPhaseExecutionException) e;
Throwable rootCause = spee.getRootCause(); Throwable rootCause = spee.getRootCause();
if (!(rootCause instanceof IllegalArgumentException)) { if ((rootCause instanceof IllegalArgumentException) == false) {
throw e; throw e;
} }
} else if (!(cause instanceof IllegalArgumentException)) { } else if ((cause instanceof IllegalArgumentException) == false) {
throw e; throw e;
} }
} }

View file

@ -93,13 +93,13 @@ public class SerialDiffIT extends ESIntegTestCase {
} }
private void assertValidIterators(Iterator expectedBucketIter, Iterator expectedCountsIter, Iterator expectedValuesIter) { private void assertValidIterators(Iterator expectedBucketIter, Iterator expectedCountsIter, Iterator expectedValuesIter) {
if (!expectedBucketIter.hasNext()) { if (expectedBucketIter.hasNext() == false) {
fail("`expectedBucketIter` iterator ended before `actual` iterator, size mismatch"); fail("`expectedBucketIter` iterator ended before `actual` iterator, size mismatch");
} }
if (!expectedCountsIter.hasNext()) { if (expectedCountsIter.hasNext() == false) {
fail("`expectedCountsIter` iterator ended before `actual` iterator, size mismatch"); fail("`expectedCountsIter` iterator ended before `actual` iterator, size mismatch");
} }
if (!expectedValuesIter.hasNext()) { if (expectedValuesIter.hasNext() == false) {
fail("`expectedValuesIter` iterator ended before `actual` iterator, size mismatch"); fail("`expectedValuesIter` iterator ended before `actual` iterator, size mismatch");
} }
} }
@ -207,7 +207,7 @@ public class SerialDiffIT extends ESIntegTestCase {
} }
// Both have values, calculate diff and replace the "empty" bucket // Both have values, calculate diff and replace the "empty" bucket
if (!Double.isNaN(metricValue) && !Double.isNaN(lagValue)) { if (Double.isNaN(metricValue) == false && Double.isNaN(lagValue) == false) {
double diff = metricValue - lagValue; double diff = metricValue - lagValue;
values.add(diff); values.add(diff);
} else { } else {

View file

@ -73,7 +73,7 @@ public class SearchWhileRelocatingIT extends ESIntegTestCase {
@Override @Override
public void run() { public void run() {
try { try {
while (!stop.get()) { while (stop.get() == false) {
SearchResponse sr = client().prepareSearch().setSize(numDocs).get(); SearchResponse sr = client().prepareSearch().setSize(numDocs).get();
if (sr.getHits().getTotalHits().value != numDocs) { if (sr.getHits().getTotalHits().value != numDocs) {
// if we did not search all shards but had no failures that is potentially fine // if we did not search all shards but had no failures that is potentially fine
@ -96,7 +96,7 @@ public class SearchWhileRelocatingIT extends ESIntegTestCase {
} catch (SearchPhaseExecutionException ex) { } catch (SearchPhaseExecutionException ex) {
// it's possible that all shards fail if we have a small number of shards. // it's possible that all shards fail if we have a small number of shards.
// with replicas this should not happen // with replicas this should not happen
if (numberOfReplicas == 1 || !ex.getMessage().contains("all shards failed")) { if (numberOfReplicas == 1 || ex.getMessage().contains("all shards failed") == false) {
throw ex; throw ex;
} }
} }
@ -117,7 +117,7 @@ public class SearchWhileRelocatingIT extends ESIntegTestCase {
.setWaitForNoRelocatingShards(true).setWaitForEvents(Priority.LANGUID).setTimeout("5m").get(); .setWaitForNoRelocatingShards(true).setWaitForEvents(Priority.LANGUID).setTimeout("5m").get();
assertNoTimeout(resp); assertNoTimeout(resp);
// if we hit only non-critical exceptions we make sure that the post search works // if we hit only non-critical exceptions we make sure that the post search works
if (!nonCriticalExceptions.isEmpty()) { if (nonCriticalExceptions.isEmpty() == false) {
logger.info("non-critical exceptions: {}", nonCriticalExceptions); logger.info("non-critical exceptions: {}", nonCriticalExceptions);
for (int j = 0; j < 10; j++) { for (int j = 0; j < 10; j++) {
assertHitCount(client().prepareSearch().get(), numDocs); assertHitCount(client().prepareSearch().get(), numDocs);

View file

@ -170,7 +170,7 @@ public class SearchWithRandomIOExceptionsIT extends ESIntegTestCase {
.setQuery(QueryBuilders.matchQuery("test", English.intToEnglish(docToQuery))) .setQuery(QueryBuilders.matchQuery("test", English.intToEnglish(docToQuery)))
.setSize(expectedResults).get(); .setSize(expectedResults).get();
logger.info("Successful shards: [{}] numShards: [{}]", searchResponse.getSuccessfulShards(), numShards.numPrimaries); logger.info("Successful shards: [{}] numShards: [{}]", searchResponse.getSuccessfulShards(), numShards.numPrimaries);
if (searchResponse.getSuccessfulShards() == numShards.numPrimaries && !refreshFailed) { if (searchResponse.getSuccessfulShards() == numShards.numPrimaries && refreshFailed == false) {
assertResultsAndLogOnFailure(expectedResults, searchResponse); assertResultsAndLogOnFailure(expectedResults, searchResponse);
} }
// check match all // check match all
@ -178,14 +178,15 @@ public class SearchWithRandomIOExceptionsIT extends ESIntegTestCase {
.setSize(numCreated + numInitialDocs).addSort("_uid", SortOrder.ASC).get(); .setSize(numCreated + numInitialDocs).addSort("_uid", SortOrder.ASC).get();
logger.info("Match all Successful shards: [{}] numShards: [{}]", searchResponse.getSuccessfulShards(), logger.info("Match all Successful shards: [{}] numShards: [{}]", searchResponse.getSuccessfulShards(),
numShards.numPrimaries); numShards.numPrimaries);
if (searchResponse.getSuccessfulShards() == numShards.numPrimaries && !refreshFailed) { if (searchResponse.getSuccessfulShards() == numShards.numPrimaries && refreshFailed == false) {
assertResultsAndLogOnFailure(numCreated + numInitialDocs, searchResponse); assertResultsAndLogOnFailure(numCreated + numInitialDocs, searchResponse);
} }
} catch (SearchPhaseExecutionException ex) { } catch (SearchPhaseExecutionException ex) {
logger.info("SearchPhaseException: [{}]", ex.getMessage()); logger.info("SearchPhaseException: [{}]", ex.getMessage());
// if a scheduled refresh or flush fails all shards we see all shards failed here // if a scheduled refresh or flush fails all shards we see all shards failed here
if (!(expectAllShardsFailed || refreshResponse.getSuccessfulShards() == 0 || if ((expectAllShardsFailed
ex.getMessage().contains("all shards failed"))) { || refreshResponse.getSuccessfulShards() == 0
|| ex.getMessage().contains("all shards failed")) == false) {
throw ex; throw ex;
} }
} }

View file

@ -475,7 +475,7 @@ public class QueryRescorerIT extends ESIntegTestCase {
QueryRescorerBuilder innerRescoreQuery = new QueryRescorerBuilder(matchQuery("field1", "the quick brown").boost(4.0f)) QueryRescorerBuilder innerRescoreQuery = new QueryRescorerBuilder(matchQuery("field1", "the quick brown").boost(4.0f))
.setQueryWeight(0.5f).setRescoreQueryWeight(0.4f); .setQueryWeight(0.5f).setRescoreQueryWeight(0.4f);
if (!"".equals(scoreModes[innerMode])) { if ("".equals(scoreModes[innerMode]) == false) {
innerRescoreQuery.setScoreMode(QueryRescoreMode.fromString(scoreModes[innerMode])); innerRescoreQuery.setScoreMode(QueryRescoreMode.fromString(scoreModes[innerMode]));
} }
@ -497,7 +497,7 @@ public class QueryRescorerIT extends ESIntegTestCase {
QueryRescorerBuilder outerRescoreQuery = new QueryRescorerBuilder(matchQuery("field1", "the quick brown").boost(4.0f)) QueryRescorerBuilder outerRescoreQuery = new QueryRescorerBuilder(matchQuery("field1", "the quick brown").boost(4.0f))
.setQueryWeight(0.5f).setRescoreQueryWeight(0.4f); .setQueryWeight(0.5f).setRescoreQueryWeight(0.4f);
if (!"".equals(scoreModes[outerMode])) { if ("".equals(scoreModes[outerMode]) == false) {
outerRescoreQuery.setScoreMode(QueryRescoreMode.fromString(scoreModes[outerMode])); outerRescoreQuery.setScoreMode(QueryRescoreMode.fromString(scoreModes[outerMode]));
} }
@ -544,7 +544,7 @@ public class QueryRescorerIT extends ESIntegTestCase {
.should(functionScoreQuery(termQuery("field1", intToEnglish[3]), weightFactorFunction(0.0f)).boostMode(REPLACE))); .should(functionScoreQuery(termQuery("field1", intToEnglish[3]), weightFactorFunction(0.0f)).boostMode(REPLACE)));
rescoreQuery.setQueryWeight(primaryWeight).setRescoreQueryWeight(secondaryWeight); rescoreQuery.setQueryWeight(primaryWeight).setRescoreQueryWeight(secondaryWeight);
if (!"".equals(scoreMode)) { if ("".equals(scoreMode) == false) {
rescoreQuery.setScoreMode(QueryRescoreMode.fromString(scoreMode)); rescoreQuery.setScoreMode(QueryRescoreMode.fromString(scoreMode));
} }

View file

@ -127,7 +127,7 @@ public class DuelScrollIT extends ESIntegTestCase {
int numMissingDocs = scaledRandomIntBetween(0, numDocs / 100); int numMissingDocs = scaledRandomIntBetween(0, numDocs / 100);
IntHashSet missingDocs = new IntHashSet(numMissingDocs); IntHashSet missingDocs = new IntHashSet(numMissingDocs);
for (int i = 0; i < numMissingDocs; i++) { for (int i = 0; i < numMissingDocs; i++) {
while (!missingDocs.add(randomInt(numDocs))) {} while (missingDocs.add(randomInt(numDocs)) == false) {}
} }
for (int i = 1; i <= numDocs; i++) { for (int i = 1; i <= numDocs; i++) {

View file

@ -206,7 +206,7 @@ public class SearchAfterIT extends ESIntegTestCase {
} }
for (int i = 0; i < o1.size(); i++) { for (int i = 0; i < o1.size(); i++) {
if (!(o1.get(i) instanceof Comparable)) { if ((o1.get(i) instanceof Comparable) == false) {
throw new RuntimeException(o1.get(i).getClass() + " is not comparable"); throw new RuntimeException(o1.get(i).getClass() + " is not comparable");
} }
Object cmp1 = o1.get(i); Object cmp1 = o1.get(i);

View file

@ -305,7 +305,7 @@ public class FieldSortIT extends ESIntegTestCase {
assertThat(searchResponse.getHits().getAt(i).getSortValues()[0].toString(), equalTo(next.getKey().utf8ToString())); assertThat(searchResponse.getHits().getAt(i).getSortValues()[0].toString(), equalTo(next.getKey().utf8ToString()));
} }
} }
if (!sparseBytes.isEmpty()) { if (sparseBytes.isEmpty() == false) {
int size = between(1, sparseBytes.size()); int size = between(1, sparseBytes.size());
SearchResponse searchResponse = client().prepareSearch().setQuery(matchAllQuery()) SearchResponse searchResponse = client().prepareSearch().setQuery(matchAllQuery())
.setPostFilter(QueryBuilders.existsQuery("sparse_bytes")).setSize(size).addSort("sparse_bytes", SortOrder.ASC).get(); .setPostFilter(QueryBuilders.existsQuery("sparse_bytes")).setSize(size).addSort("sparse_bytes", SortOrder.ASC).get();

View file

@ -231,18 +231,18 @@ public class MultiGetRequest extends ActionRequest
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof Item)) return false; if ((o instanceof Item) == false) return false;
Item item = (Item) o; Item item = (Item) o;
if (version != item.version) return false; if (version != item.version) return false;
if (fetchSourceContext != null ? !fetchSourceContext.equals(item.fetchSourceContext) : item.fetchSourceContext != null) if (fetchSourceContext != null ? fetchSourceContext.equals(item.fetchSourceContext) == false : item.fetchSourceContext != null)
return false; return false;
if (!Arrays.equals(storedFields, item.storedFields)) return false; if (Arrays.equals(storedFields, item.storedFields) == false) return false;
if (!id.equals(item.id)) return false; if (id.equals(item.id) == false) return false;
if (!index.equals(item.index)) return false; if (index.equals(item.index) == false) return false;
if (routing != null ? !routing.equals(item.routing) : item.routing != null) return false; if (routing != null ? routing.equals(item.routing) == false : item.routing != null) return false;
if (type != null ? !type.equals(item.type) : item.type != null) return false; if (type != null ? type.equals(item.type) == false : item.type != null) return false;
if (versionType != item.versionType) return false; if (versionType != item.versionType) return false;
return true; return true;
@ -425,7 +425,7 @@ public class MultiGetRequest extends ActionRequest
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token.isValue()) { } else if (token.isValue()) {
if (INDEX.match(currentFieldName, parser.getDeprecationHandler())) { if (INDEX.match(currentFieldName, parser.getDeprecationHandler())) {
if (!allowExplicitIndex) { if (allowExplicitIndex == false) {
throw new IllegalArgumentException("explicit index in multi get is not allowed"); throw new IllegalArgumentException("explicit index in multi get is not allowed");
} }
index = parser.text(); index = parser.text();
@ -523,7 +523,7 @@ public class MultiGetRequest extends ActionRequest
@Nullable String defaultRouting) throws IOException { @Nullable String defaultRouting) throws IOException {
Token token; Token token;
while ((token = parser.nextToken()) != Token.END_ARRAY) { while ((token = parser.nextToken()) != Token.END_ARRAY) {
if (!token.isValue()) { if (token.isValue() == false) {
throw new IllegalArgumentException("ids array element should only contain ids"); throw new IllegalArgumentException("ids array element should only contain ids");
} }
items.add(new Item(defaultIndex, defaultType, parser.text()).storedFields(defaultFields).fetchSourceContext(defaultFetchSource) items.add(new Item(defaultIndex, defaultType, parser.text()).storedFields(defaultFields).fetchSourceContext(defaultFetchSource)

View file

@ -132,7 +132,7 @@ public class GetPipelineResponse extends ActionResponse implements StatusToXCont
} }
for (PipelineConfiguration pipeline: pipelines) { for (PipelineConfiguration pipeline: pipelines) {
PipelineConfiguration otherPipeline = otherPipelineMap.get(pipeline.getId()); PipelineConfiguration otherPipeline = otherPipelineMap.get(pipeline.getId());
if (!pipeline.equals(otherPipeline)) { if (pipeline.equals(otherPipeline) == false) {
return false; return false;
} }
} }

View file

@ -233,7 +233,7 @@ public class MultiSearchRequest extends ActionRequest implements CompositeIndice
for (Map.Entry<String, Object> entry : source.entrySet()) { for (Map.Entry<String, Object> entry : source.entrySet()) {
Object value = entry.getValue(); Object value = entry.getValue();
if ("index".equals(entry.getKey()) || "indices".equals(entry.getKey())) { if ("index".equals(entry.getKey()) || "indices".equals(entry.getKey())) {
if (!allowExplicitIndex) { if (allowExplicitIndex == false) {
throw new IllegalArgumentException("explicit index in multi search is not allowed"); throw new IllegalArgumentException("explicit index in multi search is not allowed");
} }
searchRequest.indices(nodeStringArrayValue(value)); searchRequest.indices(nodeStringArrayValue(value));

View file

@ -275,7 +275,7 @@ public final class SearchPhaseController {
ScoreDoc[] sortedDocs = reducedQueryPhase.sortedTopDocs.scoreDocs; ScoreDoc[] sortedDocs = reducedQueryPhase.sortedTopDocs.scoreDocs;
SearchHits hits = getHits(reducedQueryPhase, ignoreFrom, fetchResults, resultsLookup); SearchHits hits = getHits(reducedQueryPhase, ignoreFrom, fetchResults, resultsLookup);
if (reducedQueryPhase.suggest != null) { if (reducedQueryPhase.suggest != null) {
if (!fetchResults.isEmpty()) { if (fetchResults.isEmpty() == false) {
int currentOffset = hits.getHits().length; int currentOffset = hits.getHits().length;
for (CompletionSuggestion suggestion : reducedQueryPhase.suggest.filter(CompletionSuggestion.class)) { for (CompletionSuggestion suggestion : reducedQueryPhase.suggest.filter(CompletionSuggestion.class)) {
final List<CompletionSuggestion.Entry.Option> suggestionOptions = suggestion.getOptions(); final List<CompletionSuggestion.Entry.Option> suggestionOptions = suggestion.getOptions();
@ -330,7 +330,7 @@ public final class SearchPhaseController {
numSearchHits = Math.min(sortedTopDocs.scoreDocs.length, numSearchHits); numSearchHits = Math.min(sortedTopDocs.scoreDocs.length, numSearchHits);
// merge hits // merge hits
List<SearchHit> hits = new ArrayList<>(); List<SearchHit> hits = new ArrayList<>();
if (!fetchResults.isEmpty()) { if (fetchResults.isEmpty() == false) {
for (int i = 0; i < numSearchHits; i++) { for (int i = 0; i < numSearchHits; i++) {
ScoreDoc shardDoc = sortedTopDocs.scoreDocs[i]; ScoreDoc shardDoc = sortedTopDocs.scoreDocs[i];
SearchPhaseResult fetchResultProvider = resultsLookup.apply(shardDoc.shardIndex); SearchPhaseResult fetchResultProvider = resultsLookup.apply(shardDoc.shardIndex);
@ -659,7 +659,7 @@ public final class SearchPhaseController {
} }
} }
fetchHits += topDocs.topDocs.scoreDocs.length; fetchHits += topDocs.topDocs.scoreDocs.length;
if (!Float.isNaN(topDocs.maxScore)) { if (Float.isNaN(topDocs.maxScore) == false) {
maxScore = Math.max(maxScore, topDocs.maxScore); maxScore = Math.max(maxScore, topDocs.maxScore);
} }
if (timedOut) { if (timedOut) {

View file

@ -60,7 +60,7 @@ public final class DestructiveOperations {
* Fail if there is wildcard usage in indices and the named is required for destructive operations. * Fail if there is wildcard usage in indices and the named is required for destructive operations.
*/ */
public void failDestructive(String[] aliasesOrIndices) { public void failDestructive(String[] aliasesOrIndices) {
if (!destructiveRequiresName) { if (destructiveRequiresName == false) {
return; return;
} }

View file

@ -122,7 +122,7 @@ public class MultiTermVectorsRequest extends ActionRequest
} }
} else if ("ids".equals(currentFieldName)) { } else if ("ids".equals(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
if (!token.isValue()) { if (token.isValue() == false) {
throw new IllegalArgumentException("ids array element should only contain ids"); throw new IllegalArgumentException("ids array element should only contain ids");
} }
ids.add(parser.text()); ids.add(parser.text());

View file

@ -179,7 +179,7 @@ public class TermVectorsFilter {
PostingsEnum docsEnum = null; PostingsEnum docsEnum = null;
for (String fieldName : fields) { for (String fieldName : fields) {
if ((selectedFields != null) && (!selectedFields.contains(fieldName))) { if (selectedFields != null && selectedFields.contains(fieldName) == false) {
continue; continue;
} }
@ -216,7 +216,7 @@ public class TermVectorsFilter {
// now call on docFreq // now call on docFreq
long docFreq = topLevelTermsEnum.docFreq(); long docFreq = topLevelTermsEnum.docFreq();
if (!isAccepted(docFreq)) { if (isAccepted(docFreq) == false) {
continue; continue;
} }

View file

@ -508,9 +508,9 @@ public class TermVectorsRequest extends SingleShardRequest<TermVectorsRequest> i
} }
private void setFlag(Flag flag, boolean set) { private void setFlag(Flag flag, boolean set) {
if (set && !flagsEnum.contains(flag)) { if (set && flagsEnum.contains(flag) == false) {
flagsEnum.add(flag); flagsEnum.add(flag);
} else if (!set) { } else if (set == false) {
flagsEnum.remove(flag); flagsEnum.remove(flag);
assert (!flagsEnum.contains(flag)); assert (!flagsEnum.contains(flag));
} }

View file

@ -139,7 +139,7 @@ public class TermVectorsResponse extends ActionResponse implements ToXContentObj
public Fields getFields() throws IOException { public Fields getFields() throws IOException {
if (hasTermVectors() && isExists()) { if (hasTermVectors() && isExists()) {
if (!sourceCopied) { // make the bytes safe if (sourceCopied == false) { // make the bytes safe
headerRef = new BytesArray(headerRef.toBytesRef(), true); headerRef = new BytesArray(headerRef.toBytesRef(), true);
termVectors = new BytesArray(termVectors.toBytesRef(), true); termVectors = new BytesArray(termVectors.toBytesRef(), true);
} }
@ -174,7 +174,7 @@ public class TermVectorsResponse extends ActionResponse implements ToXContentObj
builder.startObject(); builder.startObject();
builder.field(FieldStrings._INDEX, index); builder.field(FieldStrings._INDEX, index);
builder.field(FieldStrings._TYPE, type); builder.field(FieldStrings._TYPE, type);
if (!isArtificial()) { if (isArtificial() == false) {
builder.field(FieldStrings._ID, id); builder.field(FieldStrings._ID, id);
} }
builder.field(FieldStrings._VERSION, docVersion); builder.field(FieldStrings._VERSION, docVersion);
@ -244,7 +244,7 @@ public class TermVectorsResponse extends ActionResponse implements ToXContentObj
} }
private void buildValues(XContentBuilder builder, Terms curTerms, int termFreq) throws IOException { private void buildValues(XContentBuilder builder, Terms curTerms, int termFreq) throws IOException {
if (!(curTerms.hasPayloads() || curTerms.hasOffsets() || curTerms.hasPositions())) { if ((curTerms.hasPayloads() || curTerms.hasOffsets() || curTerms.hasPositions()) == false) {
return; return;
} }

View file

@ -152,13 +152,13 @@ public class CoordinationMetadata implements Writeable, ToXContentFragment {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof CoordinationMetadata)) return false; if ((o instanceof CoordinationMetadata) == false) return false;
CoordinationMetadata that = (CoordinationMetadata) o; CoordinationMetadata that = (CoordinationMetadata) o;
if (term != that.term) return false; if (term != that.term) return false;
if (!lastCommittedConfiguration.equals(that.lastCommittedConfiguration)) return false; if (lastCommittedConfiguration.equals(that.lastCommittedConfiguration) == false) return false;
if (!lastAcceptedConfiguration.equals(that.lastAcceptedConfiguration)) return false; if (lastAcceptedConfiguration.equals(that.lastAcceptedConfiguration) == false) return false;
return votingConfigExclusions.equals(that.votingConfigExclusions); return votingConfigExclusions.equals(that.votingConfigExclusions);
} }

View file

@ -1016,7 +1016,7 @@ public class RoutingNodes implements Iterable<RoutingNode> {
* this method does nothing. * this method does nothing.
*/ */
public static boolean assertShardStats(RoutingNodes routingNodes) { public static boolean assertShardStats(RoutingNodes routingNodes) {
if (!Assertions.ENABLED) { if (Assertions.ENABLED == false) {
return true; return true;
} }
int unassignedPrimaryCount = 0; int unassignedPrimaryCount = 0;

View file

@ -407,7 +407,7 @@ public class AllocationService {
private void logClusterHealthStateChange(ClusterStateHealth previousStateHealth, ClusterStateHealth newStateHealth, String reason) { private void logClusterHealthStateChange(ClusterStateHealth previousStateHealth, ClusterStateHealth newStateHealth, String reason) {
ClusterHealthStatus previousHealth = previousStateHealth.getStatus(); ClusterHealthStatus previousHealth = previousStateHealth.getStatus();
ClusterHealthStatus currentHealth = newStateHealth.getStatus(); ClusterHealthStatus currentHealth = newStateHealth.getStatus();
if (!previousHealth.equals(currentHealth)) { if (previousHealth.equals(currentHealth) == false) {
logger.info("Cluster health status changed from [{}] to [{}] (reason: [{}]).", previousHealth, currentHealth, reason); logger.info("Cluster health status changed from [{}] to [{}] (reason: [{}]).", previousHealth, currentHealth, reason);
} }
} }

View file

@ -149,7 +149,7 @@ public class ChildMemoryCircuitBreaker implements CircuitBreaker {
} }
// Attempt to set the new used value, but make sure it hasn't changed // Attempt to set the new used value, but make sure it hasn't changed
// underneath us, if it has, keep trying until we are able to set it // underneath us, if it has, keep trying until we are able to set it
} while (!this.used.compareAndSet(currentUsed, newUsed)); } while (this.used.compareAndSet(currentUsed, newUsed) == false);
return newUsed; return newUsed;
} }

View file

@ -112,7 +112,7 @@ public class Loggers {
} }
public static void setLevel(Logger logger, Level level) { public static void setLevel(Logger logger, Level level) {
if (!LogManager.ROOT_LOGGER_NAME.equals(logger.getName())) { if (LogManager.ROOT_LOGGER_NAME.equals(logger.getName()) == false) {
Configurator.setLevel(logger.getName(), level); Configurator.setLevel(logger.getName(), level);
} else { } else {
final LoggerContext ctx = LoggerContext.getContext(false); final LoggerContext ctx = LoggerContext.getContext(false);
@ -136,7 +136,7 @@ public class Loggers {
final Configuration config = ctx.getConfiguration(); final Configuration config = ctx.getConfiguration();
config.addAppender(appender); config.addAppender(appender);
LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
if (!logger.getName().equals(loggerConfig.getName())) { if (logger.getName().equals(loggerConfig.getName()) == false) {
loggerConfig = new LoggerConfig(logger.getName(), logger.getLevel(), true); loggerConfig = new LoggerConfig(logger.getName(), logger.getLevel(), true);
config.addLogger(logger.getName(), loggerConfig); config.addLogger(logger.getName(), loggerConfig);
} }
@ -148,7 +148,7 @@ public class Loggers {
final LoggerContext ctx = (LoggerContext) LogManager.getContext(false); final LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
final Configuration config = ctx.getConfiguration(); final Configuration config = ctx.getConfiguration();
LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName()); LoggerConfig loggerConfig = config.getLoggerConfig(logger.getName());
if (!logger.getName().equals(loggerConfig.getName())) { if (logger.getName().equals(loggerConfig.getName()) == false) {
loggerConfig = new LoggerConfig(logger.getName(), logger.getLevel(), true); loggerConfig = new LoggerConfig(logger.getName(), logger.getLevel(), true);
config.addLogger(logger.getName(), loggerConfig); config.addLogger(logger.getName(), loggerConfig);
} }

View file

@ -50,7 +50,7 @@ public class HttpPipeliningAggregator<Listener> {
if (outboundHoldingQueue.size() < maxEventsHeld) { if (outboundHoldingQueue.size() < maxEventsHeld) {
ArrayList<Tuple<HttpPipelinedResponse, Listener>> readyResponses = new ArrayList<>(); ArrayList<Tuple<HttpPipelinedResponse, Listener>> readyResponses = new ArrayList<>();
outboundHoldingQueue.add(new Tuple<>(response, listener)); outboundHoldingQueue.add(new Tuple<>(response, listener));
while (!outboundHoldingQueue.isEmpty()) { while (outboundHoldingQueue.isEmpty() == false) {
/* /*
* Since the response with the lowest sequence number is the top of the priority queue, we know if its sequence * Since the response with the lowest sequence number is the top of the priority queue, we know if its sequence
* number does not match the current write sequence number then we have not processed all preceding responses yet. * number does not match the current write sequence number then we have not processed all preceding responses yet.

View file

@ -546,7 +546,7 @@ public final class AnalysisRegistry implements Closeable {
analyzer.normalize("", ""); // check for deprecations analyzer.normalize("", ""); // check for deprecations
} }
if (!analyzers.containsKey(DEFAULT_ANALYZER_NAME)) { if (analyzers.containsKey(DEFAULT_ANALYZER_NAME) == false) {
analyzers.put(DEFAULT_ANALYZER_NAME, analyzers.put(DEFAULT_ANALYZER_NAME,
produceAnalyzer(DEFAULT_ANALYZER_NAME, produceAnalyzer(DEFAULT_ANALYZER_NAME,
new StandardAnalyzerProvider(indexSettings, null, DEFAULT_ANALYZER_NAME, Settings.Builder.EMPTY_SETTINGS), new StandardAnalyzerProvider(indexSettings, null, DEFAULT_ANALYZER_NAME, Settings.Builder.EMPTY_SETTINGS),

View file

@ -163,7 +163,7 @@ public class NamedAnalyzer extends DelegatingAnalyzerWrapper {
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof NamedAnalyzer)) return false; if ((o instanceof NamedAnalyzer) == false) return false;
NamedAnalyzer that = (NamedAnalyzer) o; NamedAnalyzer that = (NamedAnalyzer) o;
return Objects.equals(name, that.name); return Objects.equals(name, that.name);
} }

View file

@ -48,7 +48,7 @@ final class DeleteVersionValue extends VersionValue {
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false; if (super.equals(o) == false) return false;
DeleteVersionValue that = (DeleteVersionValue) o; DeleteVersionValue that = (DeleteVersionValue) o;

View file

@ -44,7 +44,7 @@ final class IndexVersionValue extends VersionValue {
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false; if (super.equals(o) == false) return false;
IndexVersionValue that = (IndexVersionValue) o; IndexVersionValue that = (IndexVersionValue) o;
return Objects.equals(translogLocation, that.translogLocation); return Objects.equals(translogLocation, that.translogLocation);
} }

View file

@ -300,7 +300,7 @@ public class GetResult implements Writeable, Iterable<DocumentField>, ToXContent
XContentHelper.writeRawField(SourceFieldMapper.NAME, source, builder, params); XContentHelper.writeRawField(SourceFieldMapper.NAME, source, builder, params);
} }
if (!documentFields.isEmpty()) { if (documentFields.isEmpty() == false) {
builder.startObject(FIELDS); builder.startObject(FIELDS);
for (DocumentField field : documentFields.values()) { for (DocumentField field : documentFields.values()) {
field.toXContent(builder, params); field.toXContent(builder, params);

View file

@ -128,7 +128,7 @@ public final class ShardGetService extends AbstractIndexShardComponent {
*/ */
public GetResult get(Engine.GetResult engineGetResult, String id, String type, public GetResult get(Engine.GetResult engineGetResult, String id, String type,
String[] fields, FetchSourceContext fetchSourceContext) { String[] fields, FetchSourceContext fetchSourceContext) {
if (!engineGetResult.exists()) { if (engineGetResult.exists() == false) {
return new GetResult(shardId.getIndexName(), type, id, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, -1, false, null, null, null); return new GetResult(shardId.getIndexName(), type, id, UNASSIGNED_SEQ_NO, UNASSIGNED_PRIMARY_TERM, -1, false, null, null, null);
} }
@ -280,7 +280,7 @@ public final class ShardGetService extends AbstractIndexShardComponent {
} }
// put stored fields into result objects // put stored fields into result objects
if (!fieldVisitor.fields().isEmpty()) { if (fieldVisitor.fields().isEmpty() == false) {
fieldVisitor.postProcess(mapperService::fieldType, fieldVisitor.postProcess(mapperService::fieldType,
mapperService.documentMapper() == null ? null : mapperService.documentMapper().type()); mapperService.documentMapper() == null ? null : mapperService.documentMapper().type());
documentFields = new HashMap<>(); documentFields = new HashMap<>();

View file

@ -422,7 +422,7 @@ public class CompletionFieldMapper extends FieldMapper {
while ((token = parser.nextToken()) != Token.END_OBJECT) { while ((token = parser.nextToken()) != Token.END_OBJECT) {
if (token == Token.FIELD_NAME) { if (token == Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
if (!ALLOWED_CONTENT_FIELD_NAMES.contains(currentFieldName)) { if (ALLOWED_CONTENT_FIELD_NAMES.contains(currentFieldName) == false) {
throw new IllegalArgumentException("unknown field name [" + currentFieldName throw new IllegalArgumentException("unknown field name [" + currentFieldName
+ "], must be one of " + ALLOWED_CONTENT_FIELD_NAMES); + "], must be one of " + ALLOWED_CONTENT_FIELD_NAMES);
} }

View file

@ -140,7 +140,7 @@ public class DocumentMapperParser {
} }
public static void checkNoRemainingFields(Map<?, ?> fieldNodeMap, String message) { public static void checkNoRemainingFields(Map<?, ?> fieldNodeMap, String message) {
if (!fieldNodeMap.isEmpty()) { if (fieldNodeMap.isEmpty() == false) {
throw new MapperParsingException(message + getRemainingFields(fieldNodeMap)); throw new MapperParsingException(message + getRemainingFields(fieldNodeMap));
} }
} }

View file

@ -457,7 +457,7 @@ final class DocumentParser {
if (nested.isIncludeInRoot()) { if (nested.isIncludeInRoot()) {
ParseContext.Document rootDoc = context.rootDoc(); ParseContext.Document rootDoc = context.rootDoc();
// don't add it twice, if its included in parent, and we are handling the master doc... // don't add it twice, if its included in parent, and we are handling the master doc...
if (!nested.isIncludeInParent() || parentDoc != rootDoc) { if (nested.isIncludeInParent() == false || parentDoc != rootDoc) {
addFields(nestedDoc, rootDoc); addFields(nestedDoc, rootDoc);
} }
} }
@ -664,7 +664,7 @@ final class DocumentParser {
/** Creates instances of the fields that the current field should be copied to */ /** Creates instances of the fields that the current field should be copied to */
private static void parseCopyFields(ParseContext context, List<String> copyToFields) throws IOException { private static void parseCopyFields(ParseContext context, List<String> copyToFields) throws IOException {
if (!context.isWithinCopyTo() && copyToFields.isEmpty() == false) { if (context.isWithinCopyTo() == false && copyToFields.isEmpty() == false) {
context = context.createCopyToContext(); context = context.createCopyToContext();
for (String field : copyToFields) { for (String field : copyToFields) {
// In case of a hierarchy of nested documents, we need to figure out // In case of a hierarchy of nested documents, we need to figure out

View file

@ -68,7 +68,7 @@ public final class FieldAliasMapper extends Mapper {
@Override @Override
public Mapper merge(Mapper mergeWith) { public Mapper merge(Mapper mergeWith) {
if (!(mergeWith instanceof FieldAliasMapper)) { if ((mergeWith instanceof FieldAliasMapper) == false) {
throw new IllegalArgumentException("Cannot merge a field alias mapping [" throw new IllegalArgumentException("Cannot merge a field alias mapping ["
+ name() + "] with a mapping that is not for a field alias."); + name() + "] with a mapping that is not for a field alias.");
} }
@ -105,7 +105,7 @@ public final class FieldAliasMapper extends Mapper {
String aliasScope = mappers.getNestedScope(name); String aliasScope = mappers.getNestedScope(name);
String pathScope = mappers.getNestedScope(path); String pathScope = mappers.getNestedScope(path);
if (!Objects.equals(aliasScope, pathScope)) { if (Objects.equals(aliasScope, pathScope) == false) {
StringBuilder message = new StringBuilder("Invalid [path] value [" + path + "] for field alias [" + StringBuilder message = new StringBuilder("Invalid [path] value [" + path + "] for field alias [" +
name + "]: an alias must have the same nested scope as its target. "); name + "]: an alias must have the same nested scope as its target. ");
message.append(aliasScope == null message.append(aliasScope == null

View file

@ -407,7 +407,7 @@ public abstract class FieldMapper extends Mapper implements Cloneable {
@Override @Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (!mappers.isEmpty()) { if (mappers.isEmpty() == false) {
// sort the mappers so we get consistent serialization format // sort the mappers so we get consistent serialization format
List<FieldMapper> sortedMappers = new ArrayList<>(mappers.values()); List<FieldMapper> sortedMappers = new ArrayList<>(mappers.values());
sortedMappers.sort(Comparator.comparing(FieldMapper::name)); sortedMappers.sort(Comparator.comparing(FieldMapper::name));
@ -439,7 +439,7 @@ public abstract class FieldMapper extends Mapper implements Cloneable {
} }
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
if (!copyToFields.isEmpty()) { if (copyToFields.isEmpty() == false) {
builder.startArray("copy_to"); builder.startArray("copy_to");
for (String field : copyToFields) { for (String field : copyToFields) {
builder.value(field); builder.value(field);

View file

@ -226,7 +226,7 @@ public class NumberFieldMapper extends FieldMapper {
} }
private void validateParsed(float value) { private void validateParsed(float value) {
if (!Float.isFinite(HalfFloatPoint.sortableShortToHalfFloat(HalfFloatPoint.halfFloatToSortableShort(value)))) { if (Float.isFinite(HalfFloatPoint.sortableShortToHalfFloat(HalfFloatPoint.halfFloatToSortableShort(value))) == false) {
throw new IllegalArgumentException("[half_float] supports only finite values, but got [" + value + "]"); throw new IllegalArgumentException("[half_float] supports only finite values, but got [" + value + "]");
} }
} }
@ -321,7 +321,7 @@ public class NumberFieldMapper extends FieldMapper {
} }
private void validateParsed(float value) { private void validateParsed(float value) {
if (!Float.isFinite(value)) { if (Float.isFinite(value) == false) {
throw new IllegalArgumentException("[float] supports only finite values, but got [" + value + "]"); throw new IllegalArgumentException("[float] supports only finite values, but got [" + value + "]");
} }
} }
@ -392,7 +392,7 @@ public class NumberFieldMapper extends FieldMapper {
} }
private void validateParsed(double value) { private void validateParsed(double value) {
if (!Double.isFinite(value)) { if (Double.isFinite(value) == false) {
throw new IllegalArgumentException("[double] supports only finite values, but got [" + value + "]"); throw new IllegalArgumentException("[double] supports only finite values, but got [" + value + "]");
} }
} }
@ -405,7 +405,7 @@ public class NumberFieldMapper extends FieldMapper {
if (doubleValue < Byte.MIN_VALUE || doubleValue > Byte.MAX_VALUE) { if (doubleValue < Byte.MIN_VALUE || doubleValue > Byte.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for a byte"); throw new IllegalArgumentException("Value [" + value + "] is out of range for a byte");
} }
if (!coerce && doubleValue % 1 != 0) { if (coerce == false && doubleValue % 1 != 0) {
throw new IllegalArgumentException("Value [" + value + "] has a decimal part"); throw new IllegalArgumentException("Value [" + value + "] has a decimal part");
} }
@ -466,7 +466,7 @@ public class NumberFieldMapper extends FieldMapper {
if (doubleValue < Short.MIN_VALUE || doubleValue > Short.MAX_VALUE) { if (doubleValue < Short.MIN_VALUE || doubleValue > Short.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for a short"); throw new IllegalArgumentException("Value [" + value + "] is out of range for a short");
} }
if (!coerce && doubleValue % 1 != 0) { if (coerce == false && doubleValue % 1 != 0) {
throw new IllegalArgumentException("Value [" + value + "] has a decimal part"); throw new IllegalArgumentException("Value [" + value + "] has a decimal part");
} }
@ -523,7 +523,7 @@ public class NumberFieldMapper extends FieldMapper {
if (doubleValue < Integer.MIN_VALUE || doubleValue > Integer.MAX_VALUE) { if (doubleValue < Integer.MIN_VALUE || doubleValue > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for an integer"); throw new IllegalArgumentException("Value [" + value + "] is out of range for an integer");
} }
if (!coerce && doubleValue % 1 != 0) { if (coerce == false && doubleValue % 1 != 0) {
throw new IllegalArgumentException("Value [" + value + "] has a decimal part"); throw new IllegalArgumentException("Value [" + value + "] has a decimal part");
} }
@ -559,7 +559,7 @@ public class NumberFieldMapper extends FieldMapper {
int upTo = 0; int upTo = 0;
for (Object value : values) { for (Object value : values) {
if (!hasDecimalPart(value)) { if (hasDecimalPart(value) == false) {
v[upTo++] = parse(value, true); v[upTo++] = parse(value, true);
} }
} }
@ -664,7 +664,7 @@ public class NumberFieldMapper extends FieldMapper {
int upTo = 0; int upTo = 0;
for (Object value : values) { for (Object value : values) {
if (!hasDecimalPart(value)) { if (hasDecimalPart(value) == false) {
v[upTo++] = parse(value, true); v[upTo++] = parse(value, true);
} }
} }
@ -816,7 +816,7 @@ public class NumberFieldMapper extends FieldMapper {
if (doubleValue < Long.MIN_VALUE || doubleValue > Long.MAX_VALUE) { if (doubleValue < Long.MIN_VALUE || doubleValue > Long.MAX_VALUE) {
throw new IllegalArgumentException("Value [" + value + "] is out of range for a long"); throw new IllegalArgumentException("Value [" + value + "] is out of range for a long");
} }
if (!coerce && doubleValue % 1 != 0) { if (coerce == false && doubleValue % 1 != 0) {
throw new IllegalArgumentException("Value [" + value + "] has a decimal part"); throw new IllegalArgumentException("Value [" + value + "] has a decimal part");
} }

View file

@ -100,7 +100,7 @@ public class ObjectMapper extends Mapper implements Cloneable {
public void merge(Nested mergeWith, MergeReason reason) { public void merge(Nested mergeWith, MergeReason reason) {
if (isNested()) { if (isNested()) {
if (!mergeWith.isNested()) { if (mergeWith.isNested() == false) {
throw new IllegalArgumentException("cannot change object mapping from nested to non-nested"); throw new IllegalArgumentException("cannot change object mapping from nested to non-nested");
} }
} else { } else {
@ -247,7 +247,7 @@ public class ObjectMapper extends Mapper implements Cloneable {
} else if (fieldName.equals("properties")) { } else if (fieldName.equals("properties")) {
if (fieldNode instanceof Collection && ((Collection) fieldNode).isEmpty()) { if (fieldNode instanceof Collection && ((Collection) fieldNode).isEmpty()) {
// nothing to do here, empty (to support "properties: []" case) // nothing to do here, empty (to support "properties: []" case)
} else if (!(fieldNode instanceof Map)) { } else if ((fieldNode instanceof Map) == false) {
throw new ElasticsearchParseException("properties must be a map type"); throw new ElasticsearchParseException("properties must be a map type");
} else { } else {
parseProperties(builder, (Map<String, Object>) fieldNode, parserContext); parseProperties(builder, (Map<String, Object>) fieldNode, parserContext);
@ -478,7 +478,7 @@ public class ObjectMapper extends Mapper implements Cloneable {
} }
public ObjectMapper merge(Mapper mergeWith, MergeReason reason) { public ObjectMapper merge(Mapper mergeWith, MergeReason reason) {
if (!(mergeWith instanceof ObjectMapper)) { if ((mergeWith instanceof ObjectMapper) == false) {
throw new IllegalArgumentException("can't merge a non object mapping [" + mergeWith.name() + "] with an object mapping"); throw new IllegalArgumentException("can't merge a non object mapping [" + mergeWith.name() + "] with an object mapping");
} }
ObjectMapper mergeWithObject = (ObjectMapper) mergeWith; ObjectMapper mergeWithObject = (ObjectMapper) mergeWith;
@ -569,7 +569,7 @@ public class ObjectMapper extends Mapper implements Cloneable {
int count = 0; int count = 0;
for (Mapper mapper : sortedMappers) { for (Mapper mapper : sortedMappers) {
if (!(mapper instanceof MetadataFieldMapper)) { if ((mapper instanceof MetadataFieldMapper) == false) {
if (count++ == 0) { if (count++ == 0) {
builder.startObject("properties"); builder.startObject("properties");
} }

View file

@ -678,11 +678,11 @@ public abstract class ParseContext {
* @return null if no external value has been set or the value * @return null if no external value has been set or the value
*/ */
public final <T> T parseExternalValue(Class<T> clazz) { public final <T> T parseExternalValue(Class<T> clazz) {
if (!externalValueSet() || externalValue() == null) { if (externalValueSet() == false || externalValue() == null) {
return null; return null;
} }
if (!clazz.isInstance(externalValue())) { if (clazz.isInstance(externalValue()) == false) {
throw new IllegalArgumentException("illegal external value class [" throw new IllegalArgumentException("illegal external value class ["
+ externalValue().getClass().getName() + "]. Should be " + clazz.getName()); + externalValue().getClass().getName() + "]. Should be " + clazz.getName());
} }

View file

@ -206,7 +206,7 @@ public class RangeFieldMapper extends FieldMapper {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
protected Object parseSourceValue(Object value) { protected Object parseSourceValue(Object value) {
RangeType rangeType = rangeType(); RangeType rangeType = rangeType();
if (!(value instanceof Map)) { if ((value instanceof Map) == false) {
assert rangeType == RangeType.IP; assert rangeType == RangeType.IP;
Tuple<InetAddress, Integer> ipRange = InetAddresses.parseCidr(value.toString()); Tuple<InetAddress, Integer> ipRange = InetAddresses.parseCidr(value.toString());
return InetAddresses.toCidrString(ipRange.v1(), ipRange.v2()); return InetAddresses.toCidrString(ipRange.v1(), ipRange.v2());

View file

@ -123,7 +123,7 @@ public class TypeParsers {
throw new MapperParsingException("Field name [" + multiFieldName + "] which is a multi field of [" + name + "] cannot" + throw new MapperParsingException("Field name [" + multiFieldName + "] which is a multi field of [" + name + "] cannot" +
" contain '.'"); " contain '.'");
} }
if (!(multiFieldEntry.getValue() instanceof Map)) { if ((multiFieldEntry.getValue() instanceof Map) == false) {
throw new MapperParsingException("illegal field [" + multiFieldName + "], only fields can be specified inside fields"); throw new MapperParsingException("illegal field [" + multiFieldName + "], only fields can be specified inside fields");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View file

@ -409,7 +409,7 @@ public abstract class AbstractGeometryQueryBuilder<QB extends AbstractGeometryQu
@Override @Override
public void onResponse(GetResponse response) { public void onResponse(GetResponse response) {
try { try {
if (!response.isExists()) { if (response.isExists() == false) {
throw new IllegalArgumentException("Shape with ID [" + getRequest.id() + "] in type [" + getRequest.type() throw new IllegalArgumentException("Shape with ID [" + getRequest.id() + "] in type [" + getRequest.type()
+ "] not found"); + "] not found");
} }

View file

@ -174,10 +174,10 @@ public class BoostingQueryBuilder extends AbstractQueryBuilder<BoostingQueryBuil
} }
} }
if (!positiveQueryFound) { if (positiveQueryFound == false) {
throw new ParsingException(parser.getTokenLocation(), "[boosting] query requires 'positive' query to be set'"); throw new ParsingException(parser.getTokenLocation(), "[boosting] query requires 'positive' query to be set'");
} }
if (!negativeQueryFound) { if (negativeQueryFound == false) {
throw new ParsingException(parser.getTokenLocation(), "[boosting] query requires 'negative' query to be set'"); throw new ParsingException(parser.getTokenLocation(), "[boosting] query requires 'negative' query to be set'");
} }
if (negativeBoost < 0) { if (negativeBoost < 0) {

View file

@ -117,7 +117,7 @@ public class ConstantScoreQueryBuilder extends AbstractQueryBuilder<ConstantScor
throw new ParsingException(parser.getTokenLocation(), "unexpected token [" + token + "]"); throw new ParsingException(parser.getTokenLocation(), "unexpected token [" + token + "]");
} }
} }
if (!queryFound) { if (queryFound == false) {
throw new ParsingException(parser.getTokenLocation(), "[constant_score] requires a 'filter' element"); throw new ParsingException(parser.getTokenLocation(), "[constant_score] requires a 'filter' element");
} }

View file

@ -165,7 +165,7 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
} }
} }
if (!queriesFound) { if (queriesFound == false) {
throw new ParsingException(parser.getTokenLocation(), "[dis_max] requires 'queries' field with at least one clause"); throw new ParsingException(parser.getTokenLocation(), "[dis_max] requires 'queries' field with at least one clause");
} }

View file

@ -311,7 +311,7 @@ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBounding
throw new QueryShardException(context, "failed to find geo field [" + fieldName + "]"); throw new QueryShardException(context, "failed to find geo field [" + fieldName + "]");
} }
} }
if (!(fieldType instanceof GeoShapeQueryable)) { if ((fieldType instanceof GeoShapeQueryable) == false) {
throw new QueryShardException(context, throw new QueryShardException(context,
"Field [" + fieldName + "] is of unsupported type [" + fieldType.typeName() + "] for [" + NAME + "] query"); "Field [" + fieldName + "] is of unsupported type [" + fieldType.typeName() + "] for [" + NAME + "] query");
} }

View file

@ -236,7 +236,7 @@ public class GeoDistanceQueryBuilder extends AbstractQueryBuilder<GeoDistanceQue
} }
} }
if (!(fieldType instanceof GeoShapeQueryable)) { if ((fieldType instanceof GeoShapeQueryable) == false) {
throw new QueryShardException(context, throw new QueryShardException(context,
"Field [" + fieldName + "] is of unsupported type [" + fieldType.typeName() + "] for [" + NAME + "] query"); "Field [" + fieldName + "] is of unsupported type [" + fieldType.typeName() + "] for [" + NAME + "] query");
} }

View file

@ -82,7 +82,7 @@ public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQuery
} }
this.fieldName = fieldName; this.fieldName = fieldName;
this.shell = new ArrayList<>(points); this.shell = new ArrayList<>(points);
if (!shell.get(shell.size() - 1).equals(shell.get(0))) { if (shell.get(shell.size() - 1).equals(shell.get(0)) == false) {
shell.add(shell.get(0)); shell.add(shell.get(0));
} }
} }
@ -161,7 +161,7 @@ public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQuery
throw new QueryShardException(context, "failed to find geo_point field [" + fieldName + "]"); throw new QueryShardException(context, "failed to find geo_point field [" + fieldName + "]");
} }
} }
if (!(fieldType instanceof GeoPointFieldType)) { if ((fieldType instanceof GeoPointFieldType) == false) {
throw new QueryShardException(context, "field [" + fieldName + "] is not a geo_point field"); throw new QueryShardException(context, "field [" + fieldName + "] is not a geo_point field");
} }
@ -173,13 +173,13 @@ public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQuery
// validation was not available prior to 2.x, so to support bwc // validation was not available prior to 2.x, so to support bwc
// percolation queries we only ignore_malformed on 2.x created indexes // percolation queries we only ignore_malformed on 2.x created indexes
if (!GeoValidationMethod.isIgnoreMalformed(validationMethod)) { if (GeoValidationMethod.isIgnoreMalformed(validationMethod) == false) {
for (GeoPoint point : shell) { for (GeoPoint point : shell) {
if (!GeoUtils.isValidLatitude(point.lat())) { if (GeoUtils.isValidLatitude(point.lat()) == false) {
throw new QueryShardException(context, "illegal latitude value [{}] for [{}]", point.lat(), throw new QueryShardException(context, "illegal latitude value [{}] for [{}]", point.lat(),
GeoPolygonQueryBuilder.NAME); GeoPolygonQueryBuilder.NAME);
} }
if (!GeoUtils.isValidLongitude(point.lon())) { if (GeoUtils.isValidLongitude(point.lon()) == false) {
throw new QueryShardException(context, "illegal longitude value [{}] for [{}]", point.lon(), throw new QueryShardException(context, "illegal longitude value [{}] for [{}]", point.lon(),
GeoPolygonQueryBuilder.NAME); GeoPolygonQueryBuilder.NAME);
} }

View file

@ -510,7 +510,7 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (!(o instanceof Item)) return false; if ((o instanceof Item) == false) return false;
Item other = (Item) o; Item other = (Item) o;
return Objects.equals(index, other.index) return Objects.equals(index, other.index)
&& Objects.equals(type, other.type) && Objects.equals(type, other.type)
@ -1124,7 +1124,7 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
boolQuery.add(mltQuery, BooleanClause.Occur.SHOULD); boolQuery.add(mltQuery, BooleanClause.Occur.SHOULD);
// exclude the items from the search // exclude the items from the search
if (!include) { if (include == false) {
handleExclude(boolQuery, likeItems, context); handleExclude(boolQuery, likeItems, context);
} }
return boolQuery.build(); return boolQuery.build();
@ -1166,7 +1166,7 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
continue; continue;
} }
TermVectorsResponse getResponse = response.getResponse(); TermVectorsResponse getResponse = response.getResponse();
if (!getResponse.isExists()) { if (getResponse.isExists() == false) {
continue; continue;
} }
likeFields.add(getResponse.getFields()); likeFields.add(getResponse.getFields());
@ -1195,7 +1195,7 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
} }
ids.add(item.id()); ids.add(item.id());
} }
if (!ids.isEmpty()) { if (ids.isEmpty() == false) {
Query query = idField.termsQuery(ids, context); Query query = idField.termsQuery(ids, context);
boolQuery.add(query, BooleanClause.Occur.MUST_NOT); boolQuery.add(query, BooleanClause.Occur.MUST_NOT);
} }

View file

@ -281,7 +281,7 @@ public class NestedQueryBuilder extends AbstractQueryBuilder<NestedQueryBuilder>
throw new IllegalStateException("[" + NAME + "] failed to find nested object under path [" + path + "]"); throw new IllegalStateException("[" + NAME + "] failed to find nested object under path [" + path + "]");
} }
} }
if (!nestedObjectMapper.nested().isNested()) { if (nestedObjectMapper.nested().isNested() == false) {
throw new IllegalStateException("[" + NAME + "] nested object under path [" + path + "] is not of nested type"); throw new IllegalStateException("[" + NAME + "] nested object under path [" + path + "] is not of nested type");
} }
final BitSetProducer parentFilter; final BitSetProducer parentFilter;

View file

@ -98,7 +98,7 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
String relationString = in.readOptionalString(); String relationString = in.readOptionalString();
if (relationString != null) { if (relationString != null) {
relation = ShapeRelation.getRelationByName(relationString); relation = ShapeRelation.getRelationByName(relationString);
if (relation != null && !isRelationAllowed(relation)) { if (relation != null && isRelationAllowed(relation) == false) {
throw new IllegalArgumentException( throw new IllegalArgumentException(
"[range] query does not support relation [" + relationString + "]"); "[range] query does not support relation [" + relationString + "]");
} }
@ -310,7 +310,7 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
if (this.relation == null) { if (this.relation == null) {
throw new IllegalArgumentException(relation + " is not a valid relation"); throw new IllegalArgumentException(relation + " is not a valid relation");
} }
if (!isRelationAllowed(this.relation)) { if (isRelationAllowed(this.relation) == false) {
throw new IllegalArgumentException("[range] query does not support relation [" + relation + "]"); throw new IllegalArgumentException("[range] query does not support relation [" + relation + "]");
} }
return this; return this;

View file

@ -53,7 +53,7 @@ public enum SimpleQueryStringFlag {
} }
static int resolveFlags(String flags) { static int resolveFlags(String flags) {
if (!Strings.hasLength(flags)) { if (Strings.hasLength(flags) == false) {
return ALL.value(); return ALL.value();
} }
int magic = NONE.value(); int magic = NONE.value();

View file

@ -213,7 +213,7 @@ public class SpanNearQueryBuilder extends AbstractQueryBuilder<SpanNearQueryBuil
SpanQueryBuilder queryBuilder = clauses.get(0); SpanQueryBuilder queryBuilder = clauses.get(0);
boolean isGap = queryBuilder instanceof SpanGapQueryBuilder; boolean isGap = queryBuilder instanceof SpanGapQueryBuilder;
Query query = null; Query query = null;
if (!isGap) { if (isGap == false) {
query = queryBuilder.toQuery(context); query = queryBuilder.toQuery(context);
assert query instanceof SpanQuery; assert query instanceof SpanQuery;
} }
@ -249,7 +249,7 @@ public class SpanNearQueryBuilder extends AbstractQueryBuilder<SpanNearQueryBuil
String fieldName = ((SpanGapQueryBuilder) queryBuilder).fieldName(); String fieldName = ((SpanGapQueryBuilder) queryBuilder).fieldName();
String spanGapFieldName = queryFieldName(context, fieldName); String spanGapFieldName = queryFieldName(context, fieldName);
if (!spanNearFieldName.equals(spanGapFieldName)) { if (spanNearFieldName.equals(spanGapFieldName) == false) {
throw new IllegalArgumentException("[span_near] clauses must have same field"); throw new IllegalArgumentException("[span_near] clauses must have same field");
} }
int gap = ((SpanGapQueryBuilder) queryBuilder).width(); int gap = ((SpanGapQueryBuilder) queryBuilder).width();

View file

@ -122,7 +122,7 @@ public class WrapperQueryBuilder extends AbstractQueryBuilder<WrapperQueryBuilde
throw new ParsingException(parser.getTokenLocation(), "[wrapper] query malformed"); throw new ParsingException(parser.getTokenLocation(), "[wrapper] query malformed");
} }
String fieldName = parser.currentName(); String fieldName = parser.currentName();
if (! QUERY_FIELD.match(fieldName, parser.getDeprecationHandler())) { if (QUERY_FIELD.match(fieldName, parser.getDeprecationHandler()) == false) {
throw new ParsingException(parser.getTokenLocation(), "[wrapper] query malformed, expected `query` but was " + fieldName); throw new ParsingException(parser.getTokenLocation(), "[wrapper] query malformed, expected `query` but was " + fieldName);
} }
parser.nextToken(); parser.nextToken();

View file

@ -141,7 +141,7 @@ public class BulkByScrollTask extends CancellableTask {
* a leader task. * a leader task.
*/ */
public LeaderBulkByScrollTaskState getLeaderState() { public LeaderBulkByScrollTaskState getLeaderState() {
if (!isLeader()) { if (isLeader() == false) {
throw new IllegalStateException("This task is not set to be a leader for other slice subtasks"); throw new IllegalStateException("This task is not set to be a leader for other slice subtasks");
} }
return leaderState; return leaderState;
@ -178,7 +178,7 @@ public class BulkByScrollTask extends CancellableTask {
* worker task. * worker task.
*/ */
public WorkerBulkByScrollTaskState getWorkerState() { public WorkerBulkByScrollTaskState getWorkerState() {
if (!isWorker()) { if (isWorker() == false) {
throw new IllegalStateException("This task is not set to be a worker"); throw new IllegalStateException("This task is not set to be a worker");
} }
return workerState; return workerState;

View file

@ -252,7 +252,7 @@ public class RemoteInfo implements Writeable, ToXContentObject {
if (query == null) { if (query == null) {
return BytesReference.bytes(matchAllQuery().toXContent(builder, ToXContent.EMPTY_PARAMS)); return BytesReference.bytes(matchAllQuery().toXContent(builder, ToXContent.EMPTY_PARAMS));
} }
if (!(query instanceof Map)) { if ((query instanceof Map) == false) {
throw new IllegalArgumentException("Expected [query] to be an object but was [" + query + "]"); throw new IllegalArgumentException("Expected [query] to be an object but was [" + query + "]");
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")

View file

@ -609,7 +609,7 @@ public class MatchQuery {
OffsetAttribute offsetAtt = stream.addAttribute(OffsetAttribute.class); OffsetAttribute offsetAtt = stream.addAttribute(OffsetAttribute.class);
stream.reset(); stream.reset();
if (!stream.incrementToken()) { if (stream.incrementToken() == false) {
throw new AssertionError(); throw new AssertionError();
} }
final Term term = new Term(field, termAtt.getBytesRef()); final Term term = new Term(field, termAtt.getBytesRef());

View file

@ -128,7 +128,7 @@ public class MultiMatchQuery extends MatchQuery {
MappedFieldType fieldType = context.getFieldType(name); MappedFieldType fieldType = context.getFieldType(name);
if (fieldType != null) { if (fieldType != null) {
Analyzer actualAnalyzer = getAnalyzer(fieldType, type == MultiMatchQueryBuilder.Type.PHRASE); Analyzer actualAnalyzer = getAnalyzer(fieldType, type == MultiMatchQueryBuilder.Type.PHRASE);
if (!groups.containsKey(actualAnalyzer)) { if (groups.containsKey(actualAnalyzer) == false) {
groups.put(actualAnalyzer, new ArrayList<>()); groups.put(actualAnalyzer, new ArrayList<>());
} }
float boost = entry.getValue() == null ? 1.0f : entry.getValue(); float boost = entry.getValue() == null ? 1.0f : entry.getValue();

View file

@ -562,7 +562,9 @@ public class QueryStringQueryParser extends XQueryParser {
while (true) { while (true) {
try { try {
if (!source.incrementToken()) break; if (source.incrementToken() == false) {
break;
}
} catch (IOException e) { } catch (IOException e) {
break; break;
} }

View file

@ -478,7 +478,7 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl
currentRouting = this.shardRouting; currentRouting = this.shardRouting;
assert currentRouting != null; assert currentRouting != null;
if (!newRouting.shardId().equals(shardId())) { if (newRouting.shardId().equals(shardId()) == false) {
throw new IllegalArgumentException("Trying to set a routing entry with shardId " + throw new IllegalArgumentException("Trying to set a routing entry with shardId " +
newRouting.shardId() + " on a shard with shardId " + shardId()); newRouting.shardId() + " on a shard with shardId " + shardId());
} }
@ -2670,7 +2670,7 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl
private void doCheckIndex() throws IOException { private void doCheckIndex() throws IOException {
long timeNS = System.nanoTime(); long timeNS = System.nanoTime();
if (!Lucene.indexExists(store.directory())) { if (Lucene.indexExists(store.directory()) == false) {
return; return;
} }
BytesStreamOutput os = new BytesStreamOutput(); BytesStreamOutput os = new BytesStreamOutput();
@ -2699,7 +2699,7 @@ public class IndexShard extends AbstractIndexShardComponent implements IndicesCl
// full checkindex // full checkindex
final CheckIndex.Status status = store.checkIndex(out); final CheckIndex.Status status = store.checkIndex(out);
out.flush(); out.flush();
if (!status.clean) { if (status.clean == false) {
if (state == IndexShardState.CLOSED) { if (state == IndexShardState.CLOSED) {
// ignore if closed.... // ignore if closed....
return; return;

View file

@ -168,7 +168,7 @@ final class IndexShardOperationPermits implements Closeable {
queuedActions = Collections.emptyList(); queuedActions = Collections.emptyList();
} }
} }
if (!queuedActions.isEmpty()) { if (queuedActions.isEmpty() == false) {
/* /*
* Try acquiring permits on fresh thread (for two reasons): * Try acquiring permits on fresh thread (for two reasons):
* - blockOperations can be called on a recovery thread which can be expected to be interrupted when recovery is cancelled; * - blockOperations can be called on a recovery thread which can be expected to be interrupted when recovery is cancelled;

View file

@ -96,7 +96,7 @@ final class InternalIndexingStats implements IndexingOperationListener {
@Override @Override
public void postIndex(ShardId shardId, Engine.Index index, Exception ex) { public void postIndex(ShardId shardId, Engine.Index index, Exception ex) {
if (!index.origin().isRecovery()) { if (index.origin().isRecovery() == false) {
totalStats.indexCurrent.dec(); totalStats.indexCurrent.dec();
typeStats(index.type()).indexCurrent.dec(); typeStats(index.type()).indexCurrent.dec();
totalStats.indexFailed.inc(); totalStats.indexFailed.inc();
@ -106,7 +106,7 @@ final class InternalIndexingStats implements IndexingOperationListener {
@Override @Override
public Engine.Delete preDelete(ShardId shardId, Engine.Delete delete) { public Engine.Delete preDelete(ShardId shardId, Engine.Delete delete) {
if (!delete.origin().isRecovery()) { if (delete.origin().isRecovery() == false) {
totalStats.deleteCurrent.inc(); totalStats.deleteCurrent.inc();
typeStats(delete.type()).deleteCurrent.inc(); typeStats(delete.type()).deleteCurrent.inc();
} }
@ -118,7 +118,7 @@ final class InternalIndexingStats implements IndexingOperationListener {
public void postDelete(ShardId shardId, Engine.Delete delete, Engine.DeleteResult result) { public void postDelete(ShardId shardId, Engine.Delete delete, Engine.DeleteResult result) {
switch (result.getResultType()) { switch (result.getResultType()) {
case SUCCESS: case SUCCESS:
if (!delete.origin().isRecovery()) { if (delete.origin().isRecovery() == false) {
long took = result.getTook(); long took = result.getTook();
totalStats.deleteMetric.inc(took); totalStats.deleteMetric.inc(took);
totalStats.deleteCurrent.dec(); totalStats.deleteCurrent.dec();
@ -137,7 +137,7 @@ final class InternalIndexingStats implements IndexingOperationListener {
@Override @Override
public void postDelete(ShardId shardId, Engine.Delete delete, Exception ex) { public void postDelete(ShardId shardId, Engine.Delete delete, Exception ex) {
if (!delete.origin().isRecovery()) { if (delete.origin().isRecovery() == false) {
totalStats.deleteCurrent.dec(); totalStats.deleteCurrent.dec();
typeStats(delete.type()).deleteCurrent.dec(); typeStats(delete.type()).deleteCurrent.dec();
} }

View file

@ -265,7 +265,7 @@ public class PrimaryReplicaSyncer {
} }
final long trimmedAboveSeqNo = firstMessage.get() ? maxSeqNo : SequenceNumbers.UNASSIGNED_SEQ_NO; final long trimmedAboveSeqNo = firstMessage.get() ? maxSeqNo : SequenceNumbers.UNASSIGNED_SEQ_NO;
// have to send sync request even in case of there are no operations to sync - have to sync trimmedAboveSeqNo at least // have to send sync request even in case of there are no operations to sync - have to sync trimmedAboveSeqNo at least
if (!operations.isEmpty() || trimmedAboveSeqNo != SequenceNumbers.UNASSIGNED_SEQ_NO) { if (operations.isEmpty() == false || trimmedAboveSeqNo != SequenceNumbers.UNASSIGNED_SEQ_NO) {
task.setPhase("sending_ops"); task.setPhase("sending_ops");
ResyncReplicationRequest request = ResyncReplicationRequest request =
new ResyncReplicationRequest(shardId, trimmedAboveSeqNo, maxSeenAutoIdTimestamp, operations.toArray(EMPTY_ARRAY)); new ResyncReplicationRequest(shardId, trimmedAboveSeqNo, maxSeenAutoIdTimestamp, operations.toArray(EMPTY_ARRAY));

View file

@ -122,8 +122,8 @@ public class ReplicationGroup {
ReplicationGroup that = (ReplicationGroup) o; ReplicationGroup that = (ReplicationGroup) o;
if (!routingTable.equals(that.routingTable)) return false; if (routingTable.equals(that.routingTable) == false) return false;
if (!inSyncAllocationIds.equals(that.inSyncAllocationIds)) return false; if (inSyncAllocationIds.equals(that.inSyncAllocationIds) == false) return false;
return trackedAllocationIds.equals(that.trackedAllocationIds); return trackedAllocationIds.equals(that.trackedAllocationIds);
} }

View file

@ -538,7 +538,7 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref
// throw exception if the file is corrupt // throw exception if the file is corrupt
String checksum = Store.digestToString(CodecUtil.checksumEntireFile(input)); String checksum = Store.digestToString(CodecUtil.checksumEntireFile(input));
// throw exception if metadata is inconsistent // throw exception if metadata is inconsistent
if (!checksum.equals(md.checksum())) { if (checksum.equals(md.checksum()) == false) {
throw new CorruptIndexException("inconsistent metadata: lucene checksum=" + checksum + throw new CorruptIndexException("inconsistent metadata: lucene checksum=" + checksum +
", metadata checksum=" + md.checksum(), input); ", metadata checksum=" + md.checksum(), input);
} }
@ -1206,7 +1206,7 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref
private void readAndCompareChecksum() throws IOException { private void readAndCompareChecksum() throws IOException {
actualChecksum = digestToString(getChecksum()); actualChecksum = digestToString(getChecksum());
if (!metadata.checksum().equals(actualChecksum)) { if (metadata.checksum().equals(actualChecksum) == false) {
throw new CorruptIndexException("checksum failed (hardware problem?) : expected=" + metadata.checksum() + throw new CorruptIndexException("checksum failed (hardware problem?) : expected=" + metadata.checksum() +
" actual=" + actualChecksum + " actual=" + actualChecksum +
" (resource=" + metadata.toString() + ")", "VerifyingIndexOutput(" + metadata.name() + ")"); " (resource=" + metadata.toString() + ")", "VerifyingIndexOutput(" + metadata.name() + ")");
@ -1376,7 +1376,7 @@ public class Store extends AbstractIndexShardComponent implements Closeable, Ref
*/ */
public void markStoreCorrupted(IOException exception) throws IOException { public void markStoreCorrupted(IOException exception) throws IOException {
ensureOpen(); ensureOpen();
if (!isMarkedCorrupted()) { if (isMarkedCorrupted() == false) {
final String corruptionMarkerName = CORRUPTED_MARKER_NAME_PREFIX + UUIDs.randomBase64UUID(); final String corruptionMarkerName = CORRUPTED_MARKER_NAME_PREFIX + UUIDs.randomBase64UUID();
try (IndexOutput output = this.directory().createOutput(corruptionMarkerName, IOContext.DEFAULT)) { try (IndexOutput output = this.directory().createOutput(corruptionMarkerName, IOContext.DEFAULT)) {
CodecUtil.writeHeader(output, CODEC, CORRUPTED_MARKER_CODEC_VERSION); CodecUtil.writeHeader(output, CODEC, CORRUPTED_MARKER_CODEC_VERSION);

View file

@ -192,7 +192,7 @@ public class TermVectorsService {
Set<String> validFields = new HashSet<>(); Set<String> validFields = new HashSet<>();
for (String field : selectedFields) { for (String field : selectedFields) {
MappedFieldType fieldType = indexShard.mapperService().fieldType(field); MappedFieldType fieldType = indexShard.mapperService().fieldType(field);
if (!isValidField(fieldType)) { if (isValidField(fieldType) == false) {
continue; continue;
} }
// already retrieved, only if the analyzer hasn't been overridden at the field // already retrieved, only if the analyzer hasn't been overridden at the field
@ -296,10 +296,10 @@ public class TermVectorsService {
Collection<DocumentField> documentFields = new HashSet<>(); Collection<DocumentField> documentFields = new HashSet<>();
for (IndexableField field : doc.getFields()) { for (IndexableField field : doc.getFields()) {
MappedFieldType fieldType = indexShard.mapperService().fieldType(field.name()); MappedFieldType fieldType = indexShard.mapperService().fieldType(field.name());
if (!isValidField(fieldType)) { if (isValidField(fieldType) == false) {
continue; continue;
} }
if (request.selectedFields() != null && !request.selectedFields().contains(field.name())) { if (request.selectedFields() != null && request.selectedFields().contains(field.name()) == false) {
continue; continue;
} }
if (seenFields.contains(field.name())) { if (seenFields.contains(field.name())) {

View file

@ -409,7 +409,7 @@ public class StrictISODateTimeFormat {
boolean minute = fields.remove(DateTimeFieldType.minuteOfHour()); boolean minute = fields.remove(DateTimeFieldType.minuteOfHour());
boolean second = fields.remove(DateTimeFieldType.secondOfMinute()); boolean second = fields.remove(DateTimeFieldType.secondOfMinute());
boolean milli = fields.remove(DateTimeFieldType.millisOfSecond()); boolean milli = fields.remove(DateTimeFieldType.millisOfSecond());
if (!hour && !minute && !second && !milli) { if (hour == false && minute == false && second == false && milli == false) {
return; return;
} }
if (hour || minute || second || milli) { if (hour || minute || second || milli) {
@ -420,13 +420,13 @@ public class StrictISODateTimeFormat {
bld.appendLiteral('T'); bld.appendLiteral('T');
} }
} }
if (hour && minute && second || (hour && !second && !milli)) { if (hour && minute && second || (hour && second == false && milli == false)) {
// OK - HMSm/HMS/HM/H - valid in combination with date // OK - HMSm/HMS/HM/H - valid in combination with date
} else { } else {
if (strictISO && datePresent) { if (strictISO && datePresent) {
throw new IllegalArgumentException("No valid ISO8601 format for fields because Time was truncated: " + fields); throw new IllegalArgumentException("No valid ISO8601 format for fields because Time was truncated: " + fields);
} }
if (!hour && (minute && second || (minute && !milli) || second)) { if (hour == false && (minute && second || (minute && milli == false) || second)) {
// OK - MSm/MS/M/Sm/S - valid ISO formats // OK - MSm/MS/M/Sm/S - valid ISO formats
} else { } else {
if (strictISO) { if (strictISO) {

View file

@ -104,7 +104,7 @@ public class TransportActionFilterChainTests extends ESTestCase {
if (testFilter.callback == RequestOperation.LISTENER_FAILURE) { if (testFilter.callback == RequestOperation.LISTENER_FAILURE) {
errorExpected = true; errorExpected = true;
} }
if (!(testFilter.callback == RequestOperation.CONTINUE_PROCESSING) ) { if (testFilter.callback != RequestOperation.CONTINUE_PROCESSING) {
break; break;
} }
} }
@ -130,7 +130,7 @@ public class TransportActionFilterChainTests extends ESTestCase {
for (ActionFilter filter : testFiltersByLastExecution) { for (ActionFilter filter : testFiltersByLastExecution) {
RequestTestFilter testFilter = (RequestTestFilter) filter; RequestTestFilter testFilter = (RequestTestFilter) filter;
finalTestFilters.add(testFilter); finalTestFilters.add(testFilter);
if (!(testFilter.callback == RequestOperation.CONTINUE_PROCESSING) ) { if (testFilter.callback != RequestOperation.CONTINUE_PROCESSING) {
break; break;
} }
} }
@ -186,7 +186,7 @@ public class TransportActionFilterChainTests extends ESTestCase {
} }
}, latch)); }, latch));
if (!latch.await(10, TimeUnit.SECONDS)) { if (latch.await(10, TimeUnit.SECONDS) == false) {
fail("timeout waiting for the filter to notify the listener as many times as expected"); fail("timeout waiting for the filter to notify the listener as many times as expected");
} }

View file

@ -203,7 +203,7 @@ public class GetTermVectorsTests extends ESSingleNodeTestCase {
String resultString = ""; String resultString = "";
Map<String, Integer> payloadCounter = new HashMap<>(); Map<String, Integer> payloadCounter = new HashMap<>();
for (String token : tokens) { for (String token : tokens) {
if (!payloadCounter.containsKey(token)) { if (payloadCounter.containsKey(token) == false) {
payloadCounter.putIfAbsent(token, 0); payloadCounter.putIfAbsent(token, 0);
} else { } else {
payloadCounter.put(token, payloadCounter.get(token) + 1); payloadCounter.put(token, payloadCounter.get(token) + 1);

View file

@ -201,7 +201,7 @@ public abstract class AbstractClientHeadersTestCase extends ESTestCase {
public Throwable unwrap(Throwable t, Class<? extends Throwable> exceptionType) { public Throwable unwrap(Throwable t, Class<? extends Throwable> exceptionType) {
int counter = 0; int counter = 0;
Throwable result = t; Throwable result = t;
while (!exceptionType.isInstance(result)) { while (exceptionType.isInstance(result) == false) {
if (result.getCause() == null) { if (result.getCause() == null) {
return null; return null;
} }

View file

@ -298,7 +298,7 @@ public class FailedShardsRoutingTests extends ESAllocationTestCase {
nodeBuilder.add(newNode("node" + Integer.toString(i))); nodeBuilder.add(newNode("node" + Integer.toString(i)));
} }
clusterState = ClusterState.builder(clusterState).nodes(nodeBuilder).build(); clusterState = ClusterState.builder(clusterState).nodes(nodeBuilder).build();
while (!clusterState.routingTable().shardsWithState(UNASSIGNED).isEmpty()) { while (clusterState.routingTable().shardsWithState(UNASSIGNED).isEmpty() == false) {
clusterState = startInitializingShardsAndReroute(strategy, clusterState); clusterState = startInitializingShardsAndReroute(strategy, clusterState);
} }
@ -328,7 +328,7 @@ public class FailedShardsRoutingTests extends ESAllocationTestCase {
} }
for (String failedNode : failedNodes) { for (String failedNode : failedNodes) {
if (!routingNodes.node(failedNode).isEmpty()) { if (routingNodes.node(failedNode).isEmpty() == false) {
fail("shard was re-assigned to failed node " + failedNode); fail("shard was re-assigned to failed node " + failedNode);
} }
} }

View file

@ -444,7 +444,7 @@ public class NodeVersionAllocationDeciderTests extends ESAllocationTestCase {
mutableShardRoutings = routingNodes.shardsWithState(ShardRoutingState.INITIALIZING); mutableShardRoutings = routingNodes.shardsWithState(ShardRoutingState.INITIALIZING);
for (ShardRouting r : mutableShardRoutings) { for (ShardRouting r : mutableShardRoutings) {
if (!r.primary()) { if (r.primary() == false) {
ShardRouting primary = routingNodes.activePrimary(r.shardId()); ShardRouting primary = routingNodes.activePrimary(r.shardId());
assertThat(primary, notNullValue()); assertThat(primary, notNullValue());
String fromId = primary.currentNodeId(); String fromId = primary.currentNodeId();

View file

@ -452,7 +452,7 @@ public class MasterServiceTests extends ESTestCase {
} }
public void execute() { public void execute() {
if (!state.compareAndSet(false, true)) { if (state.compareAndSet(false, true) == false) {
throw new IllegalStateException(); throw new IllegalStateException();
} else { } else {
counter.incrementAndGet(); counter.incrementAndGet();

View file

@ -758,7 +758,7 @@ public class CacheTests extends ESTestCase {
Set<Long> ids = threads.stream().map(t -> t.getId()).collect(Collectors.toSet()); Set<Long> ids = threads.stream().map(t -> t.getId()).collect(Collectors.toSet());
ThreadMXBean mxBean = ManagementFactory.getThreadMXBean(); ThreadMXBean mxBean = ManagementFactory.getThreadMXBean();
long[] deadlockedThreads = mxBean.findDeadlockedThreads(); long[] deadlockedThreads = mxBean.findDeadlockedThreads();
if (!deadlock.get() && deadlockedThreads != null) { if (deadlock.get() == false && deadlockedThreads != null) {
for (long deadlockedThread : deadlockedThreads) { for (long deadlockedThread : deadlockedThreads) {
// ensure that we detected deadlock on our threads // ensure that we detected deadlock on our threads
if (ids.contains(deadlockedThread)) { if (ids.contains(deadlockedThread)) {

View file

@ -141,7 +141,7 @@ public class FreqTermsEnumTests extends ESTestCase {
for (int docId = 0; docId < reader.maxDoc(); docId++) { for (int docId = 0; docId < reader.maxDoc(); docId++) {
Document doc = reader.document(docId); Document doc = reader.document(docId);
addFreqs(doc, referenceAll); addFreqs(doc, referenceAll);
if (!deletedIds.contains(doc.getField("id").stringValue())) { if (deletedIds.contains(doc.getField("id").stringValue()) == false) {
addFreqs(doc, referenceNotDeleted); addFreqs(doc, referenceNotDeleted);
if (randomBoolean()) { if (randomBoolean()) {
filterTerms.add(new BytesRef(doc.getField("id").stringValue())); filterTerms.add(new BytesRef(doc.getField("id").stringValue()));
@ -157,7 +157,7 @@ public class FreqTermsEnumTests extends ESTestCase {
for (IndexableField field : doc.getFields("field")) { for (IndexableField field : doc.getFields("field")) {
String term = field.stringValue(); String term = field.stringValue();
FreqHolder freqHolder = reference.get(term); FreqHolder freqHolder = reference.get(term);
if (!addedDocFreq.contains(term)) { if (addedDocFreq.contains(term) == false) {
freqHolder.docFreq++; freqHolder.docFreq++;
addedDocFreq.add(term); addedDocFreq.add(term);
} }
@ -204,7 +204,7 @@ public class FreqTermsEnumTests extends ESTestCase {
Collections.shuffle(terms, random()); Collections.shuffle(terms, random());
for (String term : terms) { for (String term : terms) {
if (!termsEnum.seekExact(new BytesRef(term))) { if (termsEnum.seekExact(new BytesRef(term)) == false) {
assertThat("term : " + term, reference.get(term).docFreq, is(0)); assertThat("term : " + term, reference.get(term).docFreq, is(0));
continue; continue;
} }

View file

@ -86,7 +86,7 @@ public class CancellableThreadsTests extends ESTestCase {
readyForCancel.countDown(); readyForCancel.countDown();
try { try {
if (plan.busySpin) { if (plan.busySpin) {
while (!Thread.currentThread().isInterrupted()) { while (Thread.currentThread().isInterrupted() == false) {
} }
} else { } else {
Thread.sleep(50000); Thread.sleep(50000);

View file

@ -59,7 +59,7 @@ public class PrioritizedExecutorsTests extends ESTestCase {
} }
Priority prevPriority = null; Priority prevPriority = null;
while (!queue.isEmpty()) { while (queue.isEmpty() == false) {
if (prevPriority == null) { if (prevPriority == null) {
prevPriority = queue.poll(); prevPriority = queue.poll();
} else { } else {

View file

@ -118,7 +118,7 @@ public class SeedHostsResolverTests extends ESTestCase {
logger.info("shutting down..."); logger.info("shutting down...");
// JDK stack is broken, it does not iterate in the expected order (http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4475301) // JDK stack is broken, it does not iterate in the expected order (http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4475301)
final List<Closeable> reverse = new ArrayList<>(); final List<Closeable> reverse = new ArrayList<>();
while (!closeables.isEmpty()) { while (closeables.isEmpty() == false) {
reverse.add(closeables.pop()); reverse.add(closeables.pop());
} }
IOUtils.close(reverse); IOUtils.close(reverse);

View file

@ -327,7 +327,7 @@ public abstract class AbstractStringFieldDataTestCase extends AbstractFieldDataI
final String docValue = searcher.doc(topDocs.scoreDocs[i].doc).get("value"); final String docValue = searcher.doc(topDocs.scoreDocs[i].doc).get("value");
if (first && docValue == null) { if (first && docValue == null) {
assertNull(previousValue); assertNull(previousValue);
} else if (!first && docValue != null) { } else if (first == false && docValue != null) {
assertNotNull(previousValue); assertNotNull(previousValue);
} }
final BytesRef value = docValue == null ? null : new BytesRef(docValue); final BytesRef value = docValue == null ? null : new BytesRef(docValue);

View file

@ -110,7 +110,7 @@ public class MultiOrdinalsTests extends ESTestCase {
if (docId == ordAndId.id) { if (docId == ordAndId.id) {
docOrds.add(ordAndId.ord); docOrds.add(ordAndId.ord);
} else { } else {
if (!docOrds.isEmpty()) { if (docOrds.isEmpty() == false) {
assertTrue(singleOrds.advanceExact(docId)); assertTrue(singleOrds.advanceExact(docId));
assertThat((long) singleOrds.ordValue(), equalTo(docOrds.get(0))); assertThat((long) singleOrds.ordValue(), equalTo(docOrds.get(0)));

View file

@ -89,7 +89,7 @@ public class DocumentFieldTests extends ESTestCase {
mutations.add(() -> new DocumentField(documentField.getName(), randomDocumentField(XContentType.JSON).v1().getValues())); mutations.add(() -> new DocumentField(documentField.getName(), randomDocumentField(XContentType.JSON).v1().getValues()));
final int index = randomFrom(0, 1); final int index = randomFrom(0, 1);
final DocumentField randomCandidate = mutations.get(index).get(); final DocumentField randomCandidate = mutations.get(index).get();
if (!documentField.equals(randomCandidate)) { if (documentField.equals(randomCandidate) == false) {
return randomCandidate; return randomCandidate;
} else { } else {
// we are unlucky and our random mutation is equal to our mutation, try the other candidate // we are unlucky and our random mutation is equal to our mutation, try the other candidate

View file

@ -79,7 +79,7 @@ public class BoolQueryBuilderTests extends AbstractQueryTestCase<BoolQueryBuilde
@Override @Override
protected void doAssertLuceneQuery(BoolQueryBuilder queryBuilder, Query query, SearchExecutionContext context) throws IOException { protected void doAssertLuceneQuery(BoolQueryBuilder queryBuilder, Query query, SearchExecutionContext context) throws IOException {
if (!queryBuilder.hasClauses()) { if (queryBuilder.hasClauses() == false) {
assertThat(query, instanceOf(MatchAllDocsQuery.class)); assertThat(query, instanceOf(MatchAllDocsQuery.class));
} else { } else {
List<BooleanClause> clauses = new ArrayList<>(); List<BooleanClause> clauses = new ArrayList<>();

View file

@ -951,7 +951,7 @@ public class ReplicationTrackerTests extends ReplicationTrackerTestCase {
do { do {
final AllocationId newAllocationId = AllocationId.newInitializing(); final AllocationId newAllocationId = AllocationId.newInitializing();
// ensure we do not duplicate an allocation ID // ensure we do not duplicate an allocation ID
if (!existingAllocationIds.contains(newAllocationId)) { if (existingAllocationIds.contains(newAllocationId) == false) {
return newAllocationId; return newAllocationId;
} }
} while (true); } while (true);

View file

@ -1568,7 +1568,7 @@ public class IndexShardTests extends IndexShardTestCase {
ElasticsearchException e = expectThrows(ElasticsearchException.class, shard::storeStats); ElasticsearchException e = expectThrows(ElasticsearchException.class, shard::storeStats);
assertTrue(failureCallbackTriggered.get()); assertTrue(failureCallbackTriggered.get());
if (corruptIndexException && !throwWhenMarkingStoreCorrupted.get()) { if (corruptIndexException && throwWhenMarkingStoreCorrupted.get() == false) {
assertTrue(store.isMarkedCorrupted()); assertTrue(store.isMarkedCorrupted());
} }
} }
@ -3313,7 +3313,7 @@ public class IndexShardTests extends IndexShardTestCase {
boolean gap = false; boolean gap = false;
Set<String> ids = new HashSet<>(); Set<String> ids = new HashSet<>();
for (int i = offset + 1; i < operations; i++) { for (int i = offset + 1; i < operations; i++) {
if (!rarely() || i == operations - 1) { // last operation can't be a gap as it's not a gap anymore if (rarely() == false || i == operations - 1) { // last operation can't be a gap as it's not a gap anymore
final String id = ids.isEmpty() || randomBoolean() ? Integer.toString(i) : randomFrom(ids); final String id = ids.isEmpty() || randomBoolean() ? Integer.toString(i) : randomFrom(ids);
if (ids.add(id) == false) { // this is an update if (ids.add(id) == false) { // this is an update
indexShard.advanceMaxSeqNoOfUpdatesOrDeletes(i); indexShard.advanceMaxSeqNoOfUpdatesOrDeletes(i);
@ -3322,7 +3322,7 @@ public class IndexShardTests extends IndexShardTestCase {
new BytesArray("{}"), XContentType.JSON); new BytesArray("{}"), XContentType.JSON);
indexShard.applyIndexOperationOnReplica(i, indexShard.getOperationPrimaryTerm(), 1, indexShard.applyIndexOperationOnReplica(i, indexShard.getOperationPrimaryTerm(), 1,
IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, sourceToParse); IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP, false, sourceToParse);
if (!gap && i == localCheckpoint + 1) { if (gap == false && i == localCheckpoint + 1) {
localCheckpoint++; localCheckpoint++;
} }
max = i; max = i;

View file

@ -469,8 +469,8 @@ public class StoreTests extends ESTestCase {
public static void assertConsistent(Store store, Store.MetadataSnapshot metadata) throws IOException { public static void assertConsistent(Store store, Store.MetadataSnapshot metadata) throws IOException {
for (String file : store.directory().listAll()) { for (String file : store.directory().listAll()) {
if (!IndexWriter.WRITE_LOCK_NAME.equals(file) && if (IndexWriter.WRITE_LOCK_NAME.equals(file) == false &&
!IndexFileNames.OLD_SEGMENTS_GEN.equals(file) && file.startsWith("extra") == false) { IndexFileNames.OLD_SEGMENTS_GEN.equals(file) == false && file.startsWith("extra") == false) {
assertTrue(file + " is not in the map: " + metadata.asMap().size() + " vs. " + assertTrue(file + " is not in the map: " + metadata.asMap().size() + " vs. " +
store.directory().listAll().length, metadata.asMap().containsKey(file)); store.directory().listAll().length, metadata.asMap().containsKey(file));
} else { } else {

View file

@ -3167,7 +3167,7 @@ public class TranslogTests extends ESTestCase {
final long generation = translog.getMinGenerationForSeqNo(seqNo).translogFileGeneration; final long generation = translog.getMinGenerationForSeqNo(seqNo).translogFileGeneration;
int expectedSnapshotOps = 0; int expectedSnapshotOps = 0;
for (long g = generation; g < translog.currentFileGeneration(); g++) { for (long g = generation; g < translog.currentFileGeneration(); g++) {
if (!seqNoPerGeneration.containsKey(g)) { if (seqNoPerGeneration.containsKey(g) == false) {
final Set<Tuple<Long, Long>> generationSeenSeqNos = new HashSet<>(); final Set<Tuple<Long, Long>> generationSeenSeqNos = new HashSet<>();
int opCount = 0; int opCount = 0;
final Checkpoint checkpoint = Checkpoint.read(translog.location().resolve(Translog.getCommitCheckpointFileName(g))); final Checkpoint checkpoint = Checkpoint.read(translog.location().resolve(Translog.getCommitCheckpointFileName(g)));

View file

@ -539,7 +539,7 @@ public class HierarchyCircuitBreakerServiceTests extends ESTestCase {
assertThat(output.transientChildUsage, equalTo(input.transientChildUsage)); assertThat(output.transientChildUsage, equalTo(input.transientChildUsage));
assertThat(output.permanentChildUsage, equalTo(input.permanentChildUsage)); assertThat(output.permanentChildUsage, equalTo(input.permanentChildUsage));
countDown.get().countDown(); countDown.get().countDown();
} while (!Thread.interrupted()); } while (Thread.interrupted() == false);
})).collect(Collectors.toList()); })).collect(Collectors.toList());
threads.forEach(Thread::start); threads.forEach(Thread::start);

View file

@ -53,7 +53,9 @@ public class JvmInfoTests extends ESTestCase {
private boolean flagIsEnabled(String argline, String flag) { private boolean flagIsEnabled(String argline, String flag) {
final boolean containsPositiveFlag = argline != null && argline.contains("-XX:+" + flag); final boolean containsPositiveFlag = argline != null && argline.contains("-XX:+" + flag);
if (!containsPositiveFlag) return false; if (containsPositiveFlag == false) {
return false;
}
final int index = argline.lastIndexOf(flag); final int index = argline.lastIndexOf(flag);
return argline.charAt(index - 1) == '+'; return argline.charAt(index - 1) == '+';
} }

View file

@ -123,7 +123,7 @@ public class AggregatorFactoriesTests extends ESTestCase {
word[i] = (char) rand.nextInt(127); word[i] = (char) rand.nextInt(127);
} }
name = String.valueOf(word); name = String.valueOf(word);
if (!matcher.reset(name).matches()) { if (matcher.reset(name).matches() == false) {
break; break;
} }
} }

Some files were not shown because too many files have changed in this diff Show more