diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java index 85612147b464d..5dc4c88cbbcc1 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/CRUDDocumentationIT.java @@ -114,6 +114,7 @@ */ public class CRUDDocumentationIT extends ESRestHighLevelClientTestCase { + @SuppressWarnings("unused") public void testIndex() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -278,6 +279,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testUpdate() throws Exception { RestHighLevelClient client = highLevelClient(); { @@ -546,6 +548,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testDelete() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -665,6 +668,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testBulk() throws Exception { RestHighLevelClient client = highLevelClient(); { @@ -767,6 +771,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testReindex() throws Exception { RestHighLevelClient client = highLevelClient(); { @@ -905,6 +910,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testReindexRethrottle() throws Exception { RestHighLevelClient client = highLevelClient(); TaskId taskId = new TaskId("oTUltX4IQMOUUVeiohTt8A:124"); @@ -947,6 +953,7 @@ public void onFailure(Exception e) { assertTrue(latch.await(30L, TimeUnit.SECONDS)); } + @SuppressWarnings("unused") public void testUpdateByQuery() throws Exception { RestHighLevelClient client = highLevelClient(); { @@ -1066,6 +1073,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testDeleteByQuery() throws Exception { RestHighLevelClient client = highLevelClient(); { @@ -1173,6 +1181,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testGet() throws Exception { RestHighLevelClient client = highLevelClient(); { @@ -1487,6 +1496,7 @@ public void afterBulk(long executionId, BulkRequest request, Throwable failure) } } + @SuppressWarnings("unused") public void testMultiGet() throws Exception { RestHighLevelClient client = highLevelClient(); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/ClusterClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/ClusterClientDocumentationIT.java index dedd50096f826..170bd435856aa 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/ClusterClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/ClusterClientDocumentationIT.java @@ -192,6 +192,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testClusterGetSettings() throws IOException { RestHighLevelClient client = highLevelClient(); @@ -257,6 +258,7 @@ public void onFailure(Exception e) { assertTrue(latch.await(30L, TimeUnit.SECONDS)); } + @SuppressWarnings("unused") public void testClusterHealth() throws IOException { RestHighLevelClient client = highLevelClient(); client.indices().create(new CreateIndexRequest("index"), RequestOptions.DEFAULT); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/IndicesClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/IndicesClientDocumentationIT.java index 2da4d306c2829..c66baf69d961e 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/IndicesClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/IndicesClientDocumentationIT.java @@ -706,6 +706,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testGetFieldMapping() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); @@ -891,6 +892,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testRefreshIndex() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -959,6 +961,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testFlushIndex() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -1035,6 +1038,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testSyncedFlushIndex() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -1308,6 +1312,7 @@ public void onFailure(Exception e) { assertTrue(latch.await(30L, TimeUnit.SECONDS)); } + @SuppressWarnings("unused") public void testForceMergeIndex() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -1381,6 +1386,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testClearCache() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -1527,6 +1533,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testExistsAlias() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -1590,6 +1597,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testUpdateAliases() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -1915,6 +1923,7 @@ public void onFailure(Exception e) { assertTrue(latch.await(30L, TimeUnit.SECONDS)); } + @SuppressWarnings("unused") public void testGetAlias() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -1985,6 +1994,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testIndexPutSettings() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -2315,6 +2325,7 @@ public void onFailure(Exception e) { assertTrue(latch.await(30L, TimeUnit.SECONDS)); } + @SuppressWarnings("unused") public void testValidateQuery() throws IOException, InterruptedException { RestHighLevelClient client = highLevelClient(); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/IngestClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/IngestClientDocumentationIT.java index 4702c34c6de3d..00bee27807f5f 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/IngestClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/IngestClientDocumentationIT.java @@ -143,6 +143,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testGetPipeline() throws IOException { RestHighLevelClient client = highLevelClient(); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java index d9d4f665f9d7c..4382924bb97e9 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SearchDocumentationIT.java @@ -413,6 +413,7 @@ public void testSearchRequestSuggestions() throws IOException { } } + @SuppressWarnings("unused") public void testSearchRequestHighlighting() throws IOException { RestHighLevelClient client = highLevelClient(); { @@ -831,6 +832,8 @@ public void onFailure(Exception e) { assertTrue(latch.await(30L, TimeUnit.SECONDS)); } + + @SuppressWarnings("unused") public void testMultiSearchTemplateWithInlineScript() throws Exception { indexSearchTestData(); RestHighLevelClient client = highLevelClient(); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SnapshotClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SnapshotClientDocumentationIT.java index d1aed55f44e5b..22ef30c92b78c 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SnapshotClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/SnapshotClientDocumentationIT.java @@ -577,6 +577,7 @@ public void onFailure(Exception exception) { } } + @SuppressWarnings("unused") public void testSnapshotGetSnapshots() throws IOException { RestHighLevelClient client = highLevelClient(); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java index c5d53abd978e1..9165c5cf10d0e 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/StoredScriptsDocumentationIT.java @@ -66,6 +66,7 @@ */ public class StoredScriptsDocumentationIT extends ESRestHighLevelClientTestCase { + @SuppressWarnings("unused") public void testGetStoredScript() throws Exception { RestHighLevelClient client = highLevelClient(); @@ -128,6 +129,7 @@ public void onFailure(Exception e) { } + @SuppressWarnings("unused") public void testDeleteStoredScript() throws Exception { RestHighLevelClient client = highLevelClient(); diff --git a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/TasksClientDocumentationIT.java b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/TasksClientDocumentationIT.java index 8a45195757c13..38c8986e1d9f0 100644 --- a/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/TasksClientDocumentationIT.java +++ b/client/rest-high-level/src/test/java/org/elasticsearch/client/documentation/TasksClientDocumentationIT.java @@ -66,6 +66,7 @@ */ public class TasksClientDocumentationIT extends ESRestHighLevelClientTestCase { + @SuppressWarnings("unused") public void testListTasks() throws IOException { RestHighLevelClient client = highLevelClient(); { @@ -149,6 +150,7 @@ public void onFailure(Exception e) { } } + @SuppressWarnings("unused") public void testCancelTasks() throws IOException { RestHighLevelClient client = highLevelClient(); { diff --git a/libs/grok/src/main/java/org/elasticsearch/grok/Grok.java b/libs/grok/src/main/java/org/elasticsearch/grok/Grok.java index 6c68710c6d8bd..c20737998feb9 100644 --- a/libs/grok/src/main/java/org/elasticsearch/grok/Grok.java +++ b/libs/grok/src/main/java/org/elasticsearch/grok/Grok.java @@ -35,12 +35,12 @@ import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.Collections; public final class Grok { @@ -184,6 +184,7 @@ public String toRegex(String grokPattern) { String namedPatternRef = groupMatch(NAME_GROUP, region, grokPattern); String subName = groupMatch(SUBNAME_GROUP, region, grokPattern); // TODO(tal): Support definitions + @SuppressWarnings("unused") String definition = groupMatch(DEFINITION_GROUP, region, grokPattern); String patternName = groupMatch(PATTERN_GROUP, region, grokPattern); diff --git a/libs/grok/src/test/java/org/elasticsearch/grok/GrokTests.java b/libs/grok/src/test/java/org/elasticsearch/grok/GrokTests.java index d30cf3d6fa21b..f9d2055de1b36 100644 --- a/libs/grok/src/test/java/org/elasticsearch/grok/GrokTests.java +++ b/libs/grok/src/test/java/org/elasticsearch/grok/GrokTests.java @@ -262,8 +262,6 @@ public void testCircularReference() { } public void testBooleanCaptures() { - Map bank = new HashMap<>(); - String pattern = "%{WORD:name}=%{WORD:status:boolean}"; Grok g = new Grok(basePatterns, pattern); diff --git a/libs/nio/src/test/java/org/elasticsearch/nio/FlushOperationTests.java b/libs/nio/src/test/java/org/elasticsearch/nio/FlushOperationTests.java index 0f3078715fdac..4f2a320ad583d 100644 --- a/libs/nio/src/test/java/org/elasticsearch/nio/FlushOperationTests.java +++ b/libs/nio/src/test/java/org/elasticsearch/nio/FlushOperationTests.java @@ -21,7 +21,6 @@ import org.elasticsearch.test.ESTestCase; import org.junit.Before; -import org.mockito.ArgumentCaptor; import java.io.IOException; import java.nio.ByteBuffer; @@ -61,8 +60,6 @@ public void testMultipleFlushesWithCompositeBuffer() throws IOException { ByteBuffer[] buffers = {ByteBuffer.allocate(10), ByteBuffer.allocate(15), ByteBuffer.allocate(3)}; FlushOperation writeOp = new FlushOperation(buffers, listener); - ArgumentCaptor buffersCaptor = ArgumentCaptor.forClass(ByteBuffer[].class); - writeOp.incrementIndex(5); assertFalse(writeOp.isFullyFlushed()); ByteBuffer[] byteBuffers = writeOp.getBuffersToWrite(); diff --git a/libs/x-content/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java b/libs/x-content/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java index 6aa0a321adf4d..42d53bf49859b 100644 --- a/libs/x-content/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java +++ b/libs/x-content/src/test/java/org/elasticsearch/common/xcontent/ObjectParserTests.java @@ -222,6 +222,7 @@ class TestStruct { public void testFailOnValueType() throws IOException { XContentParser parser = createParser(JsonXContent.jsonXContent, "{\"numeric_value\" : false}"); class TestStruct { + @SuppressWarnings("unused") public String test; } ObjectParser objectParser = new ObjectParser<>("foo"); diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/KeepWordFilterFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/KeepWordFilterFactory.java index df67f24cc7f5f..e89219da4d971 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/KeepWordFilterFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/KeepWordFilterFactory.java @@ -54,6 +54,7 @@ public class KeepWordFilterFactory extends AbstractTokenFilterFactory { private final CharArraySet keepWords; private static final String KEEP_WORDS_KEY = "keep_words"; private static final String KEEP_WORDS_PATH_KEY = KEEP_WORDS_KEY + "_path"; + @SuppressWarnings("unused") private static final String KEEP_WORDS_CASE_KEY = KEEP_WORDS_KEY + "_case"; // for javadoc // unsupported ancient option diff --git a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/StemmerTokenFilterFactory.java b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/StemmerTokenFilterFactory.java index 67895e82e61c6..829d97463996c 100644 --- a/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/StemmerTokenFilterFactory.java +++ b/modules/analysis-common/src/main/java/org/elasticsearch/analysis/common/StemmerTokenFilterFactory.java @@ -53,7 +53,6 @@ import org.apache.lucene.analysis.ru.RussianLightStemFilter; import org.apache.lucene.analysis.snowball.SnowballFilter; import org.apache.lucene.analysis.sv.SwedishLightStemFilter; -import org.elasticsearch.Version; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.env.Environment; @@ -94,8 +93,6 @@ public class StemmerTokenFilterFactory extends AbstractTokenFilterFactory { @Override public TokenStream create(TokenStream tokenStream) { - final Version indexVersion = indexSettings.getIndexVersionCreated(); - if ("arabic".equalsIgnoreCase(language)) { return new ArabicStemFilter(tokenStream); } else if ("armenian".equalsIgnoreCase(language)) { diff --git a/modules/lang-painless/src/main/java/org/elasticsearch/painless/Locals.java b/modules/lang-painless/src/main/java/org/elasticsearch/painless/Locals.java index e07c016ddd0e3..d819f53bf0bea 100644 --- a/modules/lang-painless/src/main/java/org/elasticsearch/painless/Locals.java +++ b/modules/lang-painless/src/main/java/org/elasticsearch/painless/Locals.java @@ -295,7 +295,6 @@ public static final class Variable { public final Class clazz; public final boolean readonly; private final int slot; - private boolean used; public Variable(Location location, String name, Class clazz, int slot, boolean readonly) { this.location = location; diff --git a/modules/parent-join/src/test/java/org/elasticsearch/join/aggregations/ChildrenIT.java b/modules/parent-join/src/test/java/org/elasticsearch/join/aggregations/ChildrenIT.java index f7f3b89773b35..61f00647f3c06 100644 --- a/modules/parent-join/src/test/java/org/elasticsearch/join/aggregations/ChildrenIT.java +++ b/modules/parent-join/src/test/java/org/elasticsearch/join/aggregations/ChildrenIT.java @@ -91,7 +91,7 @@ public void setupCluster() throws Exception { String category = categories[j] = uniqueCategories[catIndex++ % uniqueCategories.length]; Control control = categoryToControl.get(category); if (control == null) { - categoryToControl.put(category, control = new Control(category)); + categoryToControl.put(category, control = new Control()); } control.articleIds.add(id); } @@ -457,14 +457,8 @@ public void testPostCollectAllLeafReaders() throws Exception { } private static final class Control { - - final String category; final Set articleIds = new HashSet<>(); final Set commentIds = new HashSet<>(); final Map> commenterToCommentId = new HashMap<>(); - - private Control(String category) { - this.category = category; - } } } diff --git a/modules/reindex/src/test/java/org/elasticsearch/client/documentation/ReindexDocumentationIT.java b/modules/reindex/src/test/java/org/elasticsearch/client/documentation/ReindexDocumentationIT.java index 93c785e754a54..b5960592508bf 100644 --- a/modules/reindex/src/test/java/org/elasticsearch/client/documentation/ReindexDocumentationIT.java +++ b/modules/reindex/src/test/java/org/elasticsearch/client/documentation/ReindexDocumentationIT.java @@ -45,6 +45,7 @@ public class ReindexDocumentationIT extends ESIntegTestCase { + @SuppressWarnings("unused") public void reindex() { Client client = client(); // tag::reindex1 @@ -55,6 +56,7 @@ public void reindex() { // end::reindex1 } + @SuppressWarnings("unused") public void updateByQuery() { Client client = client(); { @@ -165,6 +167,7 @@ public void updateByQuery() { } } + @SuppressWarnings("unused") public void deleteByQuery() { Client client = client(); // tag::delete-by-query-sync diff --git a/plugins/analysis-icu/src/main/java/org/elasticsearch/index/mapper/ICUCollationKeywordFieldMapper.java b/plugins/analysis-icu/src/main/java/org/elasticsearch/index/mapper/ICUCollationKeywordFieldMapper.java index 0235e6e81368f..055c792282267 100644 --- a/plugins/analysis-icu/src/main/java/org/elasticsearch/index/mapper/ICUCollationKeywordFieldMapper.java +++ b/plugins/analysis-icu/src/main/java/org/elasticsearch/index/mapper/ICUCollationKeywordFieldMapper.java @@ -86,6 +86,7 @@ protected CollationFieldType(CollationFieldType ref) { this.collator = ref.collator; } + @Override public CollationFieldType clone() { return new CollationFieldType(this); } @@ -239,7 +240,6 @@ public static class Builder extends FieldMapper.Builder listener) { ClusterState clusterState = clusterService.state(); assert Node.NODE_NAME_SETTING.exists(settings); - final boolean available = clusterState.getBlocks().hasGlobalBlock(RestStatus.SERVICE_UNAVAILABLE) == false; listener.onResponse( new MainResponse(Node.NODE_NAME_SETTING.get(settings), Version.CURRENT, clusterState.getClusterName(), clusterState.metaData().clusterUUID(), Build.CURRENT)); diff --git a/server/src/main/java/org/elasticsearch/action/support/single/shard/SingleShardRequest.java b/server/src/main/java/org/elasticsearch/action/support/single/shard/SingleShardRequest.java index 88c65381e7ad8..6dc11877e7cd7 100644 --- a/server/src/main/java/org/elasticsearch/action/support/single/shard/SingleShardRequest.java +++ b/server/src/main/java/org/elasticsearch/action/support/single/shard/SingleShardRequest.java @@ -44,7 +44,6 @@ public abstract class SingleShardRequest memberType; - private final String memberKey; private MemberImpl(Member member) { this.declaringClass = member.getDeclaringClass(); @@ -642,7 +641,6 @@ private MemberImpl(Member member) { this.modifiers = member.getModifiers(); this.synthetic = member.isSynthetic(); this.memberType = memberType(member); - this.memberKey = memberKey(member); } @Override diff --git a/server/src/main/java/org/elasticsearch/common/lucene/search/XMoreLikeThis.java b/server/src/main/java/org/elasticsearch/common/lucene/search/XMoreLikeThis.java index 5d1e4537f6561..f931ee2dc31a7 100644 --- a/server/src/main/java/org/elasticsearch/common/lucene/search/XMoreLikeThis.java +++ b/server/src/main/java/org/elasticsearch/common/lucene/search/XMoreLikeThis.java @@ -759,11 +759,11 @@ private PriorityQueue createQueue(Map words, String... f if (queue.size() < limit) { // there is still space in the queue - queue.add(new ScoreTerm(word, topField, score, idf, docFreq, tf)); + queue.add(new ScoreTerm(word, topField, score)); } else { ScoreTerm term = queue.top(); if (term.score < score) { // update the smallest in the queue in place and update the queue. - term.update(word, topField, score, idf, docFreq, tf); + term.update(word, topField, score); queue.updateTop(); } } @@ -1026,30 +1026,20 @@ protected boolean lessThan(ScoreTerm a, ScoreTerm b) { } private static class ScoreTerm { - // only really need 1st 3 entries, other ones are for troubleshooting String word; String topField; float score; - float idf; - int docFreq; - int tf; - ScoreTerm(String word, String topField, float score, float idf, int docFreq, int tf) { + ScoreTerm(String word, String topField, float score) { this.word = word; this.topField = topField; this.score = score; - this.idf = idf; - this.docFreq = docFreq; - this.tf = tf; } - void update(String word, String topField, float score, float idf, int docFreq, int tf) { + void update(String word, String topField, float score) { this.word = word; this.topField = topField; this.score = score; - this.idf = idf; - this.docFreq = docFreq; - this.tf = tf; } } diff --git a/server/src/main/java/org/elasticsearch/index/mapper/BooleanFieldMapper.java b/server/src/main/java/org/elasticsearch/index/mapper/BooleanFieldMapper.java index cb44e777f871d..9e0b9f62acbe7 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/BooleanFieldMapper.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/BooleanFieldMapper.java @@ -30,8 +30,6 @@ import org.apache.lucene.search.TermRangeQuery; import org.apache.lucene.util.BytesRef; import org.elasticsearch.common.Nullable; -import org.elasticsearch.common.logging.DeprecationLogger; -import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; @@ -55,7 +53,6 @@ * A field mapper for boolean fields. */ public class BooleanFieldMapper extends FieldMapper { - private static final DeprecationLogger deprecationLogger = new DeprecationLogger(Loggers.getLogger(BooleanFieldMapper.class)); public static final String CONTENT_TYPE = "boolean"; diff --git a/server/src/main/java/org/elasticsearch/index/mapper/GeoPointFieldMapper.java b/server/src/main/java/org/elasticsearch/index/mapper/GeoPointFieldMapper.java index 350dc27c615b3..587e9abd50bf9 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/GeoPointFieldMapper.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/GeoPointFieldMapper.java @@ -306,12 +306,11 @@ public void parse(ParseContext context) throws IOException { // its an array of other possible values if (token == XContentParser.Token.VALUE_NUMBER) { double lon = context.parser().doubleValue(); - token = context.parser().nextToken(); + context.parser().nextToken(); double lat = context.parser().doubleValue(); token = context.parser().nextToken(); - Double alt = Double.NaN; if (token == XContentParser.Token.VALUE_NUMBER) { - alt = GeoPoint.assertZValue(ignoreZValue.value(), context.parser().doubleValue()); + GeoPoint.assertZValue(ignoreZValue.value(), context.parser().doubleValue()); } else if (token != XContentParser.Token.END_ARRAY) { throw new ElasticsearchParseException("[{}] field type does not accept > 3 dimensions", CONTENT_TYPE); } diff --git a/server/src/main/java/org/elasticsearch/index/mapper/TextFieldMapper.java b/server/src/main/java/org/elasticsearch/index/mapper/TextFieldMapper.java index f7bcab21d723d..7851bb1655ad0 100644 --- a/server/src/main/java/org/elasticsearch/index/mapper/TextFieldMapper.java +++ b/server/src/main/java/org/elasticsearch/index/mapper/TextFieldMapper.java @@ -19,7 +19,6 @@ package org.elasticsearch.index.mapper; -import org.apache.logging.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.AnalyzerWrapper; import org.apache.lucene.analysis.CachingTokenFilter; @@ -42,7 +41,6 @@ import org.apache.lucene.search.TermQuery; import org.elasticsearch.Version; import org.elasticsearch.common.collect.Iterators; -import org.elasticsearch.common.logging.ESLoggerFactory; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.support.XContentMapValues; @@ -64,8 +62,6 @@ /** A {@link FieldMapper} for full-text fields. */ public class TextFieldMapper extends FieldMapper { - private static final Logger logger = ESLoggerFactory.getLogger(TextFieldMapper.class); - public static final String CONTENT_TYPE = "text"; private static final int POSITION_INCREMENT_GAP_USE_ANALYZER = -1; @@ -481,6 +477,7 @@ protected TextFieldType(TextFieldType ref) { } } + @Override public TextFieldType clone() { return new TextFieldType(this); } diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java b/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java index de4f0aab67696..9198582411fb3 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/AggregatorFactories.java @@ -159,10 +159,9 @@ public AggParseContext(String name) { } } - public static final AggregatorFactories EMPTY = new AggregatorFactories(null, new AggregatorFactory[0], + public static final AggregatorFactories EMPTY = new AggregatorFactories(new AggregatorFactory[0], new ArrayList()); - private AggregatorFactory parent; private AggregatorFactory[] factories; private List pipelineAggregatorFactories; @@ -170,9 +169,7 @@ public static Builder builder() { return new Builder(); } - private AggregatorFactories(AggregatorFactory parent, AggregatorFactory[] factories, - List pipelineAggregators) { - this.parent = parent; + private AggregatorFactories(AggregatorFactory[] factories, List pipelineAggregators) { this.factories = factories; this.pipelineAggregatorFactories = pipelineAggregators; } @@ -328,7 +325,7 @@ public AggregatorFactories build(SearchContext context, AggregatorFactory par for (int i = 0; i < aggregationBuilders.size(); i++) { aggFactories[i] = aggregationBuilders.get(i).build(context, parent); } - return new AggregatorFactories(parent, aggFactories, orderedpipelineAggregators); + return new AggregatorFactories(aggFactories, orderedpipelineAggregators); } private List resolvePipelineAggregatorOrder( diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeAggregationBuilder.java b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeAggregationBuilder.java index 2274b74a505e2..251dc7e428396 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeAggregationBuilder.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/CompositeAggregationBuilder.java @@ -144,6 +144,13 @@ public CompositeAggregationBuilder size(int size) { return this; } + /** + * @return the number of composite buckets. Defaults to {@code 10}. + */ + public int size() { + return size; + } + @Override protected AggregatorFactory doBuild(SearchContext context, AggregatorFactory parent, AggregatorFactories.Builder subfactoriesBuilder) throws IOException { diff --git a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/TopHitsAggregationBuilder.java b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/TopHitsAggregationBuilder.java index 38b783e6b9519..c2add245058b2 100644 --- a/server/src/main/java/org/elasticsearch/search/aggregations/metrics/TopHitsAggregationBuilder.java +++ b/server/src/main/java/org/elasticsearch/search/aggregations/metrics/TopHitsAggregationBuilder.java @@ -721,7 +721,6 @@ public static TopHitsAggregationBuilder parse(String aggregationName, XContentPa factory.storedFieldsContext = StoredFieldsContext.fromXContent(SearchSourceBuilder.STORED_FIELDS_FIELD.getPreferredName(), parser); } else if (SearchSourceBuilder.DOCVALUE_FIELDS_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { - List fieldDataFields = new ArrayList<>(); while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { FieldAndFormat ff = FieldAndFormat.fromXContent(parser); factory.docValueField(ff.field, ff.format); diff --git a/server/src/test/java/org/elasticsearch/action/admin/indices/create/SplitIndexIT.java b/server/src/test/java/org/elasticsearch/action/admin/indices/create/SplitIndexIT.java index 4510956358f05..c79d7f62c12c2 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/indices/create/SplitIndexIT.java +++ b/server/src/test/java/org/elasticsearch/action/admin/indices/create/SplitIndexIT.java @@ -485,8 +485,6 @@ public void testCreateSplitWithIndexSort() throws Exception { ImmutableOpenMap dataNodes = client().admin().cluster().prepareState().get().getState().nodes() .getDataNodes(); assertTrue("at least 2 nodes but was: " + dataNodes.size(), dataNodes.size() >= 2); - DiscoveryNode[] discoveryNodes = dataNodes.values().toArray(DiscoveryNode.class); - String mergeNode = discoveryNodes[0].getName(); // ensure all shards are allocated otherwise the ensure green below might not succeed since we require the merge node // if we change the setting too quickly we will end up with one replica unassigned which can't be assigned anymore due // to the require._name below. diff --git a/server/src/test/java/org/elasticsearch/action/admin/indices/mapping/get/GetMappingsResponseTests.java b/server/src/test/java/org/elasticsearch/action/admin/indices/mapping/get/GetMappingsResponseTests.java index 91c7841868393..beae91df77e3d 100644 --- a/server/src/test/java/org/elasticsearch/action/admin/indices/mapping/get/GetMappingsResponseTests.java +++ b/server/src/test/java/org/elasticsearch/action/admin/indices/mapping/get/GetMappingsResponseTests.java @@ -20,6 +20,7 @@ package org.elasticsearch.action.admin.indices.mapping.get; import com.carrotsearch.hppc.cursors.ObjectCursor; + import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.collect.ImmutableOpenMap; import org.elasticsearch.common.xcontent.XContentParser; @@ -119,20 +120,15 @@ protected GetMappingsResponse createTestInstance() { private static Map randomFieldMapping() { Map mappings = new HashMap<>(); if (randomBoolean()) { - Map regularMapping = new HashMap<>(); - regularMapping.put("type", randomBoolean() ? "text" : "keyword"); - regularMapping.put("index", "analyzed"); - regularMapping.put("analyzer", "english"); - return regularMapping; + mappings.put("type", randomBoolean() ? "text" : "keyword"); + mappings.put("index", "analyzed"); + mappings.put("analyzer", "english"); } else if (randomBoolean()) { - Map numberMapping = new HashMap<>(); - numberMapping.put("type", randomFrom("integer", "float", "long", "double")); - numberMapping.put("index", Objects.toString(randomBoolean())); - return numberMapping; + mappings.put("type", randomFrom("integer", "float", "long", "double")); + mappings.put("index", Objects.toString(randomBoolean())); } else if (randomBoolean()) { - Map objMapping = new HashMap<>(); - objMapping.put("type", "object"); - objMapping.put("dynamic", "strict"); + mappings.put("type", "object"); + mappings.put("dynamic", "strict"); Map properties = new HashMap<>(); Map props1 = new HashMap<>(); props1.put("type", randomFrom("text", "keyword")); @@ -146,12 +142,10 @@ private static Map randomFieldMapping() { props3.put("index", "false"); prop2properties.put("subsubfield", props3); props2.put("properties", prop2properties); - objMapping.put("properties", properties); - return objMapping; + mappings.put("properties", properties); } else { - Map plainMapping = new HashMap<>(); - plainMapping.put("type", "keyword"); - return plainMapping; + mappings.put("type", "keyword"); } + return mappings; } } diff --git a/server/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java b/server/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java index 52dc585cf7ac6..6c084cb29cd9c 100644 --- a/server/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/replication/TransportReplicationActionTests.java @@ -171,6 +171,7 @@ public void setUp() throws Exception { action = new TestAction(Settings.EMPTY, "internal:testAction", transportService, clusterService, shardStateAction, threadPool); } + @Override @After public void tearDown() throws Exception { super.tearDown(); @@ -511,6 +512,7 @@ action.new AsyncPrimaryAction(request, primaryShard.allocationId().getId(), prim ActionListener> actionListener, TransportReplicationAction.PrimaryShardReference primaryShardReference) { return new NoopReplicationOperation(request, actionListener) { + @Override public void execute() throws Exception { assertPhase(task, "primary"); assertFalse(executed.getAndSet(true)); @@ -567,6 +569,7 @@ action.new AsyncPrimaryAction(request, primaryShard.allocationId().getRelocation ActionListener> actionListener, TransportReplicationAction.PrimaryShardReference primaryShardReference) { return new NoopReplicationOperation(request, actionListener) { + @Override public void execute() throws Exception { assertPhase(task, "primary"); assertFalse(executed.getAndSet(true)); @@ -697,13 +700,6 @@ public void testSeqNoIsSetOnPrimary() throws Exception { return null; }).when(shard).acquirePrimaryOperationPermit(any(), anyString(), anyObject()); - AtomicBoolean closed = new AtomicBoolean(); - Releasable releasable = () -> { - if (closed.compareAndSet(false, true) == false) { - fail("releasable is closed twice"); - } - }; - TestAction action = new TestAction(Settings.EMPTY, "internal:testSeqNoIsSetOnPrimary", transportService, clusterService, shardStateAction, threadPool) { @@ -1112,8 +1108,6 @@ static class TestResponse extends ReplicationResponse { private class TestAction extends TransportReplicationAction { - private final boolean withDocumentFailureOnPrimary; - private final boolean withDocumentFailureOnReplica; TestAction(Settings settings, String actionName, TransportService transportService, ClusterService clusterService, ShardStateAction shardStateAction, @@ -1122,8 +1116,6 @@ private class TestAction extends TransportReplicationAction()), new IndexNameExpressionResolver(Settings.EMPTY), Request::new, Request::new, ThreadPool.Names.SAME); - this.withDocumentFailureOnPrimary = false; - this.withDocumentFailureOnReplica = false; } TestAction(Settings settings, String actionName, TransportService transportService, @@ -1133,8 +1125,6 @@ private class TestAction extends TransportReplicationAction()), new IndexNameExpressionResolver(Settings.EMPTY), Request::new, Request::new, ThreadPool.Names.SAME); - this.withDocumentFailureOnPrimary = withDocumentFailureOnPrimary; - this.withDocumentFailureOnReplica = withDocumentFailureOnReplica; } @Override @@ -1173,7 +1163,6 @@ final IndicesService mockIndicesService(ClusterService clusterService) { Index index = (Index) invocation.getArguments()[0]; final ClusterState state = clusterService.state(); if (state.metaData().hasIndex(index.getName())) { - final IndexMetaData indexSafe = state.metaData().getIndexSafe(index); return mockIndexService(clusterService.state().metaData().getIndexSafe(index), clusterService); } else { return null; diff --git a/server/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java b/server/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java index 18bbe5b9593de..1f1e9eb2a1e96 100644 --- a/server/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java +++ b/server/src/test/java/org/elasticsearch/action/support/replication/TransportWriteActionTests.java @@ -109,6 +109,7 @@ public void initCommonMocks() { clusterService = createClusterService(threadPool); } + @Override @After public void tearDown() throws Exception { super.tearDown(); @@ -430,7 +431,6 @@ final IndicesService mockIndicesService(ClusterService clusterService) { Index index = (Index) invocation.getArguments()[0]; final ClusterState state = clusterService.state(); if (state.metaData().hasIndex(index.getName())) { - final IndexMetaData indexSafe = state.metaData().getIndexSafe(index); return mockIndexService(clusterService.state().metaData().getIndexSafe(index), clusterService); } else { return null; diff --git a/server/src/test/java/org/elasticsearch/cluster/metadata/TemplateUpgradeServiceTests.java b/server/src/test/java/org/elasticsearch/cluster/metadata/TemplateUpgradeServiceTests.java index 776a0a158aeb4..f78f84958061d 100644 --- a/server/src/test/java/org/elasticsearch/cluster/metadata/TemplateUpgradeServiceTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/metadata/TemplateUpgradeServiceTests.java @@ -63,7 +63,6 @@ import static java.util.Collections.emptyMap; import static org.elasticsearch.test.ClusterServiceUtils.createClusterService; import static org.elasticsearch.test.ClusterServiceUtils.setState; -import static org.elasticsearch.test.VersionUtils.randomVersion; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.startsWith; import static org.hamcrest.Matchers.containsString; @@ -298,7 +297,7 @@ public void testClusterStateUpdate() throws InterruptedException { return null; }).when(mockIndicesAdminClient).deleteTemplate(any(DeleteIndexTemplateRequest.class), any(ActionListener.class)); - final TemplateUpgradeService service = new TemplateUpgradeService(Settings.EMPTY, mockClient, clusterService, threadPool, + new TemplateUpgradeService(Settings.EMPTY, mockClient, clusterService, threadPool, Arrays.asList( templates -> { assertNull(templates.put("added_test_template", IndexTemplateMetaData.builder("added_test_template") @@ -415,42 +414,6 @@ public void clusterChanged(ClusterChangedEvent event) { assertThat(finishInvocation.availablePermits(), equalTo(0)); } - private static final int NODE_TEST_ITERS = 100; - - private DiscoveryNodes randomNodes(int dataAndMasterNodes, int clientNodes) { - DiscoveryNodes.Builder builder = DiscoveryNodes.builder(); - String masterNodeId = null; - for (int i = 0; i < dataAndMasterNodes; i++) { - String id = randomAlphaOfLength(10) + "_" + i; - Set roles; - if (i == 0) { - masterNodeId = id; - // The first node has to be master node - if (randomBoolean()) { - roles = EnumSet.of(DiscoveryNode.Role.MASTER, DiscoveryNode.Role.DATA); - } else { - roles = EnumSet.of(DiscoveryNode.Role.MASTER); - } - } else { - if (randomBoolean()) { - roles = EnumSet.of(DiscoveryNode.Role.DATA); - } else { - roles = EnumSet.of(DiscoveryNode.Role.MASTER); - } - } - String node = "node_" + i; - builder.add(new DiscoveryNode(node, id, buildNewFakeTransportAddress(), emptyMap(), roles, randomVersion(random()))); - } - builder.masterNodeId(masterNodeId); // Node 0 is always a master node - - for (int i = 0; i < clientNodes; i++) { - String node = "client_" + i; - builder.add(new DiscoveryNode(node, randomAlphaOfLength(10) + "__" + i, buildNewFakeTransportAddress(), emptyMap(), - EnumSet.noneOf(DiscoveryNode.Role.class), randomVersion(random()))); - } - return builder.build(); - } - public static MetaData randomMetaData(IndexTemplateMetaData... templates) { MetaData.Builder builder = MetaData.builder(); for (IndexTemplateMetaData template : templates) { diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/OperationRoutingTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/OperationRoutingTests.java index 98c8dc1b2caff..de3223517b92f 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/OperationRoutingTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/OperationRoutingTests.java @@ -18,7 +18,6 @@ */ package org.elasticsearch.cluster.routing; -import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.Version; import org.elasticsearch.action.support.replication.ClusterStateCreationUtils; import org.elasticsearch.cluster.ClusterState; @@ -27,6 +26,7 @@ import org.elasticsearch.common.settings.ClusterSettings; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; +import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.index.Index; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.node.ResponseCollectorService; @@ -530,7 +530,6 @@ public void testAdaptiveReplicaSelection() throws Exception { indexNames[i] = "test" + i; } ClusterState state = ClusterStateCreationUtils.stateWithAssignedPrimariesAndReplicas(indexNames, numShards, numReplicas); - final int numRepeatedSearches = 4; OperationRouting opRouting = new OperationRouting(Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)); opRouting.setUseAdaptiveReplicaSelection(true); diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/FailedNodeRoutingTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/FailedNodeRoutingTests.java index d4645208071a3..fbdcadc6ec32f 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/FailedNodeRoutingTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/FailedNodeRoutingTests.java @@ -20,6 +20,7 @@ package org.elasticsearch.cluster.routing.allocation; import com.carrotsearch.hppc.cursors.ObjectCursor; + import org.apache.logging.log4j.Logger; import org.elasticsearch.Version; import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteRequest; @@ -149,8 +150,6 @@ public void testRandomClusterPromotesNewestReplica() throws InterruptedException assertTrue(state.metaData().hasIndex(name)); } - ClusterState previousState = state; - logger.info("--> starting shards"); state = cluster.applyStartedShards(state, state.getRoutingNodes().shardsWithState(INITIALIZING)); logger.info("--> starting replicas a random number of times"); diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java index 88766e7943ea9..711e7401ad217 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/NodeVersionAllocationDeciderTests.java @@ -91,10 +91,6 @@ public void testDoNotAllocateFromPrimary() { .put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(5).numberOfReplicas(2)) .build(); - RoutingTable routingTable = RoutingTable.builder() - .addAsNew(metaData.index("test")) - .build(); - RoutingTable initialRoutingTable = RoutingTable.builder() .addAsNew(metaData.index("test")) .build(); diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/RandomAllocationDeciderTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/RandomAllocationDeciderTests.java index d226af26f8157..ce26e41e053aa 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/RandomAllocationDeciderTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/RandomAllocationDeciderTests.java @@ -86,7 +86,6 @@ public void testRandomDecisions() { int nodeIdCounter = 0; int atMostNodes = scaledRandomIntBetween(Math.max(1, maxNumReplicas), 15); final boolean frequentNodes = randomBoolean(); - AllocationService.CommandsResult routingResult; for (int i = 0; i < numIters; i++) { logger.info("Start iteration [{}]", i); ClusterState.Builder stateBuilder = ClusterState.builder(clusterState); diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/SingleShardNoReplicasRoutingTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/SingleShardNoReplicasRoutingTests.java index 0668ba415249b..25d29d0fca482 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/SingleShardNoReplicasRoutingTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/SingleShardNoReplicasRoutingTests.java @@ -25,7 +25,6 @@ import org.elasticsearch.cluster.ESAllocationTestCase; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; -import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.RoutingNode; import org.elasticsearch.cluster.routing.RoutingNodes; @@ -35,9 +34,7 @@ import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.settings.Settings; -import java.util.ArrayList; import java.util.HashSet; -import java.util.List; import java.util.Set; import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING; @@ -238,7 +235,6 @@ public void testMultiIndexEvenDistribution() { logger.info("Adding " + (numberOfIndices / 2) + " nodes"); DiscoveryNodes.Builder nodesBuilder = DiscoveryNodes.builder(); - List nodes = new ArrayList<>(); for (int i = 0; i < (numberOfIndices / 2); i++) { nodesBuilder.add(newNode("node" + i)); } diff --git a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java index 58d19fb61cf05..d2e86c13d4f1c 100644 --- a/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java +++ b/server/src/test/java/org/elasticsearch/cluster/routing/allocation/decider/DiskThresholdDeciderTests.java @@ -666,7 +666,6 @@ public void testAverageUsage() { } public void testFreeDiskPercentageAfterShardAssigned() { - RoutingNode rn = new RoutingNode("node1", newNode("node1")); DiskThresholdDecider decider = makeDecider(Settings.EMPTY); Map usages = new HashMap<>(); diff --git a/server/src/test/java/org/elasticsearch/common/ExponentiallyWeightedMovingAverageTests.java b/server/src/test/java/org/elasticsearch/common/ExponentiallyWeightedMovingAverageTests.java index 9e50d0afd7182..9dc6faaa18365 100644 --- a/server/src/test/java/org/elasticsearch/common/ExponentiallyWeightedMovingAverageTests.java +++ b/server/src/test/java/org/elasticsearch/common/ExponentiallyWeightedMovingAverageTests.java @@ -23,7 +23,6 @@ import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.lessThan; -import static org.junit.Assert.assertThat; /** * Implements exponentially weighted moving averages (commonly abbreviated EWMA) for a single value. @@ -41,19 +40,11 @@ public void testEWMA() { } public void testInvalidAlpha() { - try { - ExponentiallyWeightedMovingAverage ewma = new ExponentiallyWeightedMovingAverage(-0.5, 10); - fail("should have failed to create EWMA"); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), equalTo("alpha must be greater or equal to 0 and less than or equal to 1")); - } + IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> new ExponentiallyWeightedMovingAverage(-0.5, 10)); + assertThat(ex.getMessage(), equalTo("alpha must be greater or equal to 0 and less than or equal to 1")); - try { - ExponentiallyWeightedMovingAverage ewma = new ExponentiallyWeightedMovingAverage(1.5, 10); - fail("should have failed to create EWMA"); - } catch (IllegalArgumentException e) { - assertThat(e.getMessage(), equalTo("alpha must be greater or equal to 0 and less than or equal to 1")); - } + ex = expectThrows(IllegalArgumentException.class, () -> new ExponentiallyWeightedMovingAverage(1.5, 10)); + assertThat(ex.getMessage(), equalTo("alpha must be greater or equal to 0 and less than or equal to 1")); } public void testConvergingToValue() { diff --git a/server/src/test/java/org/elasticsearch/common/settings/SettingsTests.java b/server/src/test/java/org/elasticsearch/common/settings/SettingsTests.java index d9cecdd604c88..70e958b974bf1 100644 --- a/server/src/test/java/org/elasticsearch/common/settings/SettingsTests.java +++ b/server/src/test/java/org/elasticsearch/common/settings/SettingsTests.java @@ -439,10 +439,7 @@ public void testEmptyFilterMap() { Settings filteredSettings = builder.build().filter((k) -> false); assertEquals(0, filteredSettings.size()); - for (String k : filteredSettings.keySet()) { - fail("no element"); - } assertFalse(filteredSettings.keySet().contains("a.c")); assertFalse(filteredSettings.keySet().contains("a")); assertFalse(filteredSettings.keySet().contains("a.b")); diff --git a/server/src/test/java/org/elasticsearch/common/util/concurrent/AsyncIOProcessorTests.java b/server/src/test/java/org/elasticsearch/common/util/concurrent/AsyncIOProcessorTests.java index 18351d1ea6b36..387f15e3f3319 100644 --- a/server/src/test/java/org/elasticsearch/common/util/concurrent/AsyncIOProcessorTests.java +++ b/server/src/test/java/org/elasticsearch/common/util/concurrent/AsyncIOProcessorTests.java @@ -39,7 +39,8 @@ public void testPut() throws InterruptedException { protected void write(List>> candidates) throws IOException { if (blockInternal) { synchronized (this) { - for (Tuple> c :candidates) { + // TODO: check why we need a loop, can't we just use received.addAndGet(candidates.size()) + for (int i = 0; i < candidates.size(); i++) { received.incrementAndGet(); } } diff --git a/server/src/test/java/org/elasticsearch/common/util/iterable/IterablesTests.java b/server/src/test/java/org/elasticsearch/common/util/iterable/IterablesTests.java index 4d9d89312a376..6501c7caa1d64 100644 --- a/server/src/test/java/org/elasticsearch/common/util/iterable/IterablesTests.java +++ b/server/src/test/java/org/elasticsearch/common/util/iterable/IterablesTests.java @@ -19,14 +19,14 @@ package org.elasticsearch.common.util.iterable; +import org.elasticsearch.test.ESTestCase; + import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; -import org.elasticsearch.test.ESTestCase; - import static org.hamcrest.object.HasToString.hasToString; public class IterablesTests extends ESTestCase { @@ -64,7 +64,7 @@ public void testFlatten() { Iterable allInts = Iterables.flatten(list); int count = 0; - for(int x : allInts) { + for(@SuppressWarnings("unused") int x : allInts) { count++; } assertEquals(0, count); @@ -73,14 +73,14 @@ public void testFlatten() { // changes to the outer list are not seen since flatten pre-caches outer list on init: count = 0; - for(int x : allInts) { + for(@SuppressWarnings("unused") int x : allInts) { count++; } assertEquals(0, count); // but changes to the original inner lists are seen: list.get(0).add(0); - for(int x : allInts) { + for(@SuppressWarnings("unused") int x : allInts) { count++; } assertEquals(1, count); diff --git a/server/src/test/java/org/elasticsearch/discovery/AbstractDisruptionTestCase.java b/server/src/test/java/org/elasticsearch/discovery/AbstractDisruptionTestCase.java index c0b01eb5ec518..fa023882df55f 100644 --- a/server/src/test/java/org/elasticsearch/discovery/AbstractDisruptionTestCase.java +++ b/server/src/test/java/org/elasticsearch/discovery/AbstractDisruptionTestCase.java @@ -87,6 +87,7 @@ protected int numberOfReplicas() { private boolean disableBeforeIndexDeletion; + @Override @Before public void setUp() throws Exception { super.setUp(); @@ -240,7 +241,6 @@ void assertMaster(String masterNode, List nodes) throws Exception { public ServiceDisruptionScheme addRandomDisruptionScheme() { // TODO: add partial partitions - NetworkDisruption p; final DisruptedLinks disruptedLinks; if (randomBoolean()) { disruptedLinks = TwoPartitions.random(random(), internalCluster().getNodeNames()); diff --git a/server/src/test/java/org/elasticsearch/discovery/ClusterDisruptionIT.java b/server/src/test/java/org/elasticsearch/discovery/ClusterDisruptionIT.java index fab38a2b73b4a..3b08eb6870e70 100644 --- a/server/src/test/java/org/elasticsearch/discovery/ClusterDisruptionIT.java +++ b/server/src/test/java/org/elasticsearch/discovery/ClusterDisruptionIT.java @@ -364,7 +364,7 @@ public void onFailure(Exception e) { public void testSearchWithRelocationAndSlowClusterStateProcessing() throws Exception { // don't use DEFAULT settings (which can cause node disconnects on a slow CI machine) configureCluster(Settings.EMPTY, 3, null, 1); - final String masterNode = internalCluster().startMasterOnlyNode(); + internalCluster().startMasterOnlyNode(); final String node_1 = internalCluster().startDataOnlyNode(); logger.info("--> creating index [test] with one shard and on replica"); diff --git a/server/src/test/java/org/elasticsearch/gateway/MetaDataStateFormatTests.java b/server/src/test/java/org/elasticsearch/gateway/MetaDataStateFormatTests.java index 0bf80e5239874..0351a10dea33b 100644 --- a/server/src/test/java/org/elasticsearch/gateway/MetaDataStateFormatTests.java +++ b/server/src/test/java/org/elasticsearch/gateway/MetaDataStateFormatTests.java @@ -103,7 +103,6 @@ public void testReadWriteState() throws IOException { final long id = addDummyFiles("foo-", dirs); Format format = new Format("foo-"); DummyState state = new DummyState(randomRealisticUnicodeOfCodepointLengthBetween(1, 1000), randomInt(), randomLong(), randomDouble(), randomBoolean()); - int version = between(0, Integer.MAX_VALUE/2); format.write(state, dirs); for (Path file : dirs) { Path[] list = content("*", file); @@ -117,7 +116,6 @@ public void testReadWriteState() throws IOException { DummyState read = format.read(NamedXContentRegistry.EMPTY, list[0]); assertThat(read, equalTo(state)); } - final int version2 = between(version, Integer.MAX_VALUE); DummyState state2 = new DummyState(randomRealisticUnicodeOfCodepointLengthBetween(1, 1000), randomInt(), randomLong(), randomDouble(), randomBoolean()); format.write(state2, dirs); @@ -145,7 +143,6 @@ public void testVersionMismatch() throws IOException { Format format = new Format("foo-"); DummyState state = new DummyState(randomRealisticUnicodeOfCodepointLengthBetween(1, 1000), randomInt(), randomLong(), randomDouble(), randomBoolean()); - int version = between(0, Integer.MAX_VALUE/2); format.write(state, dirs); for (Path file : dirs) { Path[] list = content("*", file); @@ -169,7 +166,6 @@ public void testCorruption() throws IOException { final long id = addDummyFiles("foo-", dirs); Format format = new Format("foo-"); DummyState state = new DummyState(randomRealisticUnicodeOfCodepointLengthBetween(1, 1000), randomInt(), randomLong(), randomDouble(), randomBoolean()); - int version = between(0, Integer.MAX_VALUE/2); format.write(state, dirs); for (Path file : dirs) { Path[] list = content("*", file); diff --git a/server/src/test/java/org/elasticsearch/index/cache/bitset/BitSetFilterCacheTests.java b/server/src/test/java/org/elasticsearch/index/cache/bitset/BitSetFilterCacheTests.java index 1f2526b2e2829..2c75437ee352e 100644 --- a/server/src/test/java/org/elasticsearch/index/cache/bitset/BitSetFilterCacheTests.java +++ b/server/src/test/java/org/elasticsearch/index/cache/bitset/BitSetFilterCacheTests.java @@ -30,7 +30,6 @@ import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.LogByteSizeMergePolicy; import org.apache.lucene.index.Term; -import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.MatchAllDocsQuery; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.join.BitSetProducer; @@ -38,9 +37,9 @@ import org.apache.lucene.store.RAMDirectory; import org.apache.lucene.util.Accountable; import org.apache.lucene.util.BitSet; -import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.common.lucene.index.ElasticsearchDirectoryReader; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.shard.ShardId; import org.elasticsearch.test.ESTestCase; @@ -89,7 +88,6 @@ public void testInvalidateEntries() throws Exception { DirectoryReader reader = DirectoryReader.open(writer); reader = ElasticsearchDirectoryReader.wrap(reader, new ShardId("test", "_na_", 0)); - IndexSearcher searcher = new IndexSearcher(reader); BitsetFilterCache cache = new BitsetFilterCache(INDEX_SETTINGS, new BitsetFilterCache.Listener() { @Override @@ -114,7 +112,6 @@ public void onRemoval(ShardId shardId, Accountable accountable) { reader.close(); reader = DirectoryReader.open(writer); reader = ElasticsearchDirectoryReader.wrap(reader, new ShardId("test", "_na_", 0)); - searcher = new IndexSearcher(reader); assertThat(matchCount(filter, reader), equalTo(3)); diff --git a/server/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java b/server/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java index e77203b83fee6..26c2453a27142 100644 --- a/server/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java +++ b/server/src/test/java/org/elasticsearch/index/engine/InternalEngineTests.java @@ -19,42 +19,9 @@ package org.elasticsearch.index.engine; -import java.io.Closeable; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Base64; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.concurrent.BrokenBarrierException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.LongSupplier; -import java.util.function.Supplier; -import java.util.function.ToLongBiFunction; -import java.util.stream.Collectors; -import java.util.stream.LongStream; - import com.carrotsearch.hppc.cursors.ObjectObjectCursor; import com.carrotsearch.randomizedtesting.generators.RandomNumbers; + import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; @@ -162,6 +129,40 @@ import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; +import java.io.Closeable; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.Charset; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.BrokenBarrierException; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.LongSupplier; +import java.util.function.Supplier; +import java.util.function.ToLongBiFunction; +import java.util.stream.Collectors; +import java.util.stream.LongStream; + import static java.util.Collections.emptyMap; import static java.util.Collections.shuffle; import static org.elasticsearch.index.engine.Engine.Operation.Origin.LOCAL_TRANSLOG_RECOVERY; @@ -2863,11 +2864,7 @@ public void testRecoverFromForeignTranslog() throws IOException { IndexSearcher.getDefaultQueryCachingPolicy(), translogConfig, TimeValue.timeValueMinutes(5), config.getExternalRefreshListener(), config.getInternalRefreshListener(), null, new NoneCircuitBreakerService(), () -> SequenceNumbers.UNASSIGNED_SEQ_NO, primaryTerm::get, tombstoneDocSupplier()); - try { - InternalEngine internalEngine = new InternalEngine(brokenConfig); - fail("translog belongs to a different engine"); - } catch (EngineCreationFailureException ex) { - } + expectThrows(EngineCreationFailureException.class, () -> new InternalEngine(brokenConfig)); engine = createEngine(store, primaryTranslogDir); // and recover again! assertVisibleCount(engine, numDocs, false); diff --git a/server/src/test/java/org/elasticsearch/index/mapper/MapperTests.java b/server/src/test/java/org/elasticsearch/index/mapper/MapperTests.java index 97a72d75e3a13..d2971034fd7ec 100644 --- a/server/src/test/java/org/elasticsearch/index/mapper/MapperTests.java +++ b/server/src/test/java/org/elasticsearch/index/mapper/MapperTests.java @@ -37,7 +37,7 @@ public void testSuccessfulBuilderContext() { } public void testBuilderContextWithIndexSettingsAsNull() { - NullPointerException e = expectThrows(NullPointerException.class, () -> new Mapper.BuilderContext(null, new ContentPath(1))); + expectThrows(NullPointerException.class, () -> new Mapper.BuilderContext(null, new ContentPath(1))); } } diff --git a/server/src/test/java/org/elasticsearch/index/mapper/TextFieldMapperTests.java b/server/src/test/java/org/elasticsearch/index/mapper/TextFieldMapperTests.java index 4736cbe471289..1211488e466c5 100644 --- a/server/src/test/java/org/elasticsearch/index/mapper/TextFieldMapperTests.java +++ b/server/src/test/java/org/elasticsearch/index/mapper/TextFieldMapperTests.java @@ -621,11 +621,6 @@ public void testEmptyName() throws IOException { } public void testIndexPrefixIndexTypes() throws IOException { - QueryShardContext queryShardContext = indexService.newQueryShardContext( - randomInt(20), null, () -> { - throw new UnsupportedOperationException(); - }, null); - { String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("type") .startObject("properties").startObject("field") diff --git a/server/src/test/java/org/elasticsearch/index/query/CommonTermsQueryBuilderTests.java b/server/src/test/java/org/elasticsearch/index/query/CommonTermsQueryBuilderTests.java index fe39345dadddd..5e443ec41ede9 100644 --- a/server/src/test/java/org/elasticsearch/index/query/CommonTermsQueryBuilderTests.java +++ b/server/src/test/java/org/elasticsearch/index/query/CommonTermsQueryBuilderTests.java @@ -179,7 +179,6 @@ public void testCommonTermsQuery3() throws IOException { public void testCommonTermsQuery4() throws IOException { Query parsedQuery = parseQuery(commonTermsQuery("field", "text")).toQuery(createShardContext()); assertThat(parsedQuery, instanceOf(ExtendedCommonTermsQuery.class)); - ExtendedCommonTermsQuery ectQuery = (ExtendedCommonTermsQuery) parsedQuery; } public void testParseFailsWithMultipleFields() throws IOException { diff --git a/server/src/test/java/org/elasticsearch/index/query/GeoBoundingBoxQueryBuilderTests.java b/server/src/test/java/org/elasticsearch/index/query/GeoBoundingBoxQueryBuilderTests.java index 551bd6488cd2f..74553c3be1f79 100644 --- a/server/src/test/java/org/elasticsearch/index/query/GeoBoundingBoxQueryBuilderTests.java +++ b/server/src/test/java/org/elasticsearch/index/query/GeoBoundingBoxQueryBuilderTests.java @@ -371,7 +371,8 @@ public void testParsingAndToQuery6() throws IOException { private void assertGeoBoundingBoxQuery(String query) throws IOException { QueryShardContext shardContext = createShardContext(); - Query parsedQuery = parseQuery(query).toQuery(shardContext); + // just check if we can parse the query + parseQuery(query).toQuery(shardContext); } public void testFromJson() throws IOException { diff --git a/server/src/test/java/org/elasticsearch/index/query/GeoDistanceQueryBuilderTests.java b/server/src/test/java/org/elasticsearch/index/query/GeoDistanceQueryBuilderTests.java index 0cb6a74570bfb..3a01125122460 100644 --- a/server/src/test/java/org/elasticsearch/index/query/GeoDistanceQueryBuilderTests.java +++ b/server/src/test/java/org/elasticsearch/index/query/GeoDistanceQueryBuilderTests.java @@ -298,9 +298,10 @@ public void testParsingAndToQuery12() throws IOException { assertGeoDistanceRangeQuery(query, 40, -70, 12, DistanceUnit.DEFAULT); } - private void assertGeoDistanceRangeQuery(String query, double lat, double lon, double distance, DistanceUnit distanceUnit) throws IOException { - Query parsedQuery = parseQuery(query).toQuery(createShardContext()); - // TODO: what can we check? + private void assertGeoDistanceRangeQuery(String query, double lat, double lon, double distance, DistanceUnit distanceUnit) + throws IOException { + parseQuery(query).toQuery(createShardContext()); + // TODO: what can we check? See https://github.com/elastic/elasticsearch/issues/34043 } public void testFromJson() throws IOException { diff --git a/server/src/test/java/org/elasticsearch/index/query/GeoPolygonQueryBuilderTests.java b/server/src/test/java/org/elasticsearch/index/query/GeoPolygonQueryBuilderTests.java index ee64e595e0845..8a9c98ef4a3fa 100644 --- a/server/src/test/java/org/elasticsearch/index/query/GeoPolygonQueryBuilderTests.java +++ b/server/src/test/java/org/elasticsearch/index/query/GeoPolygonQueryBuilderTests.java @@ -197,8 +197,8 @@ public void testParsingAndToQuery4() throws IOException { private void assertGeoPolygonQuery(String query) throws IOException { QueryShardContext context = createShardContext(); - Query parsedQuery = parseQuery(query).toQuery(context); - // todo LatLonPointInPolygon is package private, need a closeTo check on the query + parseQuery(query).toQuery(context); + // TODO LatLonPointInPolygon is package private, need a closeTo check on the query // since some points can be computed from the geohash } diff --git a/server/src/test/java/org/elasticsearch/index/query/functionscore/FunctionScoreTests.java b/server/src/test/java/org/elasticsearch/index/query/functionscore/FunctionScoreTests.java index a77d10f12eafa..8563d9883909f 100644 --- a/server/src/test/java/org/elasticsearch/index/query/functionscore/FunctionScoreTests.java +++ b/server/src/test/java/org/elasticsearch/index/query/functionscore/FunctionScoreTests.java @@ -34,10 +34,10 @@ import org.apache.lucene.search.Query; import org.apache.lucene.search.RandomApproximationQuery; import org.apache.lucene.search.Scorer; +import org.apache.lucene.search.SortField; import org.apache.lucene.search.TermQuery; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.Weight; -import org.apache.lucene.search.SortField; import org.apache.lucene.store.Directory; import org.apache.lucene.util.Accountable; import org.apache.lucene.util.BytesRef; @@ -46,6 +46,7 @@ import org.elasticsearch.common.lucene.search.function.CombineFunction; import org.elasticsearch.common.lucene.search.function.FieldValueFactorFunction; import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery; +import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery.FilterScoreFunction; import org.elasticsearch.common.lucene.search.function.FunctionScoreQuery.ScoreMode; import org.elasticsearch.common.lucene.search.function.LeafScoreFunction; import org.elasticsearch.common.lucene.search.function.RandomScoreFunction; @@ -71,7 +72,6 @@ import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; -import static org.elasticsearch.common.lucene.search.function.FunctionScoreQuery.FilterScoreFunction; public class FunctionScoreTests extends ESTestCase { @@ -709,13 +709,11 @@ public void testFilterFunctionScoreHashCodeAndEquals() { public void testExplanationAndScoreEqualsEvenIfNoFunctionMatches() throws IOException { IndexSearcher localSearcher = newSearcher(reader); - ScoreMode scoreMode = randomFrom(new - ScoreMode[]{ScoreMode.SUM, ScoreMode.AVG, ScoreMode.FIRST, ScoreMode.MIN, ScoreMode.MAX, ScoreMode.MULTIPLY}); CombineFunction combineFunction = randomFrom(new CombineFunction[]{CombineFunction.SUM, CombineFunction.AVG, CombineFunction.MIN, CombineFunction.MAX, CombineFunction.MULTIPLY, CombineFunction.REPLACE}); - // check for document that has no macthing function + // check for document that has no matching function FunctionScoreQuery query = new FunctionScoreQuery(new TermQuery(new Term(FIELD, "out")), new FilterScoreFunction(new TermQuery(new Term("_uid", "2")), new WeightFactorFunction(10)), combineFunction, Float.NEGATIVE_INFINITY, Float.MAX_VALUE); diff --git a/server/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java b/server/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java index 4d41e2b41b8b4..487ac7e0694ef 100644 --- a/server/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java +++ b/server/src/test/java/org/elasticsearch/index/shard/IndexShardTests.java @@ -485,7 +485,6 @@ public void testPrimaryFillsSeqNoGapsOnPromotion() throws Exception { final Result result = indexOnReplicaWithGaps(indexShard, operations, Math.toIntExact(SequenceNumbers.NO_OPS_PERFORMED)); final int maxSeqNo = result.maxSeqNo; - final boolean gap = result.gap; // promote the replica final ShardRouting replicaRouting = indexShard.routingEntry(); @@ -1780,7 +1779,7 @@ public void testPrimaryHandOffUpdatesLocalCheckpoint() throws IOException { public void testRecoverFromStoreWithNoOps() throws IOException { final IndexShard shard = newStartedShard(true); indexDoc(shard, "_doc", "0"); - Engine.IndexResult test = indexDoc(shard, "_doc", "1"); + indexDoc(shard, "_doc", "1"); // start a replica shard and index the second doc final IndexShard otherShard = newStartedShard(false); updateMappings(otherShard, shard.indexSettings().getIndexMetaData()); @@ -2877,12 +2876,10 @@ public void testReadSnapshotAndCheckIndexConcurrently() throws Exception { class Result { private final int localCheckpoint; private final int maxSeqNo; - private final boolean gap; - Result(final int localCheckpoint, final int maxSeqNo, final boolean gap) { + Result(final int localCheckpoint, final int maxSeqNo) { this.localCheckpoint = localCheckpoint; this.maxSeqNo = maxSeqNo; - this.gap = gap; } } @@ -2921,7 +2918,7 @@ private Result indexOnReplicaWithGaps( } assert localCheckpoint == indexShard.getLocalCheckpoint(); assert !gap || (localCheckpoint != max); - return new Result(localCheckpoint, max, gap); + return new Result(localCheckpoint, max); } /** A dummy repository for testing which just needs restore overridden */ diff --git a/server/src/test/java/org/elasticsearch/index/shard/StoreRecoveryTests.java b/server/src/test/java/org/elasticsearch/index/shard/StoreRecoveryTests.java index 8b606c82b1b20..7d63286c44ee9 100644 --- a/server/src/test/java/org/elasticsearch/index/shard/StoreRecoveryTests.java +++ b/server/src/test/java/org/elasticsearch/index/shard/StoreRecoveryTests.java @@ -39,11 +39,11 @@ import org.apache.lucene.store.IOContext; import org.apache.lucene.store.IndexOutput; import org.apache.lucene.util.BytesRef; -import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.Version; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.routing.OperationRouting; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.core.internal.io.IOUtils; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.mapper.IdFieldMapper; import org.elasticsearch.index.mapper.Uid; @@ -142,7 +142,6 @@ public void testSplitShard() throws IOException { } else { indexSort = null; } - int id = 0; IndexWriterConfig iwc = newIndexWriterConfig() .setMergePolicy(NoMergePolicy.INSTANCE) .setOpenMode(IndexWriterConfig.OpenMode.CREATE); diff --git a/server/src/test/java/org/elasticsearch/index/store/StoreTests.java b/server/src/test/java/org/elasticsearch/index/store/StoreTests.java index 584ce9b06421d..6546e6ebc8c61 100644 --- a/server/src/test/java/org/elasticsearch/index/store/StoreTests.java +++ b/server/src/test/java/org/elasticsearch/index/store/StoreTests.java @@ -364,10 +364,8 @@ public void testCheckIntegrity() throws IOException { } - final long luceneChecksum; try (IndexInput indexInput = dir.openInput("lucene_checksum.bin", IOContext.DEFAULT)) { assertEquals(luceneFileLength, indexInput.length()); - luceneChecksum = CodecUtil.retrieveChecksum(indexInput); } dir.close(); @@ -663,7 +661,6 @@ public void testCleanupFromSnapshot() throws IOException { if (randomBoolean()) { store.cleanupAndVerify("test", firstMeta); String[] strings = store.directory().listAll(); - int numChecksums = 0; int numNotFound = 0; for (String file : strings) { if (file.startsWith("extra")) { @@ -679,7 +676,6 @@ public void testCleanupFromSnapshot() throws IOException { } else { store.cleanupAndVerify("test", secondMeta); String[] strings = store.directory().listAll(); - int numChecksums = 0; int numNotFound = 0; for (String file : strings) { if (file.startsWith("extra")) { diff --git a/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java b/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java index 45bf7a700aa5d..9d18845a05e33 100644 --- a/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java +++ b/server/src/test/java/org/elasticsearch/index/translog/TranslogTests.java @@ -639,12 +639,8 @@ public void testSnapshotOnClosedTranslog() throws IOException { assertTrue(Files.exists(translogDir.resolve(Translog.getFilename(1)))); translog.add(new Translog.Index("test", "1", 0, primaryTerm.get(), new byte[]{1})); translog.close(); - try { - Translog.Snapshot snapshot = translog.newSnapshot(); - fail("translog is closed"); - } catch (AlreadyClosedException ex) { - assertEquals(ex.getMessage(), "translog is already closed"); - } + AlreadyClosedException ex = expectThrows(AlreadyClosedException.class, () -> translog.newSnapshot()); + assertEquals(ex.getMessage(), "translog is already closed"); } public void testSnapshotFromMinGen() throws Exception { @@ -845,7 +841,7 @@ public void testTranslogCorruption() throws Exception { try (Translog translog = openTranslog(config, uuid)) { try (Translog.Snapshot snapshot = translog.newSnapshot()) { - for (Location loc : locations) { + for (int i = 0; i < locations.size(); i++) { snapshot.next(); } } @@ -871,7 +867,7 @@ public void testTruncatedTranslogs() throws Exception { AtomicInteger truncations = new AtomicInteger(0); try (Translog.Snapshot snap = translog.newSnapshot()) { - for (Translog.Location location : locations) { + for (int i = 0; i < locations.size(); i++) { try { assertNotNull(snap.next()); } catch (EOFException e) { @@ -2378,6 +2374,7 @@ public int write(ByteBuffer src, long position) throws IOException { } + @Override public int write(ByteBuffer src) throws IOException { if (fail.fail()) { if (partialWrite) { @@ -2486,14 +2483,9 @@ public void testRecoverWithUnbackedNextGenInIllegalState() throws IOException { // don't copy the new file Files.createFile(config.getTranslogPath().resolve("translog-" + (read.generation + 1) + ".tlog")); - try { - Translog tlog = new Translog(config, translog.getTranslogUUID(), translog.getDeletionPolicy(), () -> SequenceNumbers.NO_OPS_PERFORMED, primaryTerm::get); - fail("file already exists?"); - } catch (TranslogException ex) { - // all is well - assertEquals(ex.getMessage(), "failed to create new translog file"); - assertEquals(ex.getCause().getClass(), FileAlreadyExistsException.class); - } + TranslogException ex = expectThrows(TranslogException.class, () -> new Translog(config, translog.getTranslogUUID(), translog.getDeletionPolicy(), () -> SequenceNumbers.NO_OPS_PERFORMED, primaryTerm::get)); + assertEquals(ex.getMessage(), "failed to create new translog file"); + assertEquals(ex.getCause().getClass(), FileAlreadyExistsException.class); } public void testRecoverWithUnbackedNextGenAndFutureFile() throws IOException { @@ -2521,14 +2513,10 @@ public void testRecoverWithUnbackedNextGenAndFutureFile() throws IOException { tlog.add(new Translog.Index("test", "" + 1, 1, primaryTerm.get(), Integer.toString(1).getBytes(Charset.forName("UTF-8")))); } - try { - Translog tlog = new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbers.NO_OPS_PERFORMED, primaryTerm::get); - fail("file already exists?"); - } catch (TranslogException ex) { - // all is well - assertEquals(ex.getMessage(), "failed to create new translog file"); - assertEquals(ex.getCause().getClass(), FileAlreadyExistsException.class); - } + TranslogException ex = expectThrows(TranslogException.class, + () -> new Translog(config, translogUUID, deletionPolicy, () -> SequenceNumbers.NO_OPS_PERFORMED, primaryTerm::get)); + assertEquals(ex.getMessage(), "failed to create new translog file"); + assertEquals(ex.getCause().getClass(), FileAlreadyExistsException.class); } /** diff --git a/server/src/test/java/org/elasticsearch/indices/IndexingMemoryControllerTests.java b/server/src/test/java/org/elasticsearch/indices/IndexingMemoryControllerTests.java index 01d7dc2a53558..e5a23b155e841 100644 --- a/server/src/test/java/org/elasticsearch/indices/IndexingMemoryControllerTests.java +++ b/server/src/test/java/org/elasticsearch/indices/IndexingMemoryControllerTests.java @@ -295,7 +295,6 @@ public void testThrottling() throws Exception { .put("indices.memory.index_buffer_size", "4mb").build()); IndexShard shard0 = test.getShard(0); IndexShard shard1 = test.getShard(1); - IndexShard shard2 = test.getShard(2); controller.simulateIndexing(shard0); controller.simulateIndexing(shard0); controller.simulateIndexing(shard0); diff --git a/server/src/test/java/org/elasticsearch/indices/cluster/AbstractIndicesClusterStateServiceTestCase.java b/server/src/test/java/org/elasticsearch/indices/cluster/AbstractIndicesClusterStateServiceTestCase.java index c68e4870aaeb0..e3c15ceda1d25 100644 --- a/server/src/test/java/org/elasticsearch/indices/cluster/AbstractIndicesClusterStateServiceTestCase.java +++ b/server/src/test/java/org/elasticsearch/indices/cluster/AbstractIndicesClusterStateServiceTestCase.java @@ -324,7 +324,6 @@ public Index index() { * Mock for {@link IndexShard} */ protected class MockIndexShard implements IndicesClusterStateService.Shard { - private volatile long clusterStateVersion; private volatile ShardRouting shardRouting; private volatile RecoveryState recoveryState; private volatile Set inSyncAllocationIds; @@ -372,7 +371,6 @@ public void updateShardState(ShardRouting shardRouting, this.shardRouting = shardRouting; if (shardRouting.primary()) { term = newPrimaryTerm; - this.clusterStateVersion = applyingClusterStateVersion; this.inSyncAllocationIds = inSyncAllocationIds; this.routingTable = routingTable; } diff --git a/server/src/test/java/org/elasticsearch/indices/mapping/UpdateMappingIntegrationIT.java b/server/src/test/java/org/elasticsearch/indices/mapping/UpdateMappingIntegrationIT.java index af9bf9910ec28..2e54490ed7884 100644 --- a/server/src/test/java/org/elasticsearch/indices/mapping/UpdateMappingIntegrationIT.java +++ b/server/src/test/java/org/elasticsearch/indices/mapping/UpdateMappingIntegrationIT.java @@ -74,7 +74,6 @@ public void testDynamicUpdates() throws Exception { client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet(); int recCount = randomIntBetween(200, 600); - int numberOfTypes = randomIntBetween(1, 5); List indexRequests = new ArrayList<>(); for (int rec = 0; rec < recCount; rec++) { String type = "type"; diff --git a/server/src/test/java/org/elasticsearch/indices/recovery/IndexRecoveryIT.java b/server/src/test/java/org/elasticsearch/indices/recovery/IndexRecoveryIT.java index 6a6970675eb9b..324b32fa6a940 100644 --- a/server/src/test/java/org/elasticsearch/indices/recovery/IndexRecoveryIT.java +++ b/server/src/test/java/org/elasticsearch/indices/recovery/IndexRecoveryIT.java @@ -57,7 +57,6 @@ import org.elasticsearch.test.ESIntegTestCase.Scope; import org.elasticsearch.test.InternalTestCluster; import org.elasticsearch.test.junit.annotations.TestLogging; -import org.elasticsearch.test.store.MockFSDirectoryService; import org.elasticsearch.test.store.MockFSIndexStore; import org.elasticsearch.test.transport.MockTransportService; import org.elasticsearch.test.transport.StubbableTransport; @@ -550,7 +549,6 @@ public void testDisconnectsWhileRecovering() throws Exception { final Settings nodeSettings = Settings.builder() .put(RecoverySettings.INDICES_RECOVERY_RETRY_DELAY_NETWORK_SETTING.getKey(), "100ms") .put(RecoverySettings.INDICES_RECOVERY_INTERNAL_ACTION_TIMEOUT_SETTING.getKey(), "1s") - .put(MockFSDirectoryService.RANDOM_PREVENT_DOUBLE_WRITE_SETTING.getKey(), false) // restarted recoveries will delete temp files and write them again .build(); // start a master node internalCluster().startNode(nodeSettings); diff --git a/server/src/test/java/org/elasticsearch/indices/store/IndicesStoreIntegrationIT.java b/server/src/test/java/org/elasticsearch/indices/store/IndicesStoreIntegrationIT.java index 7e99ccbbe6117..f9028a51a3c45 100644 --- a/server/src/test/java/org/elasticsearch/indices/store/IndicesStoreIntegrationIT.java +++ b/server/src/test/java/org/elasticsearch/indices/store/IndicesStoreIntegrationIT.java @@ -94,7 +94,7 @@ protected void ensureClusterStateConsistency() throws IOException { } public void testIndexCleanup() throws Exception { - final String masterNode = internalCluster().startNode(Settings.builder().put(Node.NODE_DATA_SETTING.getKey(), false)); + internalCluster().startNode(Settings.builder().put(Node.NODE_DATA_SETTING.getKey(), false)); final String node_1 = internalCluster().startNode(Settings.builder().put(Node.NODE_MASTER_SETTING.getKey(), false)); final String node_2 = internalCluster().startNode(Settings.builder().put(Node.NODE_MASTER_SETTING.getKey(), false)); logger.info("--> creating index [test] with one shard and on replica"); @@ -325,7 +325,7 @@ public void testShardsCleanup() throws Exception { } public void testShardActiveElsewhereDoesNotDeleteAnother() throws Exception { - final String masterNode = internalCluster().startMasterOnlyNode(); + internalCluster().startMasterOnlyNode(); final List nodes = internalCluster().startDataOnlyNodes(4); final String node1 = nodes.get(0); diff --git a/server/src/test/java/org/elasticsearch/persistent/PersistentTasksNodeServiceTests.java b/server/src/test/java/org/elasticsearch/persistent/PersistentTasksNodeServiceTests.java index 906ecf232053d..50bcf5949267e 100644 --- a/server/src/test/java/org/elasticsearch/persistent/PersistentTasksNodeServiceTests.java +++ b/server/src/test/java/org/elasticsearch/persistent/PersistentTasksNodeServiceTests.java @@ -31,16 +31,16 @@ import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.common.UUIDs; import org.elasticsearch.common.settings.Settings; +import org.elasticsearch.persistent.PersistentTasksCustomMetaData.Assignment; +import org.elasticsearch.persistent.PersistentTasksCustomMetaData.PersistentTask; +import org.elasticsearch.persistent.TestPersistentTasksPlugin.TestParams; +import org.elasticsearch.persistent.TestPersistentTasksPlugin.TestPersistentTasksExecutor; import org.elasticsearch.tasks.Task; import org.elasticsearch.tasks.TaskId; import org.elasticsearch.tasks.TaskManager; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.TestThreadPool; import org.elasticsearch.threadpool.ThreadPool; -import org.elasticsearch.persistent.PersistentTasksCustomMetaData.Assignment; -import org.elasticsearch.persistent.PersistentTasksCustomMetaData.PersistentTask; -import org.elasticsearch.persistent.TestPersistentTasksPlugin.TestParams; -import org.elasticsearch.persistent.TestPersistentTasksPlugin.TestPersistentTasksExecutor; import org.junit.After; import org.junit.Before; @@ -334,13 +334,11 @@ private class Execution { private final PersistentTaskParams params; private final AllocatedPersistentTask task; private final PersistentTaskState state; - private final PersistentTasksExecutor holder; - Execution(PersistentTaskParams params, AllocatedPersistentTask task, PersistentTaskState state, PersistentTasksExecutor holder) { + Execution(PersistentTaskParams params, AllocatedPersistentTask task, PersistentTaskState state) { this.params = params; this.task = task; this.state = state; - this.holder = holder; } } @@ -356,7 +354,7 @@ public void executeTask(final Params param final PersistentTaskState state, final AllocatedPersistentTask task, final PersistentTasksExecutor executor) { - executions.add(new Execution(params, task, state, executor)); + executions.add(new Execution(params, task, state)); } public Execution get(int i) { diff --git a/server/src/test/java/org/elasticsearch/recovery/FullRollingRestartIT.java b/server/src/test/java/org/elasticsearch/recovery/FullRollingRestartIT.java index 50035e1027b66..6624d4eb8ded4 100644 --- a/server/src/test/java/org/elasticsearch/recovery/FullRollingRestartIT.java +++ b/server/src/test/java/org/elasticsearch/recovery/FullRollingRestartIT.java @@ -148,7 +148,7 @@ public void testNoRebalanceOnRollingRestart() throws Exception { } internalCluster().restartRandomDataNode(); ensureGreen(); - ClusterState afterState = client().admin().cluster().prepareState().get().getState(); + client().admin().cluster().prepareState().get().getState(); recoveryResponse = client().admin().indices().prepareRecoveries("test").get(); for (RecoveryState recoveryState : recoveryResponse.shardRecoveryStates().get("test")) { diff --git a/server/src/test/java/org/elasticsearch/repositories/RepositoriesServiceIT.java b/server/src/test/java/org/elasticsearch/repositories/RepositoriesServiceIT.java index 05c9746aa49ac..28537022e3f33 100644 --- a/server/src/test/java/org/elasticsearch/repositories/RepositoriesServiceIT.java +++ b/server/src/test/java/org/elasticsearch/repositories/RepositoriesServiceIT.java @@ -54,7 +54,6 @@ public void testUpdateRepository() { final Client client = client(); final RepositoriesService repositoriesService = cluster.getDataOrMasterNodeInstances(RepositoriesService.class).iterator().next(); - final Settings settings = cluster.getDefaultSettings(); final Settings.Builder repoSettings = Settings.builder().put("location", randomRepoPath()); diff --git a/server/src/test/java/org/elasticsearch/rest/RestControllerTests.java b/server/src/test/java/org/elasticsearch/rest/RestControllerTests.java index cbf554289711e..d35a8b5d24955 100644 --- a/server/src/test/java/org/elasticsearch/rest/RestControllerTests.java +++ b/server/src/test/java/org/elasticsearch/rest/RestControllerTests.java @@ -212,7 +212,6 @@ public void testRestHandlerWrapper() throws Exception { }; final RestController restController = new RestController(Settings.EMPTY, Collections.emptySet(), wrapper, null, circuitBreakerService, usageService); - final ThreadContext threadContext = new ThreadContext(Settings.EMPTY); restController.dispatchRequest(new FakeRestRequest.Builder(xContentRegistry()).build(), null, null, Optional.of(handler)); assertTrue(wrapperCalled.get()); assertFalse(handlerCalled.get()); diff --git a/server/src/test/java/org/elasticsearch/rest/RestHttpResponseHeadersTests.java b/server/src/test/java/org/elasticsearch/rest/RestHttpResponseHeadersTests.java index ebe8ae00ac0f3..e5e8bce6d6da1 100644 --- a/server/src/test/java/org/elasticsearch/rest/RestHttpResponseHeadersTests.java +++ b/server/src/test/java/org/elasticsearch/rest/RestHttpResponseHeadersTests.java @@ -40,7 +40,6 @@ import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.is; -import static org.mockito.Mockito.mock; public class RestHttpResponseHeadersTests extends ESTestCase { @@ -114,7 +113,6 @@ public void handleRequest(RestRequest request, RestChannel channel, NodeClient c // Send the request and verify the response status code FakeRestChannel restChannel = new FakeRestChannel(restRequest, false, 1); - NodeClient client = mock(NodeClient.class); restController.dispatchRequest(restRequest, restChannel, new ThreadContext(Settings.EMPTY)); assertThat(restChannel.capturedResponse().status().getStatus(), is(405)); diff --git a/server/src/test/java/org/elasticsearch/script/StoredScriptSourceTests.java b/server/src/test/java/org/elasticsearch/script/StoredScriptSourceTests.java index 79d5c67bc782e..d628561e2c613 100644 --- a/server/src/test/java/org/elasticsearch/script/StoredScriptSourceTests.java +++ b/server/src/test/java/org/elasticsearch/script/StoredScriptSourceTests.java @@ -35,7 +35,6 @@ public class StoredScriptSourceTests extends AbstractSerializingTestCase testSearchCase(query, timestamps, + expectThrows(TooManyBucketsException.class, () -> testSearchCase(query, timestamps, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.seconds(5)).field(DATE_FIELD), histogram -> {}, 2)); - exc = expectThrows(TooManyBucketsException.class, () -> testSearchAndReduceCase(query, timestamps, + expectThrows(TooManyBucketsException.class, () -> testSearchAndReduceCase(query, timestamps, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.seconds(5)).field(DATE_FIELD), histogram -> {}, 2)); - exc = expectThrows(TooManyBucketsException.class, () -> testSearchAndReduceCase(query, timestamps, + expectThrows(TooManyBucketsException.class, () -> testSearchAndReduceCase(query, timestamps, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.seconds(5)).field(DATE_FIELD).minDocCount(0L), histogram -> {}, 100)); - exc = expectThrows(TooManyBucketsException.class, () -> testSearchAndReduceCase(query, timestamps, + expectThrows(TooManyBucketsException.class, () -> testSearchAndReduceCase(query, timestamps, aggregation -> aggregation.dateHistogramInterval(DateHistogramInterval.seconds(5)) .field(DATE_FIELD) diff --git a/server/src/test/java/org/elasticsearch/search/aggregations/pipeline/ExtendedStatsBucketIT.java b/server/src/test/java/org/elasticsearch/search/aggregations/pipeline/ExtendedStatsBucketIT.java index 40c3bfb500e4d..e1aa1dfce3f9e 100644 --- a/server/src/test/java/org/elasticsearch/search/aggregations/pipeline/ExtendedStatsBucketIT.java +++ b/server/src/test/java/org/elasticsearch/search/aggregations/pipeline/ExtendedStatsBucketIT.java @@ -439,8 +439,7 @@ public void testNoBuckets() throws Exception { } public void testBadSigmaAsSubAgg() throws Exception { - try { - SearchResponse response = client() + Exception ex = expectThrows(Exception.class, () -> client() .prepareSearch("idx") .addAggregation( terms("terms") @@ -451,21 +450,18 @@ public void testBadSigmaAsSubAgg() throws Exception { .extendedBounds(minRandomValue, maxRandomValue) .subAggregation(sum("sum").field(SINGLE_VALUED_FIELD_NAME))) .subAggregation(extendedStatsBucket("extended_stats_bucket", "histo>sum") - .sigma(-1.0))).execute().actionGet(); - fail("Illegal sigma was provided but no exception was thrown."); - } catch (Exception e) { - Throwable cause = ExceptionsHelper.unwrapCause(e); - if (cause == null) { - throw e; - } else if (cause instanceof SearchPhaseExecutionException) { - SearchPhaseExecutionException spee = (SearchPhaseExecutionException) e; - Throwable rootCause = spee.getRootCause(); - if (!(rootCause instanceof IllegalArgumentException)) { - throw e; - } - } else if (!(cause instanceof IllegalArgumentException)) { - throw e; + .sigma(-1.0))).execute().actionGet()); + Throwable cause = ExceptionsHelper.unwrapCause(ex); + if (cause == null) { + throw ex; + } else if (cause instanceof SearchPhaseExecutionException) { + SearchPhaseExecutionException spee = (SearchPhaseExecutionException) ex; + Throwable rootCause = spee.getRootCause(); + if (!(rootCause instanceof IllegalArgumentException)) { + throw ex; } + } else if (!(cause instanceof IllegalArgumentException)) { + throw ex; } } diff --git a/server/src/test/java/org/elasticsearch/search/aggregations/pipeline/moving/avg/MovAvgIT.java b/server/src/test/java/org/elasticsearch/search/aggregations/pipeline/moving/avg/MovAvgIT.java index d14f93b7a5189..49c700548f946 100644 --- a/server/src/test/java/org/elasticsearch/search/aggregations/pipeline/moving/avg/MovAvgIT.java +++ b/server/src/test/java/org/elasticsearch/search/aggregations/pipeline/moving/avg/MovAvgIT.java @@ -24,6 +24,7 @@ import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.WriteRequest; +import org.elasticsearch.client.Client; import org.elasticsearch.common.collect.EvictingQueue; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket; @@ -411,7 +412,7 @@ public void testSimpleSingleValuedField() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts","_count") .window(windowSize) @@ -459,7 +460,7 @@ public void testLinearSingleValuedField() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) @@ -507,7 +508,7 @@ public void testEwmaSingleValuedField() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) @@ -555,7 +556,7 @@ public void testHoltSingleValuedField() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) @@ -604,7 +605,7 @@ public void testHoltWintersValuedField() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) @@ -708,7 +709,7 @@ public void testSizeZeroWindow() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(0) @@ -746,7 +747,7 @@ public void testNegativeWindow() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "_count") .window(-10) @@ -810,7 +811,7 @@ public void testZeroPrediction() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) @@ -831,7 +832,7 @@ public void testNegativePrediction() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(randomMetric("the_metric", VALUE_FIELD)) .subAggregation(movingAvg("movavg_counts", "the_metric") .window(windowSize) @@ -847,12 +848,11 @@ public void testNegativePrediction() { } public void testHoltWintersNotEnoughData() { - try { - SearchResponse response = client() - .prepareSearch("idx").setTypes("type") + Client client = client(); + expectThrows(SearchPhaseExecutionException.class, () -> client.prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(10) @@ -864,11 +864,7 @@ public void testHoltWintersNotEnoughData() { .modelBuilder(new HoltWintersModel.HoltWintersModelBuilder() .alpha(alpha).beta(beta).gamma(gamma).period(20).seasonalityType(seasonalityType)) .gapPolicy(gapPolicy)) - ).execute().actionGet(); - } catch (SearchPhaseExecutionException e) { - // All good - } - + ).execute().actionGet()); } public void testTwoMovAvgsWithPredictions() { @@ -982,23 +978,19 @@ public void testTwoMovAvgsWithPredictions() { } } + @AwaitsFix(bugUrl="https://github.com/elastic/elasticsearch/issues/34046") public void testBadModelParams() { - try { - SearchResponse response = client() + expectThrows(SearchPhaseExecutionException.class, () -> client() .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(10) .modelBuilder(randomModelBuilder(100)) .gapPolicy(gapPolicy)) - ).execute().actionGet(); - } catch (SearchPhaseExecutionException e) { - // All good - } - + ).execute().actionGet()); } public void testHoltWintersMinimization() { @@ -1006,7 +998,7 @@ public void testHoltWintersMinimization() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(windowSize) @@ -1092,7 +1084,7 @@ public void testMinimizeNotEnoughData() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) @@ -1146,7 +1138,7 @@ public void testCheckIfNonTunableCanBeMinimized() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) @@ -1164,7 +1156,7 @@ public void testCheckIfNonTunableCanBeMinimized() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) @@ -1194,7 +1186,7 @@ public void testCheckIfTunableCanBeMinimized() { .prepareSearch("idx").setTypes("type") .addAggregation( histogram("histo").field(INTERVAL_FIELD).interval(interval) - .extendedBounds(0L, (long) (interval * (numBuckets - 1))) + .extendedBounds(0L, interval * (numBuckets - 1)) .subAggregation(metric) .subAggregation(movingAvg("movavg_counts", "_count") .window(numBuckets) diff --git a/server/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java b/server/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java index dedd0f036641b..607133ea8f287 100644 --- a/server/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java +++ b/server/src/test/java/org/elasticsearch/search/morelikethis/MoreLikeThisIT.java @@ -23,7 +23,6 @@ import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchResponse; -import org.elasticsearch.client.Client; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.elasticsearch.common.Strings; import org.elasticsearch.common.settings.Settings; @@ -213,7 +212,6 @@ public void testMoreLikeThisWithAliasesInLikeDocuments() throws Exception { } public void testMoreLikeThisIssue2197() throws Exception { - Client client = client(); String mapping = Strings.toString(XContentFactory.jsonBuilder().startObject().startObject("bar") .startObject("properties") .endObject() diff --git a/server/src/test/java/org/elasticsearch/search/query/SearchQueryIT.java b/server/src/test/java/org/elasticsearch/search/query/SearchQueryIT.java index 860c3e074f3df..a861cc76655e5 100644 --- a/server/src/test/java/org/elasticsearch/search/query/SearchQueryIT.java +++ b/server/src/test/java/org/elasticsearch/search/query/SearchQueryIT.java @@ -1744,7 +1744,7 @@ public void testRangeQueryWithTimeZone() throws Exception { assertThat(searchResponse.getHits().getAt(0).getId(), is("3")); // When we use long values, it means we have ms since epoch UTC based so we don't apply any transformation - Exception e = expectThrows(SearchPhaseExecutionException.class, () -> + expectThrows(SearchPhaseExecutionException.class, () -> client().prepareSearch("test") .setQuery(QueryBuilders.rangeQuery("date").from(1388534400000L).to(1388537940999L).timeZone("+01:00")) .get()); diff --git a/server/src/test/java/org/elasticsearch/search/rescore/QueryRescorerBuilderTests.java b/server/src/test/java/org/elasticsearch/search/rescore/QueryRescorerBuilderTests.java index 700b3949facf4..24621a12d39e4 100644 --- a/server/src/test/java/org/elasticsearch/search/rescore/QueryRescorerBuilderTests.java +++ b/server/src/test/java/org/elasticsearch/search/rescore/QueryRescorerBuilderTests.java @@ -201,12 +201,10 @@ public MappedFieldType fieldMapper(String name) { rescoreBuilder.setRescoreQueryWeight(randomFloat()); rescoreBuilder.setScoreMode(QueryRescoreMode.Max); - QueryRescoreContext rescoreContext = (QueryRescoreContext) rescoreBuilder.buildContext(mockShardContext); QueryRescorerBuilder rescoreRewritten = rescoreBuilder.rewrite(mockShardContext); assertEquals(rescoreRewritten.getQueryWeight(), rescoreBuilder.getQueryWeight(), 0.01f); assertEquals(rescoreRewritten.getRescoreQueryWeight(), rescoreBuilder.getRescoreQueryWeight(), 0.01f); assertEquals(rescoreRewritten.getScoreMode(), rescoreBuilder.getScoreMode()); - } /** diff --git a/server/src/test/java/org/elasticsearch/search/suggest/SuggestSearchIT.java b/server/src/test/java/org/elasticsearch/search/suggest/SuggestSearchIT.java index 995a2c10fe555..98ed6a4a59858 100644 --- a/server/src/test/java/org/elasticsearch/search/suggest/SuggestSearchIT.java +++ b/server/src/test/java/org/elasticsearch/search/suggest/SuggestSearchIT.java @@ -972,11 +972,8 @@ public void testSuggestWithManyCandidates() throws InterruptedException, Executi assertSuggestionSize(searchSuggest, 0, 25480, "title"); // Just to prove that we've run through a ton of options suggest.size(1); - long start = System.currentTimeMillis(); searchSuggest = searchSuggest("united states house of representatives elections in washington 2006", "title", suggest); - long total = System.currentTimeMillis() - start; assertSuggestion(searchSuggest, 0, 0, "title", "united states house of representatives elections in washington 2006"); - // assertThat(total, lessThan(1000L)); // Takes many seconds without fix - just for debugging } public void testSuggestWithFieldAlias() throws Exception { @@ -1168,7 +1165,7 @@ public void testPhraseSuggesterCollate() throws InterruptedException, ExecutionE .endObject() .endObject()); - PhraseSuggestionBuilder in = suggest.collateQuery(filterStr); + suggest.collateQuery(filterStr); try { searchSuggest("united states house of representatives elections in washington 2006", numShards.numPrimaries, namedSuggestion); fail("Post filter error has been swallowed"); @@ -1186,7 +1183,6 @@ public void testPhraseSuggesterCollate() throws InterruptedException, ExecutionE .endObject()); - PhraseSuggestionBuilder phraseSuggestWithNoParams = suggest.collateQuery(collateWithParams); try { searchSuggest("united states house of representatives elections in washington 2006", numShards.numPrimaries, namedSuggestion); fail("Malformed query (lack of additional params) should fail"); diff --git a/server/src/test/java/org/elasticsearch/search/suggest/completion/CompletionSuggesterBuilderTests.java b/server/src/test/java/org/elasticsearch/search/suggest/completion/CompletionSuggesterBuilderTests.java index 88e6ce6466622..f7423d3f55a93 100644 --- a/server/src/test/java/org/elasticsearch/search/suggest/completion/CompletionSuggesterBuilderTests.java +++ b/server/src/test/java/org/elasticsearch/search/suggest/completion/CompletionSuggesterBuilderTests.java @@ -45,7 +45,6 @@ public class CompletionSuggesterBuilderTests extends AbstractSuggestionBuilderTestCase { private static final String[] SHUFFLE_PROTECTED_FIELDS = new String[] { CompletionSuggestionBuilder.CONTEXTS_FIELD.getPreferredName() }; - private static final Map> contextMap = new HashMap<>(); private static String categoryContextName; private static String geoQueryContextName; private static List> contextMappings = new ArrayList<>(); diff --git a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java index 632a1ecbee1ae..8e907fe8a1aa4 100644 --- a/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java +++ b/server/src/test/java/org/elasticsearch/snapshots/SharedClusterSnapshotRestoreIT.java @@ -2819,7 +2819,7 @@ public void testRestoreSnapshotWithCorruptedIndexMetadata() throws Exception { Predicate isRestorableIndex = index -> corruptedIndex.getName().equals(index) == false; - RestoreSnapshotResponse restoreSnapshotResponse = client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap") + client().admin().cluster().prepareRestoreSnapshot("test-repo", "test-snap") .setIndices(nbDocsPerIndex.keySet().stream().filter(isRestorableIndex).toArray(String[]::new)) .setRestoreGlobalState(randomBoolean()) .setWaitForCompletion(true) diff --git a/server/src/test/java/org/elasticsearch/threadpool/SimpleThreadPoolIT.java b/server/src/test/java/org/elasticsearch/threadpool/SimpleThreadPoolIT.java index cec5f9b1be28f..5f286a5ff0ad4 100644 --- a/server/src/test/java/org/elasticsearch/threadpool/SimpleThreadPoolIT.java +++ b/server/src/test/java/org/elasticsearch/threadpool/SimpleThreadPoolIT.java @@ -55,7 +55,7 @@ public void testThreadNames() throws Exception { } } logger.info("pre node threads are {}", preNodeStartThreadNames); - String node = internalCluster().startNode(); + internalCluster().startNode(); logger.info("do some indexing, flushing, optimize, and searches"); int numDocs = randomIntBetween(2, 100); IndexRequestBuilder[] builders = new IndexRequestBuilder[numDocs]; diff --git a/server/src/test/java/org/elasticsearch/threadpool/UpdateThreadPoolSettingsTests.java b/server/src/test/java/org/elasticsearch/threadpool/UpdateThreadPoolSettingsTests.java index ea281f7d9ae1e..c004ed9b3bcc8 100644 --- a/server/src/test/java/org/elasticsearch/threadpool/UpdateThreadPoolSettingsTests.java +++ b/server/src/test/java/org/elasticsearch/threadpool/UpdateThreadPoolSettingsTests.java @@ -61,7 +61,6 @@ public void testCorrectThreadPoolTypePermittedInSettings() throws InterruptedExc } public void testWriteThreadPoolsMaxSize() throws InterruptedException { - final String name = Names.WRITE; final int maxSize = 1 + EsExecutors.numberOfProcessors(Settings.EMPTY); final int tooBig = randomIntBetween(1 + maxSize, Integer.MAX_VALUE); diff --git a/server/src/test/java/org/elasticsearch/transport/TcpTransportTests.java b/server/src/test/java/org/elasticsearch/transport/TcpTransportTests.java index bc7ef0fd5d222..c6fb1f406cf53 100644 --- a/server/src/test/java/org/elasticsearch/transport/TcpTransportTests.java +++ b/server/src/test/java/org/elasticsearch/transport/TcpTransportTests.java @@ -223,6 +223,7 @@ public NodeChannels openConnection(DiscoveryNode node, ConnectionProfile connect StreamInput streamIn = reference.streamInput(); streamIn.skip(TcpHeader.MARKER_BYTES_SIZE); + @SuppressWarnings("unused") int len = streamIn.readInt(); long requestId = streamIn.readLong(); assertEquals(42, requestId); diff --git a/server/src/test/java/org/elasticsearch/update/UpdateIT.java b/server/src/test/java/org/elasticsearch/update/UpdateIT.java index 85ebf01ef28c0..70489e5c1ded6 100644 --- a/server/src/test/java/org/elasticsearch/update/UpdateIT.java +++ b/server/src/test/java/org/elasticsearch/update/UpdateIT.java @@ -19,19 +19,6 @@ package org.elasticsearch.update; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; - import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.ActionRequestValidationException; @@ -56,6 +43,19 @@ import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.InternalSettingsPlugin; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; + import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows; @@ -586,15 +586,13 @@ public void testStressUpdateDeleteConcurrency() throws Exception { final class UpdateThread extends Thread { final Map failedMap = new HashMap<>(); final int numberOfIds; - final int updatesPerId; final int maxUpdateRequests = numberOfIdsPerThread*numberOfUpdatesPerId; final int maxDeleteRequests = numberOfIdsPerThread*numberOfUpdatesPerId; private final Semaphore updateRequestsOutstanding = new Semaphore(maxUpdateRequests); private final Semaphore deleteRequestsOutstanding = new Semaphore(maxDeleteRequests); - UpdateThread(int numberOfIds, int updatesPerId) { + UpdateThread(int numberOfIds) { this.numberOfIds = numberOfIds; - this.updatesPerId = updatesPerId; } final class UpdateListener implements ActionListener { @@ -725,7 +723,7 @@ private void waitForOutstandingRequests(TimeValue timeOut, Semaphore requestsOut final List threads = new ArrayList<>(); for (int i = 0; i < numberOfThreads; i++) { - UpdateThread ut = new UpdateThread(numberOfIdsPerThread, numberOfUpdatesPerId); + UpdateThread ut = new UpdateThread(numberOfIdsPerThread); ut.start(); threads.add(ut); } @@ -749,7 +747,7 @@ private void waitForOutstandingRequests(TimeValue timeOut, Semaphore requestsOut //This means that we add 1 to the expected versions and attempts //All the previous operations should be complete or failed at this point for (int i = 0; i < numberOfIdsPerThread; ++i) { - UpdateResponse ur = client().prepareUpdate("test", "type1", Integer.toString(i)) + client().prepareUpdate("test", "type1", Integer.toString(i)) .setScript(fieldIncScript) .setRetryOnConflict(Integer.MAX_VALUE) .setUpsert(jsonBuilder().startObject().field("field", 1).endObject()) diff --git a/server/src/test/java/org/elasticsearch/versioning/SimpleVersioningIT.java b/server/src/test/java/org/elasticsearch/versioning/SimpleVersioningIT.java index 588118db4aef3..e8d9dd0fc2cc9 100644 --- a/server/src/test/java/org/elasticsearch/versioning/SimpleVersioningIT.java +++ b/server/src/test/java/org/elasticsearch/versioning/SimpleVersioningIT.java @@ -20,8 +20,8 @@ import org.apache.lucene.util.TestUtil; import org.elasticsearch.action.ActionResponse; -import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.DocWriteRequest; +import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.action.delete.DeleteResponse; import org.elasticsearch.action.index.IndexResponse; @@ -358,7 +358,6 @@ public String next() { // zero-pad sequential logger.info("--> use zero-padded sequential ids"); ids = new IDSource() { - final int radix = TestUtil.nextInt(random, Character.MIN_RADIX, Character.MAX_RADIX); final String zeroPad = String.format(Locale.ROOT, "%0" + TestUtil.nextInt(random, 4, 20) + "d", 0); int upto; @@ -374,7 +373,6 @@ public String next() { logger.info("--> use random long ids"); ids = new IDSource() { final int radix = TestUtil.nextInt(random, Character.MIN_RADIX, Character.MAX_RADIX); - int upto; @Override public String next() { @@ -387,8 +385,6 @@ public String next() { logger.info("--> use zero-padded random long ids"); ids = new IDSource() { final int radix = TestUtil.nextInt(random, Character.MIN_RADIX, Character.MAX_RADIX); - final String zeroPad = String.format(Locale.ROOT, "%015d", 0); - int upto; @Override public String next() { diff --git a/test/framework/src/main/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java b/test/framework/src/main/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java index 42eab104d6a33..8914bad5c4102 100644 --- a/test/framework/src/main/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/index/mapper/FieldTypeTestCase.java @@ -21,9 +21,6 @@ import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.search.Query; import org.apache.lucene.search.similarities.BM25Similarity; -import org.elasticsearch.Version; -import org.elasticsearch.cluster.metadata.IndexMetaData; -import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.analysis.AnalyzerScope; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.index.query.QueryShardContext; @@ -37,8 +34,6 @@ /** Base test case for subclasses of MappedFieldType */ public abstract class FieldTypeTestCase extends ESTestCase { - private static final Settings INDEX_SETTINGS = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build(); - /** Abstraction for mutating a property of a MappedFieldType */ public abstract static class Modifier { /** The name of the property that is being modified. Used in test failure messages. */ diff --git a/test/framework/src/main/java/org/elasticsearch/repositories/ESBlobStoreContainerTestCase.java b/test/framework/src/main/java/org/elasticsearch/repositories/ESBlobStoreContainerTestCase.java index 9f12c36999145..3e4e639dd01e3 100644 --- a/test/framework/src/main/java/org/elasticsearch/repositories/ESBlobStoreContainerTestCase.java +++ b/test/framework/src/main/java/org/elasticsearch/repositories/ESBlobStoreContainerTestCase.java @@ -103,7 +103,7 @@ public void testList() throws IOException { int length = randomIntBetween(10, 100); String name = "bar-0-"; generatedBlobs.put(name, (long) length); - byte[] data = writeRandomBlob(container, name, length); + writeRandomBlob(container, name, length); Map blobs = container.listBlobs(); assertThat(blobs.size(), equalTo(numberOfFooBlobs + numberOfBarBlobs)); diff --git a/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java b/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java index 69142dba63871..794c7fef783ce 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java +++ b/test/framework/src/main/java/org/elasticsearch/test/InternalTestCluster.java @@ -24,6 +24,7 @@ import com.carrotsearch.randomizedtesting.generators.RandomNumbers; import com.carrotsearch.randomizedtesting.generators.RandomPicks; import com.carrotsearch.randomizedtesting.generators.RandomStrings; + import org.apache.logging.log4j.Logger; import org.apache.lucene.store.AlreadyClosedException; import org.elasticsearch.ElasticsearchException; @@ -165,10 +166,6 @@ public final class InternalTestCluster extends TestCluster { private final Logger logger = Loggers.getLogger(getClass()); - - private static final AtomicInteger clusterOrdinal = new AtomicInteger(); - - public static final int DEFAULT_LOW_NUM_MASTER_NODES = 1; public static final int DEFAULT_HIGH_NUM_MASTER_NODES = 3; @@ -317,7 +314,6 @@ public InternalTestCluster( this.mockPlugins = mockPlugins; - sharedNodesSeeds = new long[numSharedDedicatedMasterNodes + numSharedDataNodes + numSharedCoordOnlyNodes]; for (int i = 0; i < sharedNodesSeeds.length; i++) { sharedNodesSeeds[i] = random.nextLong(); @@ -2062,6 +2058,7 @@ synchronized String routingKeyForShard(Index index, int shard, Random random) { return null; } + @Override public synchronized Iterable getClients() { ensureOpen(); return () -> { diff --git a/test/framework/src/main/java/org/elasticsearch/test/store/MockFSDirectoryService.java b/test/framework/src/main/java/org/elasticsearch/test/store/MockFSDirectoryService.java index 98eb0b10502b0..cdc33b38b8676 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/store/MockFSDirectoryService.java +++ b/test/framework/src/main/java/org/elasticsearch/test/store/MockFSDirectoryService.java @@ -21,6 +21,7 @@ import com.carrotsearch.randomizedtesting.SeedUtils; import com.carrotsearch.randomizedtesting.generators.RandomPicks; + import org.apache.logging.log4j.Logger; import org.apache.lucene.index.CheckIndex; import org.apache.lucene.store.BaseDirectoryWrapper; @@ -62,10 +63,6 @@ public class MockFSDirectoryService extends FsDirectoryService { Setting.doubleSetting("index.store.mock.random.io_exception_rate_on_open", 0.0d, 0.0d, Property.IndexScope, Property.NodeScope); public static final Setting RANDOM_IO_EXCEPTION_RATE_SETTING = Setting.doubleSetting("index.store.mock.random.io_exception_rate", 0.0d, 0.0d, Property.IndexScope, Property.NodeScope); - public static final Setting RANDOM_PREVENT_DOUBLE_WRITE_SETTING = - Setting.boolSetting("index.store.mock.random.prevent_double_write", true, Property.IndexScope, Property.NodeScope); - public static final Setting RANDOM_NO_DELETE_OPEN_FILE_SETTING = - Setting.boolSetting("index.store.mock.random.no_delete_open_file", true, Property.IndexScope, Property.NodeScope); public static final Setting CRASH_INDEX_SETTING = Setting.boolSetting("index.store.mock.random.crash_index", true, Property.IndexScope, Property.NodeScope); @@ -74,8 +71,6 @@ public class MockFSDirectoryService extends FsDirectoryService { private final double randomIOExceptionRate; private final double randomIOExceptionRateOnOpen; private final MockDirectoryWrapper.Throttling throttle; - private final boolean preventDoubleWrite; - private final boolean noDeleteOpenFile; private final boolean crashIndex; @Inject @@ -87,9 +82,6 @@ public MockFSDirectoryService(IndexSettings idxSettings, IndexStore indexStore, randomIOExceptionRate = RANDOM_IO_EXCEPTION_RATE_SETTING.get(indexSettings); randomIOExceptionRateOnOpen = RANDOM_IO_EXCEPTION_RATE_ON_OPEN_SETTING.get(indexSettings); - preventDoubleWrite = RANDOM_PREVENT_DOUBLE_WRITE_SETTING.get(indexSettings); - noDeleteOpenFile = RANDOM_NO_DELETE_OPEN_FILE_SETTING.exists(indexSettings) ? - RANDOM_NO_DELETE_OPEN_FILE_SETTING.get(indexSettings) : random.nextBoolean(); random.nextInt(shardId.getId() + 1); // some randomness per shard throttle = MockDirectoryWrapper.Throttling.NEVER; crashIndex = CRASH_INDEX_SETTING.get(indexSettings); diff --git a/test/framework/src/main/java/org/elasticsearch/test/store/MockFSIndexStore.java b/test/framework/src/main/java/org/elasticsearch/test/store/MockFSIndexStore.java index 3b876f3c3832c..82ab9fc412144 100644 --- a/test/framework/src/main/java/org/elasticsearch/test/store/MockFSIndexStore.java +++ b/test/framework/src/main/java/org/elasticsearch/test/store/MockFSIndexStore.java @@ -61,8 +61,6 @@ public List> getSettings() { return Arrays.asList(INDEX_CHECK_INDEX_ON_CLOSE_SETTING, MockFSDirectoryService.CRASH_INDEX_SETTING, MockFSDirectoryService.RANDOM_IO_EXCEPTION_RATE_SETTING, - MockFSDirectoryService.RANDOM_PREVENT_DOUBLE_WRITE_SETTING, - MockFSDirectoryService.RANDOM_NO_DELETE_OPEN_FILE_SETTING, MockFSDirectoryService.RANDOM_IO_EXCEPTION_RATE_ON_OPEN_SETTING); } @@ -86,6 +84,7 @@ public void onIndexModule(IndexModule indexModule) { super(indexSettings); } + @Override public DirectoryService newDirectoryService(ShardPath path) { return new MockFSDirectoryService(indexSettings, this, path); } diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/license/LicenseVerifier.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/license/LicenseVerifier.java index a879dc9ed1807..918067e676692 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/license/LicenseVerifier.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/license/LicenseVerifier.java @@ -43,6 +43,7 @@ public static boolean verifyLicense(final License license, byte[] publicKeyData) try { byte[] signatureBytes = Base64.getDecoder().decode(license.signature()); ByteBuffer byteBuffer = ByteBuffer.wrap(signatureBytes); + @SuppressWarnings("unused") int version = byteBuffer.getInt(); int magicLen = byteBuffer.getInt(); byte[] magic = new byte[magicLen]; diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java index 57bc360d64e41..d4ccc22d32ab4 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/scheduler/Cron.java @@ -254,7 +254,6 @@ public class Cron implements ToXContentFragment { private transient boolean lastdayOfMonth = false; private transient boolean nearestWeekday = false; private transient int lastdayOffset = 0; - private transient boolean expressionParsed = false; public static final int MAX_YEAR = Calendar.getInstance(UTC, Locale.ROOT).get(Calendar.YEAR) + 100; @@ -802,7 +801,6 @@ public static void validate(String expression) throws IllegalArgumentException { //////////////////////////////////////////////////////////////////////////// private void buildExpression(String expression) { - expressionParsed = true; try { @@ -1214,32 +1212,6 @@ private static String expressionSetSummary(java.util.Set set) { return buf.toString(); } - private static String expressionSetSummary(java.util.ArrayList list) { - - if (list.contains(NO_SPEC)) { - return "?"; - } - if (list.contains(ALL_SPEC)) { - return "*"; - } - - StringBuilder buf = new StringBuilder(); - - Iterator itr = list.iterator(); - boolean first = true; - while (itr.hasNext()) { - Integer iVal = itr.next(); - String val = iVal.toString(); - if (!first) { - buf.append(","); - } - buf.append(val); - first = false; - } - - return buf.toString(); - } - private static int skipWhiteSpace(int i, String s) { for (; i < s.length() && (s.charAt(i) == ' ' || s.charAt(i) == '\t'); i++) { ; diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/FieldPermissions.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/FieldPermissions.java index 144d2877463b8..53d6c328f5d08 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/FieldPermissions.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/FieldPermissions.java @@ -23,7 +23,6 @@ import java.io.IOException; import java.util.Arrays; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @@ -44,7 +43,6 @@ public final class FieldPermissions implements Accountable { private static final long BASE_FIELD_PERM_DEF_BYTES = RamUsageEstimator.shallowSizeOf(new FieldPermissionsDefinition(null, null)); private static final long BASE_FIELD_GROUP_BYTES = RamUsageEstimator.shallowSizeOf(new FieldGrantExcludeGroup(null, null)); - private static final long BASE_HASHSET_SIZE = RamUsageEstimator.shallowSizeOfInstance(HashSet.class); private static final long BASE_HASHSET_ENTRY_SIZE; static { HashMap map = new HashMap<>(); diff --git a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/client/WatchSourceBuilder.java b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/client/WatchSourceBuilder.java index b82e9b641095c..001a430ddb1e6 100644 --- a/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/client/WatchSourceBuilder.java +++ b/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/client/WatchSourceBuilder.java @@ -185,7 +185,6 @@ public final BytesReference buildAsBytes(XContentType contentType) { static class TransformedAction implements ToXContentObject { - private final String id; private final Action action; @Nullable private final TimeValue throttlePeriod; @Nullable private final Condition condition; @@ -193,7 +192,6 @@ static class TransformedAction implements ToXContentObject { TransformedAction(String id, Action action, @Nullable TimeValue throttlePeriod, @Nullable Condition condition, @Nullable Transform transform) { - this.id = id; this.throttlePeriod = throttlePeriod; this.condition = condition; this.transform = transform; diff --git a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/PostCalendarEventActionRequestTests.java b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/PostCalendarEventActionRequestTests.java index ce6a64be6c572..af94c180a1f78 100644 --- a/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/PostCalendarEventActionRequestTests.java +++ b/x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/PostCalendarEventActionRequestTests.java @@ -10,7 +10,6 @@ import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.test.AbstractStreamableTestCase; -import org.elasticsearch.xpack.core.ml.action.PostCalendarEventsAction; import org.elasticsearch.xpack.core.ml.calendars.ScheduledEvent; import org.elasticsearch.xpack.core.ml.calendars.ScheduledEventTests; @@ -63,7 +62,6 @@ public void testParseRequest() throws IOException { public void testParseRequest_throwsIfCalendarIdsAreDifferent() throws IOException { PostCalendarEventsAction.Request sourceRequest = createTestInstance("foo"); - PostCalendarEventsAction.Request request = new PostCalendarEventsAction.Request("bar", sourceRequest.getScheduledEvents()); StringBuilder requestString = new StringBuilder(); requestString.append("{\"events\": ["); diff --git a/x-pack/plugin/graph/src/test/java/org/elasticsearch/xpack/graph/test/GraphTests.java b/x-pack/plugin/graph/src/test/java/org/elasticsearch/xpack/graph/test/GraphTests.java index a58d8e8a8b0c6..611bf74fbf48e 100644 --- a/x-pack/plugin/graph/src/test/java/org/elasticsearch/xpack/graph/test/GraphTests.java +++ b/x-pack/plugin/graph/src/test/java/org/elasticsearch/xpack/graph/test/GraphTests.java @@ -27,9 +27,9 @@ import org.elasticsearch.script.ScriptType; import org.elasticsearch.test.ESSingleNodeTestCase; import org.elasticsearch.xpack.core.XPackPlugin; -import org.elasticsearch.xpack.graph.Graph; import org.elasticsearch.xpack.core.graph.action.GraphExploreAction; import org.elasticsearch.xpack.core.graph.action.GraphExploreRequestBuilder; +import org.elasticsearch.xpack.graph.Graph; import java.util.Collection; import java.util.Collections; @@ -46,7 +46,7 @@ public class GraphTests extends ESSingleNodeTestCase { - + static class DocTemplate { int numDocs; String[] people; @@ -61,20 +61,20 @@ static class DocTemplate { this.people = people; } } - + static final DocTemplate[] socialNetTemplate = { new DocTemplate(10, "60s", "beatles", "john", "paul", "george", "ringo"), - new DocTemplate(2, "60s", "collaboration", "ravi", "george"), - new DocTemplate(3, "80s", "travelling wilburys", "roy", "george", "jeff"), - new DocTemplate(5, "80s", "travelling wilburys", "roy", "jeff", "bob"), - new DocTemplate(1, "70s", "collaboration", "roy", "elvis"), - new DocTemplate(10, "90s", "nirvana", "dave", "kurt"), - new DocTemplate(2, "00s", "collaboration", "dave", "paul"), - new DocTemplate(2, "80s", "collaboration", "stevie", "paul"), - new DocTemplate(2, "70s", "collaboration", "john", "yoko"), + new DocTemplate(2, "60s", "collaboration", "ravi", "george"), + new DocTemplate(3, "80s", "travelling wilburys", "roy", "george", "jeff"), + new DocTemplate(5, "80s", "travelling wilburys", "roy", "jeff", "bob"), + new DocTemplate(1, "70s", "collaboration", "roy", "elvis"), + new DocTemplate(10, "90s", "nirvana", "dave", "kurt"), + new DocTemplate(2, "00s", "collaboration", "dave", "paul"), + new DocTemplate(2, "80s", "collaboration", "stevie", "paul"), + new DocTemplate(2, "70s", "collaboration", "john", "yoko"), new DocTemplate(100, "70s", "fillerDoc", "other", "irrelevant", "duplicated", "spammy", "background") - }; + }; @Override public void setUp() throws Exception { @@ -112,7 +112,7 @@ public void setUp() throws Exception { assertEquals(1, shardSegments.getSegments().size()); } } - + assertHitCount(client().prepareSearch().setQuery(matchAllQuery()).get(), numDocs); } @@ -126,7 +126,7 @@ public void testSignificanceQueryCrawl() { Hop hop1 = grb.createNextHop(QueryBuilders.termQuery("description", "beatles")); hop1.addVertexRequest("people").size(10).minDocCount(1); // members of beatles grb.createNextHop(null).addVertexRequest("people").size(100).minDocCount(1); // friends of members of beatles - + GraphExploreResponse response = grb.get(); checkVertexDepth(response, 0, "john", "paul", "george", "ringo"); @@ -135,8 +135,8 @@ public void testSignificanceQueryCrawl() { checkVertexIsMoreImportant(response, "John's only collaboration is more relevant than George's with profligate Roy", "yoko", "roy"); assertNull("Elvis is a 3rd tier connection so should not be returned here", response.getVertex(Vertex.createId("people","elvis"))); } - - + + @Override protected Settings nodeSettings() { // Disable security otherwise authentication failures happen creating indices. @@ -155,7 +155,7 @@ public void testTargetedQueryCrawl() { Hop hop1 = grb.createNextHop(QueryBuilders.termQuery("description", "beatles")); hop1.addVertexRequest("people").size(10).minDocCount(1); // members of beatles //70s friends of beatles - grb.createNextHop(QueryBuilders.termQuery("decade", "70s")).addVertexRequest("people").size(100).minDocCount(1); + grb.createNextHop(QueryBuilders.termQuery("decade", "70s")).addVertexRequest("people").size(100).minDocCount(1); GraphExploreResponse response = grb.get(); @@ -163,37 +163,37 @@ public void testTargetedQueryCrawl() { checkVertexDepth(response, 1, "yoko"); assertNull("Roy collaborated with George in the 80s not the 70s", response.getVertex(Vertex.createId("people","roy"))); assertNull("Stevie collaborated with Paul in the 80s not the 70s", response.getVertex(Vertex.createId("people","stevie"))); - + } - - + + public void testLargeNumberTermsStartCrawl() { GraphExploreRequestBuilder grb = new GraphExploreRequestBuilder(client(), GraphExploreAction.INSTANCE).setIndices("test"); Hop hop1 = grb.createNextHop(null); - VertexRequest peopleNames = hop1.addVertexRequest("people").minDocCount(1); + VertexRequest peopleNames = hop1.addVertexRequest("people").minDocCount(1); peopleNames.addInclude("john", 1); - + for (int i = 0; i < BooleanQuery.getMaxClauseCount()+1; i++) { - peopleNames.addInclude("unknown"+i, 1); + peopleNames.addInclude("unknown"+i, 1); } - + grb.createNextHop(null).addVertexRequest("people").size(100).minDocCount(1); // friends of members of beatles - + GraphExploreResponse response = grb.get(); checkVertexDepth(response, 0, "john"); checkVertexDepth(response, 1, "yoko"); - } + } public void testTargetedQueryCrawlDepth2() { GraphExploreRequestBuilder grb = new GraphExploreRequestBuilder(client(), GraphExploreAction.INSTANCE).setIndices("test"); Hop hop1 = grb.createNextHop(QueryBuilders.termQuery("description", "beatles")); hop1.addVertexRequest("people").size(10).minDocCount(1); // members of beatles //00s friends of beatles - grb.createNextHop(QueryBuilders.termQuery("decade", "00s")).addVertexRequest("people").size(100).minDocCount(1); + grb.createNextHop(QueryBuilders.termQuery("decade", "00s")).addVertexRequest("people").size(100).minDocCount(1); //90s friends of friends of beatles - grb.createNextHop(QueryBuilders.termQuery("decade", "90s")).addVertexRequest("people").size(100).minDocCount(1); + grb.createNextHop(QueryBuilders.termQuery("decade", "90s")).addVertexRequest("people").size(100).minDocCount(1); GraphExploreResponse response = grb.get(); @@ -201,9 +201,9 @@ public void testTargetedQueryCrawlDepth2() { checkVertexDepth(response, 0, "john", "paul", "george", "ringo"); checkVertexDepth(response, 1, "dave"); checkVertexDepth(response, 2, "kurt"); - + } - + public void testPopularityQueryCrawl() { GraphExploreRequestBuilder grb = new GraphExploreRequestBuilder(client(), GraphExploreAction.INSTANCE).setIndices("test"); // Turning off the significance feature means we reward popularity @@ -211,7 +211,7 @@ public void testPopularityQueryCrawl() { Hop hop1 = grb.createNextHop(QueryBuilders.termQuery("description", "beatles")); hop1.addVertexRequest("people").size(10).minDocCount(1); // members of beatles grb.createNextHop(null).addVertexRequest("people").size(100).minDocCount(1); // friends of members of beatles - + GraphExploreResponse response = grb.get(); checkVertexDepth(response, 0, "john", "paul", "george", "ringo"); @@ -219,15 +219,15 @@ public void testPopularityQueryCrawl() { checkVertexIsMoreImportant(response, "Yoko has more collaborations than Stevie", "yoko", "stevie"); checkVertexIsMoreImportant(response, "Roy has more collaborations than Stevie", "roy", "stevie"); assertNull("Elvis is a 3rd tier connection so should not be returned here", response.getVertex(Vertex.createId("people","elvis"))); - } - + } + public void testTimedoutQueryCrawl() { GraphExploreRequestBuilder grb = new GraphExploreRequestBuilder(client(), GraphExploreAction.INSTANCE).setIndices("test"); grb.setTimeout(TimeValue.timeValueMillis(400)); Hop hop1 = grb.createNextHop(QueryBuilders.termQuery("description", "beatles")); hop1.addVertexRequest("people").size(10).minDocCount(1); // members of beatles //00s friends of beatles - grb.createNextHop(QueryBuilders.termQuery("decade", "00s")).addVertexRequest("people").size(100).minDocCount(1); + grb.createNextHop(QueryBuilders.termQuery("decade", "00s")).addVertexRequest("people").size(100).minDocCount(1); // A query that should cause a timeout ScriptQueryBuilder timeoutQuery = QueryBuilders.scriptQuery(new Script(ScriptType.INLINE, "mockscript", "graph_timeout", Collections.emptyMap())); @@ -237,13 +237,13 @@ public void testTimedoutQueryCrawl() { assertTrue(response.isTimedOut()); checkVertexDepth(response, 0, "john", "paul", "george", "ringo"); - - // Most of the test runs we reach dave in the allotted time before we hit our + + // Most of the test runs we reach dave in the allotted time before we hit our // intended delay but sometimes this doesn't happen so I commented this line out. - - // checkVertexDepth(response, 1, "dave"); + + // checkVertexDepth(response, 1, "dave"); } - + public void testNonDiversifiedCrawl() { GraphExploreRequestBuilder grb = new GraphExploreRequestBuilder(client(), GraphExploreAction.INSTANCE).setIndices("test"); @@ -289,14 +289,14 @@ public void testInvalidDiversifiedCrawl() { String message = expectedError.toString(); assertTrue(message.contains("Sample diversifying key must be a single valued-field")); } - + public void testMappedAndUnmappedQueryCrawl() { GraphExploreRequestBuilder grb = new GraphExploreRequestBuilder(client(), GraphExploreAction.INSTANCE) .setIndices("test", "idx_unmapped"); Hop hop1 = grb.createNextHop(QueryBuilders.termQuery("description", "beatles")); hop1.addVertexRequest("people").size(10).minDocCount(1); // members of beatles grb.createNextHop(null).addVertexRequest("people").size(100).minDocCount(1); // friends of members of beatles - + GraphExploreResponse response = grb.get(); checkVertexDepth(response, 0, "john", "paul", "george", "ringo"); @@ -304,13 +304,13 @@ public void testMappedAndUnmappedQueryCrawl() { checkVertexIsMoreImportant(response, "John's only collaboration is more relevant than one of Paul's many", "yoko", "stevie"); checkVertexIsMoreImportant(response, "John's only collaboration is more relevant than George's with profligate Roy", "yoko", "roy"); assertNull("Elvis is a 3rd tier connection so should not be returned here", response.getVertex(Vertex.createId("people","elvis"))); - } - + } + public void testUnmappedQueryCrawl() { GraphExploreRequestBuilder grb = new GraphExploreRequestBuilder(client(), GraphExploreAction.INSTANCE).setIndices("idx_unmapped"); Hop hop1 = grb.createNextHop(QueryBuilders.termQuery("description", "beatles")); hop1.addVertexRequest("people").size(10).minDocCount(1); - + GraphExploreResponse response = grb.get(); assertEquals(0, response.getConnections().size()); assertEquals(0, response.getVertices().size()); @@ -327,7 +327,7 @@ public void testRequestValidation() { assertTrue(rte.getMessage().contains(GraphExploreRequest.NO_HOPS_ERROR_MESSAGE)); } - Hop hop = grb.createNextHop(null); + grb.createNextHop(null); try { grb.get(); diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/DataCountsReporter.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/DataCountsReporter.java index a00c14078eb95..5d7d84c14ce67 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/DataCountsReporter.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/process/DataCountsReporter.java @@ -11,7 +11,6 @@ import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; -import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.xpack.core.ml.job.config.Job; import org.elasticsearch.xpack.core.ml.job.process.autodetect.state.DataCounts; import org.elasticsearch.xpack.ml.job.persistence.JobDataCountsPersister; @@ -66,8 +65,6 @@ public class DataCountsReporter extends AbstractComponent { Property.Dynamic, Property.NodeScope); - private static final TimeValue PERSIST_INTERVAL = TimeValue.timeValueMillis(10_000L); - private final Job job; private final JobDataCountsPersister dataCountsPersister; diff --git a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/modelsnapshots/RestGetModelSnapshotsAction.java b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/modelsnapshots/RestGetModelSnapshotsAction.java index ceeb55442e5dd..5b4895f6bbbfe 100644 --- a/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/modelsnapshots/RestGetModelSnapshotsAction.java +++ b/x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/modelsnapshots/RestGetModelSnapshotsAction.java @@ -12,11 +12,11 @@ import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.action.RestToXContentListener; -import org.elasticsearch.xpack.ml.MachineLearning; import org.elasticsearch.xpack.core.ml.action.GetModelSnapshotsAction; import org.elasticsearch.xpack.core.ml.action.GetModelSnapshotsAction.Request; import org.elasticsearch.xpack.core.ml.action.util.PageParams; import org.elasticsearch.xpack.core.ml.job.config.Job; +import org.elasticsearch.xpack.ml.MachineLearning; import java.io.IOException; @@ -30,7 +30,6 @@ public class RestGetModelSnapshotsAction extends BaseRestHandler { private final String DEFAULT_SORT = null; private final String DEFAULT_START = null; private final String DEFAULT_END = null; - private final String DEFAULT_DESCRIPTION = null; private final boolean DEFAULT_DESC_ORDER = true; public RestGetModelSnapshotsAction(Settings settings, RestController controller) { diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationDataExtractorTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationDataExtractorTests.java index 903ab4af1157f..93bdc1258905d 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationDataExtractorTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/AggregationDataExtractorTests.java @@ -17,6 +17,7 @@ import org.elasticsearch.search.aggregations.AggregatorFactories; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.test.ESTestCase; +import org.elasticsearch.xpack.ml.datafeed.extractor.aggregation.AggregationTestUtils.Term; import org.junit.Before; import java.io.BufferedReader; @@ -33,7 +34,6 @@ import java.util.Set; import java.util.stream.Collectors; -import static org.elasticsearch.xpack.ml.datafeed.extractor.aggregation.AggregationTestUtils.Term; import static org.elasticsearch.xpack.ml.datafeed.extractor.aggregation.AggregationTestUtils.createHistogramBucket; import static org.elasticsearch.xpack.ml.datafeed.extractor.aggregation.AggregationTestUtils.createMax; import static org.elasticsearch.xpack.ml.datafeed.extractor.aggregation.AggregationTestUtils.createTerms; @@ -254,7 +254,7 @@ public void testExtractionGivenSearchResponseHasShardFailures() { extractor.setNextResponse(createResponseWithShardFailures()); assertThat(extractor.hasNext(), is(true)); - IOException e = expectThrows(IOException.class, extractor::next); + expectThrows(IOException.class, extractor::next); } public void testExtractionGivenInitSearchResponseEncounteredUnavailableShards() { diff --git a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/params/ForecastParamsTests.java b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/params/ForecastParamsTests.java index 84d9e6ceabdb4..b3467a3d4054d 100644 --- a/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/params/ForecastParamsTests.java +++ b/x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/job/process/autodetect/params/ForecastParamsTests.java @@ -16,7 +16,6 @@ public class ForecastParamsTests extends ESTestCase { - private static ParseField END = new ParseField("end"); private static ParseField DURATION = new ParseField("duration"); public void testForecastIdsAreUnique() { diff --git a/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/action/SearchActionTests.java b/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/action/SearchActionTests.java index d7bb34bb1561f..19933d181188c 100644 --- a/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/action/SearchActionTests.java +++ b/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/action/SearchActionTests.java @@ -81,6 +81,7 @@ public class SearchActionTests extends ESTestCase { private NamedWriteableRegistry namedWriteableRegistry; + @Override @Before public void setUp() throws Exception { super.setUp(); @@ -523,8 +524,7 @@ public void testTwoMatchingJobsOneBetter() { public void testNoIndicesToSeparate() { String[] indices = new String[]{}; ImmutableOpenMap meta = ImmutableOpenMap.builder().build(); - IllegalArgumentException e = expectThrows(IllegalArgumentException.class, - () -> TransportRollupSearchAction.separateIndices(indices, meta)); + expectThrows(IllegalArgumentException.class, () -> TransportRollupSearchAction.separateIndices(indices, meta)); } public void testSeparateAll() { @@ -774,6 +774,7 @@ public void testBoth() throws IOException { MultiSearchResponse msearchResponse = new MultiSearchResponse(new MultiSearchResponse.Item[]{unrolledResponse, rolledResponse}, 123); + SearchResponse response = TransportRollupSearchAction.processResponses(separateIndices, msearchResponse, mock(InternalAggregation.ReduceContext.class)); diff --git a/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/job/IndexerUtilsTests.java b/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/job/IndexerUtilsTests.java index f5d335ca6f106..bee43bce47112 100644 --- a/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/job/IndexerUtilsTests.java +++ b/x-pack/plugin/rollup/src/test/java/org/elasticsearch/xpack/rollup/job/IndexerUtilsTests.java @@ -200,7 +200,6 @@ public void testNumericTerms() throws IOException { String indexName = randomAlphaOfLengthBetween(1, 10); RollupIndexerJobStats stats= new RollupIndexerJobStats(0, 0, 0, 0); - String timestampField = "the_histo"; String valueField = "the_avg"; Directory directory = newDirectory(); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportDeleteRoleActionTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportDeleteRoleActionTests.java index 94856f701fa05..612a0ea83c0f8 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportDeleteRoleActionTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/action/role/TransportDeleteRoleActionTests.java @@ -126,7 +126,6 @@ public void testException() { DeleteRoleRequest request = new DeleteRoleRequest(); request.name(roleName); - final boolean found = randomBoolean(); doAnswer(new Answer() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlMetadataCommandTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlMetadataCommandTests.java index e239c8706b99f..f2c91437c3e02 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlMetadataCommandTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authc/saml/SamlMetadataCommandTests.java @@ -33,7 +33,6 @@ import org.opensaml.xmlsec.signature.X509Certificate; import org.opensaml.xmlsec.signature.X509Data; import org.opensaml.xmlsec.signature.support.SignatureValidator; -import org.w3c.dom.Element; import java.io.OutputStream; import java.nio.file.Files; @@ -385,7 +384,7 @@ public void testSigningMetadataWithPasswordProtectedPfx() throws Exception { final MockTerminal terminal = new MockTerminal(); final EntityDescriptor descriptor = command.buildEntityDescriptor(terminal, options, env); - Element e = command.possiblySignDescriptor(terminal, options, descriptor, env); + command.possiblySignDescriptor(terminal, options, descriptor, env); assertThat(descriptor, notNullValue()); // Verify generated signature assertThat(descriptor.getSignature(), notNullValue()); diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndexAliasesTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndexAliasesTests.java index 036f1667e14b8..dca113b6e4229 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndexAliasesTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/authz/IndexAliasesTests.java @@ -362,8 +362,7 @@ public void testDeleteAliasesCreateAndAliasesPermission2() { IndicesAliasesAction.NAME, "create_test_aliases_alias"); //fails: user doesn't have manage_aliases on test_*, wildcards can't get replaced - IndexNotFoundException indexNotFoundException = expectThrows(IndexNotFoundException.class, - client.admin().indices().prepareAliases().removeAlias("test_*", "alias_1")::get); + expectThrows(IndexNotFoundException.class, client.admin().indices().prepareAliases().removeAlias("test_*", "alias_1")::get); } public void testGetAliasesCreateAndAliasesPermission2() { diff --git a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java index 541e660691275..16bdc705a4390 100644 --- a/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java +++ b/x-pack/plugin/security/src/test/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java @@ -32,10 +32,6 @@ import org.elasticsearch.xpack.core.ssl.SSLService; import org.elasticsearch.xpack.security.LocalStateSecurity; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.TrustManagerFactory; - import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; @@ -48,10 +44,13 @@ import java.util.Locale; import java.util.Set; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.TrustManagerFactory; + import static org.elasticsearch.test.SecuritySettingsSource.addSSLSettingsForPEMFiles; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.instanceOf; public class SslIntegrationTests extends SecurityIntegTestCase { @@ -150,10 +149,7 @@ public void testThatHttpUsingSSLv3IsRejected() throws Exception { SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, new String[]{ "SSLv3" }, null, NoopHostnameVerifier.INSTANCE); try (CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sf).build()) { - CloseableHttpResponse result = SocketAccess.doPrivileged(() -> client.execute(new HttpGet(getNodeUrl()))); - fail("Expected a connection error due to SSLv3 not being supported by default"); - } catch (Exception e) { - assertThat(e, is(instanceOf(SSLHandshakeException.class))); + expectThrows(SSLHandshakeException.class, () -> SocketAccess.doPrivileged(() -> client.execute(new HttpGet(getNodeUrl())))); } } diff --git a/x-pack/plugin/sql/jdbc/src/main/java/org/elasticsearch/xpack/sql/jdbc/jdbc/JdbcConfiguration.java b/x-pack/plugin/sql/jdbc/src/main/java/org/elasticsearch/xpack/sql/jdbc/jdbc/JdbcConfiguration.java index a2ab9060b5aa3..ca35504b2c806 100644 --- a/x-pack/plugin/sql/jdbc/src/main/java/org/elasticsearch/xpack/sql/jdbc/jdbc/JdbcConfiguration.java +++ b/x-pack/plugin/sql/jdbc/src/main/java/org/elasticsearch/xpack/sql/jdbc/jdbc/JdbcConfiguration.java @@ -66,7 +66,6 @@ public class JdbcConfiguration extends ConnectionConfiguration { } // immutable properties - private final String originalUrl; private final boolean debug; private final String debugOut; @@ -147,8 +146,6 @@ private static Properties parseProperties(URI uri, String u) throws JdbcSQLExcep private JdbcConfiguration(URI baseURI, String u, Properties props) throws JdbcSQLException { super(baseURI, u, props); - this.originalUrl = u; - this.debug = parseValue(DEBUG, props.getProperty(DEBUG, DEBUG_DEFAULT), Boolean::parseBoolean); this.debugOut = props.getProperty(DEBUG_OUTPUT, DEBUG_OUTPUT_DEFAULT); diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java index f45368afc06f0..ec56e2c2f112b 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/analysis/analyzer/Analyzer.java @@ -112,10 +112,6 @@ protected Iterable.Batch> batches() { new ResolveAggsInHaving() //new ImplicitCasting() ); - // TODO: this might be removed since the deduplication happens already in ResolveFunctions - Batch deduplication = new Batch("Deduplication", - new PruneDuplicateFunctions()); - return Arrays.asList(substitution, resolution); } @@ -196,7 +192,7 @@ private static Attribute resolveAgainstList(UnresolvedAttribute u, Collection exprs) { for (Expression expression : exprs) { if (expression instanceof UnresolvedStar) { diff --git a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/LogicalPlanBuilder.java b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/LogicalPlanBuilder.java index 58d858c42415a..7d41e6e677dd4 100644 --- a/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/LogicalPlanBuilder.java +++ b/x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/LogicalPlanBuilder.java @@ -177,6 +177,7 @@ public LogicalPlan visitRelation(RelationContext ctx) { private Join doJoin(LogicalPlan left, JoinRelationContext ctx) { JoinTypeContext joinType = ctx.joinType(); + @SuppressWarnings("unused") Join.JoinType type = JoinType.INNER; if (joinType != null) { if (joinType.FULL() != null) { @@ -190,6 +191,7 @@ private Join doJoin(LogicalPlan left, JoinRelationContext ctx) { } } + @SuppressWarnings("unused") Expression condition = null; JoinCriteriaContext criteria = ctx.joinCriteria(); if (criteria != null) { diff --git a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SourceGeneratorTests.java b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SourceGeneratorTests.java index 816b665133583..43c72b5583d11 100644 --- a/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SourceGeneratorTests.java +++ b/x-pack/plugin/sql/src/test/java/org/elasticsearch/xpack/sql/execution/search/SourceGeneratorTests.java @@ -61,12 +61,12 @@ public void testQueryFilter() { public void testLimit() { QueryContainer container = new QueryContainer().withLimit(10).addGroups(singletonList(new GroupByColumnKey("1", "field"))); - SearchSourceBuilder sourceBuilder = SourceGenerator.sourceBuilder(container, null, randomIntBetween(1, 10)); + int size = randomIntBetween(1, 10); + SearchSourceBuilder sourceBuilder = SourceGenerator.sourceBuilder(container, null, size); Builder aggBuilder = sourceBuilder.aggregations(); assertEquals(1, aggBuilder.count()); CompositeAggregationBuilder composite = (CompositeAggregationBuilder) aggBuilder.getAggregatorFactories().get(0); - // TODO: cannot access size - //assertEquals(10, composite.size()); + assertEquals(size, composite.size()); } public void testSortNoneSpecified() { diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/ScriptCondition.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/ScriptCondition.java index e2befe9a24e68..b65eca086c46c 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/ScriptCondition.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/condition/ScriptCondition.java @@ -29,20 +29,17 @@ public final class ScriptCondition implements ExecutableCondition { private static final Result MET = new Result(null, TYPE, true); private static final Result UNMET = new Result(null, TYPE, false); - private final ScriptService scriptService; private final Script script; private final ExecutableScript.Factory scriptFactory; public ScriptCondition(Script script) { this.script = script; - scriptService = null; scriptFactory = null; } - ScriptCondition(Script script, ScriptService scriptService) { - this.scriptService = scriptService; + ScriptCondition(Script script, ExecutableScript.Factory scriptFactory) { this.script = script; - scriptFactory = scriptService.compile(script, Watcher.SCRIPT_EXECUTABLE_CONTEXT); + this.scriptFactory = scriptFactory; } public Script getScript() { @@ -52,7 +49,7 @@ public Script getScript() { public static ScriptCondition parse(ScriptService scriptService, String watchId, XContentParser parser) throws IOException { try { Script script = Script.parse(parser); - return new ScriptCondition(script, scriptService); + return new ScriptCondition(script, scriptService.compile(script, Watcher.SCRIPT_EXECUTABLE_CONTEXT)); } catch (ElasticsearchParseException pe) { throw new ElasticsearchParseException("could not parse [{}] condition for watch [{}]. failed to parse script", pe, TYPE, watchId); diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/pagerduty/PagerDutyAccount.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/pagerduty/PagerDutyAccount.java index b2498a749d7b2..fdc5ca07b84c1 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/pagerduty/PagerDutyAccount.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/pagerduty/PagerDutyAccount.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.xpack.watcher.notification.pagerduty; -import org.apache.logging.log4j.Logger; import org.elasticsearch.common.settings.SecureSetting; import org.elasticsearch.common.settings.SecureString; import org.elasticsearch.common.settings.Setting; @@ -29,15 +28,13 @@ public class PagerDutyAccount { private final String serviceKey; private final HttpClient httpClient; private final IncidentEventDefaults eventDefaults; - private final Logger logger; - PagerDutyAccount(String name, Settings accountSettings, Settings serviceSettings, HttpClient httpClient, Logger logger) { + PagerDutyAccount(String name, Settings accountSettings, Settings serviceSettings, HttpClient httpClient) { this.name = name; this.serviceKey = getServiceKey(name, accountSettings, serviceSettings); this.httpClient = httpClient; this.eventDefaults = new IncidentEventDefaults(accountSettings.getAsSettings(TRIGGER_DEFAULTS_SETTING)); - this.logger = logger; } public String getName() { diff --git a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/pagerduty/PagerDutyService.java b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/pagerduty/PagerDutyService.java index 32a6dcb91aa51..c10bcf4782f4c 100644 --- a/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/pagerduty/PagerDutyService.java +++ b/x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/pagerduty/PagerDutyService.java @@ -51,7 +51,7 @@ public PagerDutyService(Settings settings, HttpClient httpClient, ClusterSetting @Override protected PagerDutyAccount createAccount(String name, Settings accountSettings) { - return new PagerDutyAccount(name, accountSettings, accountSettings, httpClient, logger); + return new PagerDutyAccount(name, accountSettings, accountSettings, httpClient); } public static List> getSettings() { diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/AlwaysConditionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/AlwaysConditionTests.java index 8ae0025066eb0..c29452302c0ab 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/AlwaysConditionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/AlwaysConditionTests.java @@ -8,9 +8,11 @@ import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; +import org.elasticsearch.script.Script; import org.elasticsearch.script.ScriptService; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.xpack.core.watcher.condition.ExecutableCondition; +import org.elasticsearch.xpack.watcher.Watcher; import java.time.Clock; @@ -53,7 +55,8 @@ public static ExecutableCondition randomCondition(ScriptService scriptService) { String type = randomFrom(ScriptCondition.TYPE, InternalAlwaysCondition.TYPE, CompareCondition.TYPE, ArrayCompareCondition.TYPE); switch (type) { case ScriptCondition.TYPE: - return new ScriptCondition(mockScript("_script"), scriptService); + Script mockScript = mockScript("_script"); + return new ScriptCondition(mockScript, scriptService.compile(mockScript, Watcher.SCRIPT_EXECUTABLE_CONTEXT)); case CompareCondition.TYPE: return new CompareCondition("_path", randomFrom(CompareCondition.Op.values()), randomFrom(5, "3"), Clock.systemUTC()); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ScriptConditionTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ScriptConditionTests.java index c7b7f2c63cdde..bef38a27b6be2 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ScriptConditionTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/condition/ScriptConditionTests.java @@ -94,7 +94,8 @@ public void init() throws IOException { } public void testExecute() throws Exception { - ScriptCondition condition = new ScriptCondition(mockScript("ctx.payload.hits.total > 1"), scriptService); + Script script = mockScript("ctx.payload.hits.total > 1"); + ScriptCondition condition = new ScriptCondition(script, scriptService.compile(script, Watcher.SCRIPT_EXECUTABLE_CONTEXT)); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 0, 500L, ShardSearchFailure.EMPTY_ARRAY, SearchResponse.Clusters.EMPTY); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); @@ -103,7 +104,7 @@ public void testExecute() throws Exception { public void testExecuteMergedParams() throws Exception { Script script = new Script(ScriptType.INLINE, "mockscript", "ctx.payload.hits.total > threshold", singletonMap("threshold", 1)); - ScriptCondition executable = new ScriptCondition(script, scriptService); + ScriptCondition executable = new ScriptCondition(script, scriptService.compile(script, Watcher.SCRIPT_EXECUTABLE_CONTEXT)); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 0, 500L, ShardSearchFailure.EMPTY_ARRAY, SearchResponse.Clusters.EMPTY); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); @@ -181,8 +182,9 @@ public void testScriptConditionParser_badLang() throws Exception { } public void testScriptConditionThrowException() throws Exception { + Script script = mockScript("null.foo"); ScriptCondition condition = new ScriptCondition( - mockScript("null.foo"), scriptService); + script, scriptService.compile(script, Watcher.SCRIPT_EXECUTABLE_CONTEXT)); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 0, 500L, ShardSearchFailure.EMPTY_ARRAY, SearchResponse.Clusters.EMPTY); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); @@ -191,7 +193,8 @@ public void testScriptConditionThrowException() throws Exception { } public void testScriptConditionReturnObjectThrowsException() throws Exception { - ScriptCondition condition = new ScriptCondition(mockScript("return new Object()"), scriptService); + Script script = mockScript("return new Object()"); + ScriptCondition condition = new ScriptCondition(script, scriptService.compile(script, Watcher.SCRIPT_EXECUTABLE_CONTEXT)); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 0, 500L, ShardSearchFailure.EMPTY_ARRAY, SearchResponse.Clusters.EMPTY); WatchExecutionContext ctx = mockExecutionContext("_name", new Payload.XContent(response)); @@ -201,8 +204,8 @@ public void testScriptConditionReturnObjectThrowsException() throws Exception { } public void testScriptConditionAccessCtx() throws Exception { - ScriptCondition condition = new ScriptCondition(mockScript("ctx.trigger.scheduled_time.getMillis() < new Date().time"), - scriptService); + Script script = mockScript("ctx.trigger.scheduled_time.getMillis() < new Date().time"); + ScriptCondition condition = new ScriptCondition(script, scriptService.compile(script, Watcher.SCRIPT_EXECUTABLE_CONTEXT)); SearchResponse response = new SearchResponse(InternalSearchResponse.empty(), "", 3, 3, 0, 500L, ShardSearchFailure.EMPTY_ARRAY, SearchResponse.Clusters.EMPTY); WatchExecutionContext ctx = mockExecutionContext("_name", new DateTime(DateTimeZone.UTC), new Payload.XContent(response)); diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java index 3461c530b4417..8cce6fd6663db 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/test/AbstractWatcherIntegrationTestCase.java @@ -5,7 +5,6 @@ */ package org.elasticsearch.xpack.watcher.test; -import org.apache.logging.log4j.Logger; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse; @@ -181,7 +180,7 @@ protected boolean timeWarped() { public void _setup() throws Exception { if (timeWarped()) { timeWarp = new TimeWarp(internalCluster().getInstances(ScheduleTriggerEngineMock.class), - (ClockMock)getInstanceFromMaster(Clock.class), logger); + (ClockMock)getInstanceFromMaster(Clock.class)); } if (internalCluster().size() > 0) { @@ -541,12 +540,10 @@ protected static class TimeWarp { private final List schedulers; private final ClockMock clock; - private final Logger logger; - TimeWarp(Iterable schedulers, ClockMock clock, Logger logger) { + TimeWarp(Iterable schedulers, ClockMock clock) { this.schedulers = StreamSupport.stream(schedulers.spliterator(), false).collect(Collectors.toList()); this.clock = clock; - this.logger = logger; } public void trigger(String jobName) { diff --git a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java index ae3066a3ee64f..2e8190da42f6d 100644 --- a/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java +++ b/x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/watch/WatchTests.java @@ -236,8 +236,7 @@ public void testThatBothStatusFieldsCanBeRead() throws Exception { TriggerService triggerService = new TriggerService(Settings.EMPTY, Collections.emptySet()) { @Override public Trigger parseTrigger(String jobName, XContentParser parser) throws IOException { - XContentParser.Token token; - while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { + while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) { } return new ScheduleTrigger(randomSchedule()); diff --git a/x-pack/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolIT.java b/x-pack/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolIT.java index 4ac927c6646c1..3581bf2fda7fd 100644 --- a/x-pack/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolIT.java +++ b/x-pack/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolIT.java @@ -7,7 +7,7 @@ import joptsimple.OptionParser; import joptsimple.OptionSet; -import org.elasticsearch.action.search.SearchResponse; + import org.elasticsearch.cli.MockTerminal; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; @@ -125,6 +125,6 @@ public void testRunMigrateTool() throws Exception { .waitForEvents(Priority.LANGUID) .waitForNoRelocatingShards(true)) .actionGet(); - SearchResponse searchResp = client.filterWithHeader(Collections.singletonMap("Authorization", token)).prepareSearch("index1").get(); + client.filterWithHeader(Collections.singletonMap("Authorization", token)).prepareSearch("index1").get(); } } diff --git a/x-pack/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolTestCase.java b/x-pack/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolTestCase.java index 2987c1afc8daf..6b323c4496d94 100644 --- a/x-pack/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolTestCase.java +++ b/x-pack/qa/security-migrate-tests/src/test/java/org/elasticsearch/xpack/security/MigrateToolTestCase.java @@ -129,7 +129,6 @@ public static String getHttpURL() { @BeforeClass public static void initializeSettings() throws UnknownHostException { - String port = System.getProperty("integ.http.port"); clusterAddresses = System.getProperty(TESTS_CLUSTER); clusterHttpAddresses = System.getProperty(TESTS_HTTP_CLUSTER); if (clusterAddresses == null || clusterAddresses.isEmpty()) { diff --git a/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/jdbc/JdbcAssert.java b/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/jdbc/JdbcAssert.java index 133006c66a820..b0a0d36fba446 100644 --- a/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/jdbc/JdbcAssert.java +++ b/x-pack/qa/sql/src/main/java/org/elasticsearch/xpack/qa/sql/jdbc/JdbcAssert.java @@ -14,10 +14,8 @@ import java.sql.SQLException; import java.sql.Types; import java.util.ArrayList; -import java.util.Calendar; import java.util.List; import java.util.Locale; -import java.util.TimeZone; import static java.lang.String.format; import static java.sql.Types.BIGINT; @@ -35,8 +33,6 @@ * Utility class for doing JUnit-style asserts over JDBC. */ public class JdbcAssert { - private static final Calendar UTC_CALENDAR = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT); - public static void assertResultSets(ResultSet expected, ResultSet actual) throws SQLException { assertResultSets(expected, actual, null); } @@ -133,7 +129,7 @@ public static void assertResultSetData(ResultSet expected, ResultSet actual, Log doAssertResultSetData(ex, ac, logger, lenient); } } - + private static void doAssertResultSetData(ResultSet expected, ResultSet actual, Logger logger, boolean lenient) throws SQLException { ResultSetMetaData metaData = expected.getMetaData(); int columns = metaData.getColumnCount(); @@ -172,7 +168,7 @@ private static void doAssertResultSetData(ResultSet expected, ResultSet actual, } catch (ClassNotFoundException cnfe) { throw new SQLException(cnfe); } - + Object expectedObject = expected.getObject(column); Object actualObject = lenient ? actual.getObject(column, expectedColumnClass) : actual.getObject(column);