Procházet zdrojové kódy

Fix shadowed variables in various places - part 1 (#77555)

Part of #19752.

Fix a number of locations where local variables or parameters are shadowing a field
that is defined in the same class.
Rory Hunter před 4 roky
rodič
revize
e55edf937a
45 změnil soubory, kde provedl 253 přidání a 230 odebrání
  1. 11 0
      build-tools-internal/src/main/resources/checkstyle.xml
  2. 2 2
      client/benchmark/src/main/java/org/elasticsearch/client/benchmark/ops/search/SearchBenchmarkTask.java
  3. 2 2
      client/rest/src/main/java/org/elasticsearch/client/HeapBufferedAsyncResponseConsumer.java
  4. 2 2
      client/rest/src/main/java/org/elasticsearch/client/Request.java
  5. 26 26
      client/rest/src/main/java/org/elasticsearch/client/RestClient.java
  6. 12 12
      client/rest/src/test/java/org/elasticsearch/client/FailureTrackingResponseListenerTests.java
  7. 6 6
      client/rest/src/test/java/org/elasticsearch/client/HostsTrackingFailureListener.java
  8. 9 9
      client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java
  9. 3 3
      libs/cli/src/main/java/org/elasticsearch/cli/Terminal.java
  10. 3 3
      libs/core/src/main/java/org/elasticsearch/core/internal/io/Streams.java
  11. 6 6
      libs/core/src/main/java/org/elasticsearch/jdk/JavaVersion.java
  12. 3 3
      libs/dissect/src/main/java/org/elasticsearch/dissect/DissectMatch.java
  13. 10 10
      libs/dissect/src/main/java/org/elasticsearch/dissect/DissectParser.java
  14. 2 3
      libs/geo/src/main/java/org/elasticsearch/geometry/Polygon.java
  15. 3 3
      libs/grok/src/main/java/org/elasticsearch/grok/Grok.java
  16. 9 9
      libs/nio/src/main/java/org/elasticsearch/nio/InboundChannelBuffer.java
  17. 2 2
      libs/nio/src/main/java/org/elasticsearch/nio/RoundRobinSupplier.java
  18. 4 4
      libs/nio/src/main/java/org/elasticsearch/nio/SocketChannelContext.java
  19. 3 3
      libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java
  20. 2 3
      libs/x-content/src/main/java/org/elasticsearch/common/xcontent/ConstructingObjectParser.java
  21. 1 1
      libs/x-content/src/main/java/org/elasticsearch/common/xcontent/InstantiatingObjectParser.java
  22. 6 6
      libs/x-content/src/main/java/org/elasticsearch/common/xcontent/NamedXContentRegistry.java
  23. 26 12
      libs/x-content/src/main/java/org/elasticsearch/common/xcontent/ObjectParser.java
  24. 13 13
      libs/x-content/src/main/java/org/elasticsearch/common/xcontent/ParseField.java
  25. 7 7
      libs/x-content/src/main/java/org/elasticsearch/common/xcontent/ParsedMediaType.java
  26. 2 2
      libs/x-content/src/main/java/org/elasticsearch/common/xcontent/XContentBuilder.java
  27. 8 8
      libs/x-content/src/main/java/org/elasticsearch/common/xcontent/json/JsonXContentGenerator.java
  28. 3 3
      libs/x-content/src/main/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathBasedFilter.java
  29. 1 1
      modules/transport-netty4/src/main/java/org/elasticsearch/transport/netty4/Netty4Transport.java
  30. 2 2
      plugins/examples/painless-whitelist/src/main/java/org/elasticsearch/example/painlesswhitelist/ExampleWhitelistedClass.java
  31. 2 2
      plugins/examples/painless-whitelist/src/main/java/org/elasticsearch/example/painlesswhitelist/ExampleWhitelistedInstance.java
  32. 2 2
      plugins/examples/rescore/src/main/java/org/elasticsearch/example/rescore/ExampleRescoreBuilder.java
  33. 1 1
      plugins/transport-nio/src/main/java/org/elasticsearch/transport/nio/NioTransport.java
  34. 2 2
      server/src/main/java/org/elasticsearch/transport/RemoteClusterAwareClient.java
  35. 1 1
      server/src/main/java/org/elasticsearch/transport/RemoteClusterConnection.java
  36. 3 4
      server/src/main/java/org/elasticsearch/transport/RemoteClusterService.java
  37. 4 4
      server/src/main/java/org/elasticsearch/transport/RemoteConnectionStrategy.java
  38. 6 6
      server/src/main/java/org/elasticsearch/transport/SniffConnectionStrategy.java
  39. 7 7
      server/src/main/java/org/elasticsearch/transport/TcpTransport.java
  40. 4 4
      server/src/main/java/org/elasticsearch/transport/TransportHandshaker.java
  41. 2 2
      server/src/main/java/org/elasticsearch/transport/TransportMessage.java
  42. 2 2
      server/src/main/java/org/elasticsearch/transport/TransportService.java
  43. 26 25
      server/src/main/java/org/elasticsearch/watcher/FileWatcher.java
  44. 1 1
      server/src/test/java/org/elasticsearch/transport/RemoteClusterServiceTests.java
  45. 1 1
      test/framework/src/main/java/org/elasticsearch/transport/nio/MockNioTransport.java

+ 11 - 0
build-tools-internal/src/main/resources/checkstyle.xml

@@ -95,6 +95,17 @@
       lines up with the directory structure. -->
     <module name="PackageDeclaration" />
 
+    <!-- Checks that a local variable or a parameter does not shadow a field that is defined in the same class. -->
+    <!-- Disabled until existing violations are fixed -->
+    <!--
+    <module name="HiddenField">
+        <property name="ignoreConstructorParameter" value="true" />
+        <property name="ignoreSetter" value="true" />
+        <property name="setterCanReturnItsClass" value="true"/>
+        <property name="ignoreFormat" value="^(threadPool)$"/>
+    </module>
+    -->
+
     <!-- We don't use Java's builtin serialization and we suppress all warning
       about it. The flip side of that coin is that we shouldn't _try_ to use
       it. We can't outright ban it with ForbiddenApis because it complain about

+ 2 - 2
client/benchmark/src/main/java/org/elasticsearch/client/benchmark/ops/search/SearchBenchmarkTask.java

@@ -32,8 +32,8 @@ public class SearchBenchmarkTask implements BenchmarkTask {
     }
 
     @Override
-    public void setUp(SampleRecorder sampleRecorder) throws Exception {
-        this.sampleRecorder = sampleRecorder;
+    public void setUp(SampleRecorder recorder) throws Exception {
+        this.sampleRecorder = recorder;
     }
 
     @Override

+ 2 - 2
client/rest/src/main/java/org/elasticsearch/client/HeapBufferedAsyncResponseConsumer.java

@@ -65,8 +65,8 @@ public class HeapBufferedAsyncResponseConsumer extends AbstractAsyncResponseCons
     }
 
     @Override
-    protected void onResponseReceived(HttpResponse response) throws HttpException, IOException {
-        this.response = response;
+    protected void onResponseReceived(HttpResponse httpResponse) throws HttpException, IOException {
+        this.response = httpResponse;
     }
 
     @Override

+ 2 - 2
client/rest/src/main/java/org/elasticsearch/client/Request.java

@@ -109,8 +109,8 @@ public final class Request {
      * If you need a different content type then use
      * {@link #setEntity(HttpEntity)}.
      */
-    public void setJsonEntity(String entity) {
-        setEntity(entity == null ? null : new NStringEntity(entity, ContentType.APPLICATION_JSON));
+    public void setJsonEntity(String body) {
+        setEntity(body == null ? null : new NStringEntity(body, ContentType.APPLICATION_JSON));
     }
 
     /**

+ 26 - 26
client/rest/src/main/java/org/elasticsearch/client/RestClient.java

@@ -270,10 +270,10 @@ public class RestClient implements Closeable {
         return performRequest(nextNodes(), internalRequest, null);
     }
 
-    private Response performRequest(final NodeTuple<Iterator<Node>> nodeTuple,
+    private Response performRequest(final NodeTuple<Iterator<Node>> tuple,
                                     final InternalRequest request,
                                     Exception previousException) throws IOException {
-        RequestContext context = request.createContextForNextAttempt(nodeTuple.nodes.next(), nodeTuple.authCache);
+        RequestContext context = request.createContextForNextAttempt(tuple.nodes.next(), tuple.authCache);
         HttpResponse httpResponse;
         try {
             httpResponse = client.execute(context.requestProducer, context.asyncResponseConsumer, context.context, null).get();
@@ -282,8 +282,8 @@ public class RestClient implements Closeable {
             onFailure(context.node);
             Exception cause = extractAndWrapCause(e);
             addSuppressedException(previousException, cause);
-            if (nodeTuple.nodes.hasNext()) {
-                return performRequest(nodeTuple, request, cause);
+            if (tuple.nodes.hasNext()) {
+                return performRequest(tuple, request, cause);
             }
             if (cause instanceof IOException) {
                 throw (IOException) cause;
@@ -298,8 +298,8 @@ public class RestClient implements Closeable {
             return responseOrResponseException.response;
         }
         addSuppressedException(previousException, responseOrResponseException.responseException);
-        if (nodeTuple.nodes.hasNext()) {
-            return performRequest(nodeTuple, request, responseOrResponseException.responseException);
+        if (tuple.nodes.hasNext()) {
+            return performRequest(tuple, request, responseOrResponseException.responseException);
         }
         throw responseOrResponseException.responseException;
     }
@@ -366,11 +366,11 @@ public class RestClient implements Closeable {
         }
     }
 
-    private void performRequestAsync(final NodeTuple<Iterator<Node>> nodeTuple,
+    private void performRequestAsync(final NodeTuple<Iterator<Node>> tuple,
                                      final InternalRequest request,
                                      final FailureTrackingResponseListener listener) {
         request.cancellable.runIfNotCancelled(() -> {
-            final RequestContext context = request.createContextForNextAttempt(nodeTuple.nodes.next(), nodeTuple.authCache);
+            final RequestContext context = request.createContextForNextAttempt(tuple.nodes.next(), tuple.authCache);
             client.execute(context.requestProducer, context.asyncResponseConsumer, context.context, new FutureCallback<HttpResponse>() {
                 @Override
                 public void completed(HttpResponse httpResponse) {
@@ -379,9 +379,9 @@ public class RestClient implements Closeable {
                         if (responseOrResponseException.responseException == null) {
                             listener.onSuccess(responseOrResponseException.response);
                         } else {
-                            if (nodeTuple.nodes.hasNext()) {
+                            if (tuple.nodes.hasNext()) {
                                 listener.trackFailure(responseOrResponseException.responseException);
-                                performRequestAsync(nodeTuple, request, listener);
+                                performRequestAsync(tuple, request, listener);
                             } else {
                                 listener.onDefinitiveFailure(responseOrResponseException.responseException);
                             }
@@ -396,9 +396,9 @@ public class RestClient implements Closeable {
                     try {
                         RequestLogger.logFailedRequest(logger, request.httpRequest, context.node, failure);
                         onFailure(context.node);
-                        if (nodeTuple.nodes.hasNext()) {
+                        if (tuple.nodes.hasNext()) {
                             listener.trackFailure(failure);
-                            performRequestAsync(nodeTuple, request, listener);
+                            performRequestAsync(tuple, request, listener);
                         } else {
                             listener.onDefinitiveFailure(failure);
                         }
@@ -425,9 +425,9 @@ public class RestClient implements Closeable {
      * @throws IOException if no nodes are available
      */
     private NodeTuple<Iterator<Node>> nextNodes() throws IOException {
-        NodeTuple<List<Node>> nodeTuple = this.nodeTuple;
-        Iterable<Node> hosts = selectNodes(nodeTuple, blacklist, lastNodeIndex, nodeSelector);
-        return new NodeTuple<>(hosts.iterator(), nodeTuple.authCache);
+        NodeTuple<List<Node>> tuple = this.nodeTuple;
+        Iterable<Node> hosts = selectNodes(tuple, blacklist, lastNodeIndex, nodeSelector);
+        return new NodeTuple<>(hosts.iterator(), tuple.authCache);
     }
 
     /**
@@ -643,17 +643,17 @@ public class RestClient implements Closeable {
         /**
          * Tracks one last definitive failure and returns to the caller by notifying the wrapped listener
          */
-        void onDefinitiveFailure(Exception exception) {
-            trackFailure(exception);
+        void onDefinitiveFailure(Exception e) {
+            trackFailure(e);
             responseListener.onFailure(this.exception);
         }
 
         /**
          * Tracks an exception, which caused a retry hence we should not return yet to the caller
          */
-        void trackFailure(Exception exception) {
-            addSuppressedException(this.exception, exception);
-            this.exception = exception;
+        void trackFailure(Exception e) {
+            addSuppressedException(this.exception, e);
+            this.exception = e;
         }
     }
 
@@ -756,26 +756,26 @@ public class RestClient implements Closeable {
                 RestClient.this.warningsHandler : request.getOptions().getWarningsHandler();
         }
 
-        private void setHeaders(HttpRequest httpRequest, Collection<Header> requestHeaders) {
+        private void setHeaders(HttpRequest req, Collection<Header> requestHeaders) {
             // request headers override default headers, so we don't add default headers if they exist as request headers
             final Set<String> requestNames = new HashSet<>(requestHeaders.size());
             for (Header requestHeader : requestHeaders) {
-                httpRequest.addHeader(requestHeader);
+                req.addHeader(requestHeader);
                 requestNames.add(requestHeader.getName());
             }
             for (Header defaultHeader : defaultHeaders) {
                 if (requestNames.contains(defaultHeader.getName()) == false) {
-                    httpRequest.addHeader(defaultHeader);
+                    req.addHeader(defaultHeader);
                 }
             }
             if (compressionEnabled) {
-                httpRequest.addHeader("Accept-Encoding", "gzip");
+                req.addHeader("Accept-Encoding", "gzip");
             }
         }
 
-        private void setRequestConfig(HttpRequestBase httpRequest, RequestConfig requestConfig) {
+        private void setRequestConfig(HttpRequestBase requestBase, RequestConfig requestConfig) {
             if (requestConfig != null) {
-                httpRequest.setConfig(requestConfig);
+                requestBase.setConfig(requestConfig);
             }
         }
 

+ 12 - 12
client/rest/src/test/java/org/elasticsearch/client/FailureTrackingResponseListenerTests.java

@@ -43,8 +43,8 @@ public class FailureTrackingResponseListenerTests extends RestClientTestCase {
 
         final Response response = mockResponse();
         listener.onSuccess(response);
-        assertSame(response, responseListener.response.get());
-        assertNull(responseListener.exception.get());
+        assertSame(response, responseListener.lastResponse.get());
+        assertNull(responseListener.lastException.get());
     }
 
     public void testOnFailure() {
@@ -56,20 +56,20 @@ public class FailureTrackingResponseListenerTests extends RestClientTestCase {
             RuntimeException runtimeException = new RuntimeException("test" + i);
             expectedExceptions[i] = runtimeException;
             listener.trackFailure(runtimeException);
-            assertNull(responseListener.response.get());
-            assertNull(responseListener.exception.get());
+            assertNull(responseListener.lastResponse.get());
+            assertNull(responseListener.lastException.get());
         }
 
         if (randomBoolean()) {
             Response response = mockResponse();
             listener.onSuccess(response);
-            assertSame(response, responseListener.response.get());
-            assertNull(responseListener.exception.get());
+            assertSame(response, responseListener.lastResponse.get());
+            assertNull(responseListener.lastException.get());
         } else {
             RuntimeException runtimeException = new RuntimeException("definitive");
             listener.onDefinitiveFailure(runtimeException);
-            assertNull(responseListener.response.get());
-            Throwable exception = responseListener.exception.get();
+            assertNull(responseListener.lastResponse.get());
+            Throwable exception = responseListener.lastException.get();
             assertSame(runtimeException, exception);
 
             int i = numIters - 1;
@@ -83,19 +83,19 @@ public class FailureTrackingResponseListenerTests extends RestClientTestCase {
     }
 
     private static class MockResponseListener implements ResponseListener {
-        private final AtomicReference<Response> response = new AtomicReference<>();
-        private final AtomicReference<Exception> exception = new AtomicReference<>();
+        private final AtomicReference<Response> lastResponse = new AtomicReference<>();
+        private final AtomicReference<Exception> lastException = new AtomicReference<>();
 
         @Override
         public void onSuccess(Response response) {
-            if (this.response.compareAndSet(null, response) == false) {
+            if (this.lastResponse.compareAndSet(null, response) == false) {
                 throw new IllegalStateException("onSuccess was called multiple times");
             }
         }
 
         @Override
         public void onFailure(Exception exception) {
-            if (this.exception.compareAndSet(null, exception) == false) {
+            if (this.lastException.compareAndSet(null, exception) == false) {
                 throw new IllegalStateException("onFailure was called multiple times");
             }
         }

+ 6 - 6
client/rest/src/test/java/org/elasticsearch/client/HostsTrackingFailureListener.java

@@ -33,11 +33,11 @@ import static org.junit.Assert.assertThat;
  * {@link RestClient.FailureListener} impl that allows to track when it gets called for which host.
  */
 class HostsTrackingFailureListener extends RestClient.FailureListener {
-    private volatile Set<HttpHost> hosts = new HashSet<>();
+    private volatile Set<HttpHost> httpHosts = new HashSet<>();
 
     @Override
     public void onFailure(Node node) {
-        hosts.add(node.getHost());
+        httpHosts.add(node.getHost());
     }
 
     void assertCalled(List<Node> nodes) {
@@ -49,12 +49,12 @@ class HostsTrackingFailureListener extends RestClient.FailureListener {
     }
 
     void assertCalled(HttpHost... hosts) {
-        assertEquals(hosts.length, this.hosts.size());
-        assertThat(this.hosts, containsInAnyOrder(hosts));
-        this.hosts.clear();
+        assertEquals(hosts.length, this.httpHosts.size());
+        assertThat(this.httpHosts, containsInAnyOrder(hosts));
+        this.httpHosts.clear();
     }
 
     void assertNotCalled() {
-        assertEquals(0, hosts.size());
+        assertEquals(0, httpHosts.size());
     }
 }

+ 9 - 9
client/rest/src/test/java/org/elasticsearch/client/RestClientSingleHostIntegTests.java

@@ -95,15 +95,15 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase {
     }
 
     private HttpServer createHttpServer() throws Exception {
-        HttpServer httpServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
-        httpServer.start();
+        HttpServer mockServer = MockHttpServer.createHttp(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
+        mockServer.start();
         //returns a different status code depending on the path
         for (int statusCode : getAllStatusCodes()) {
-            httpServer.createContext(pathPrefix + "/" + statusCode, new ResponseHandler(statusCode));
+            mockServer.createContext(pathPrefix + "/" + statusCode, new ResponseHandler(statusCode));
         }
         waitForCancelHandler = new WaitForCancelHandler();
-        httpServer.createContext(pathPrefix + "/wait", waitForCancelHandler);
-        return httpServer;
+        mockServer.createContext(pathPrefix + "/wait", waitForCancelHandler);
+        return mockServer;
     }
 
     private static class WaitForCancelHandler implements HttpHandler {
@@ -540,12 +540,12 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase {
         return bodyTest(restClient, method);
     }
 
-    private Response bodyTest(final RestClient restClient, final String method) throws Exception {
+    private Response bodyTest(final RestClient client, final String method) throws Exception {
         int statusCode = randomStatusCode(getRandom());
-        return bodyTest(restClient, method, statusCode, new Header[0]);
+        return bodyTest(client, method, statusCode, new Header[0]);
     }
 
-    private Response bodyTest(RestClient restClient, String method, int statusCode, Header[] headers) throws Exception {
+    private Response bodyTest(RestClient client, String method, int statusCode, Header[] headers) throws Exception {
         String requestBody = "{ \"field\": \"value\" }";
         Request request = new Request(method, "/" + statusCode);
         request.setJsonEntity(requestBody);
@@ -556,7 +556,7 @@ public class RestClientSingleHostIntegTests extends RestClientTestCase {
         request.setOptions(options);
         Response esResponse;
         try {
-            esResponse = RestClientSingleHostTests.performRequestSyncOrAsync(restClient, request);
+            esResponse = RestClientSingleHostTests.performRequestSyncOrAsync(client, request);
         } catch(ResponseException e) {
             esResponse = e.getResponse();
         }

+ 3 - 3
libs/cli/src/main/java/org/elasticsearch/cli/Terminal.java

@@ -49,7 +49,7 @@ public abstract class Terminal {
     }
 
     /** The current verbosity for the terminal, defaulting to {@link Verbosity#NORMAL}. */
-    private Verbosity verbosity = Verbosity.NORMAL;
+    private Verbosity currentVerbosity = Verbosity.NORMAL;
 
     /** The newline used when calling println. */
     private final String lineSeparator;
@@ -60,7 +60,7 @@ public abstract class Terminal {
 
     /** Sets the verbosity of the terminal. */
     public void setVerbosity(Verbosity verbosity) {
-        this.verbosity = verbosity;
+        this.currentVerbosity = verbosity;
     }
 
     /** Reads clear text from the terminal input. See {@link Console#readLine()}. */
@@ -128,7 +128,7 @@ public abstract class Terminal {
 
     /** Checks if is enough {@code verbosity} level to be printed */
     public final boolean isPrintable(Verbosity verbosity) {
-        return this.verbosity.ordinal() >= verbosity.ordinal();
+        return this.currentVerbosity.ordinal() >= verbosity.ordinal();
     }
 
     /**

+ 3 - 3
libs/core/src/main/java/org/elasticsearch/core/internal/io/Streams.java

@@ -19,7 +19,7 @@ import java.io.OutputStream;
  */
 public class Streams {
 
-    private static final ThreadLocal<byte[]> buffer = ThreadLocal.withInitial(() -> new byte[8 * 1024]);
+    private static final ThreadLocal<byte[]> LOCAL_BUFFER = ThreadLocal.withInitial(() -> new byte[8 * 1024]);
 
     private Streams() {
 
@@ -60,7 +60,7 @@ public class Streams {
      * @see #copy(InputStream, OutputStream, byte[], boolean)
      */
     public static long copy(final InputStream in, final OutputStream out, boolean close) throws IOException {
-        return copy(in, out, buffer.get(), close);
+        return copy(in, out, LOCAL_BUFFER.get(), close);
     }
 
     /**
@@ -74,6 +74,6 @@ public class Streams {
      * @see #copy(InputStream, OutputStream, byte[], boolean)
      */
     public static long copy(final InputStream in, final OutputStream out) throws IOException {
-        return copy(in, out, buffer.get(), true);
+        return copy(in, out, LOCAL_BUFFER.get(), true);
     }
 }

+ 6 - 6
libs/core/src/main/java/org/elasticsearch/jdk/JavaVersion.java

@@ -95,13 +95,13 @@ public class JavaVersion implements Comparable<JavaVersion> {
         return 0;
     }
 
-    private int comparePrePart(String prePart, String otherPrePart) {
-        if (prePart.matches("\\d+")) {
-            return otherPrePart.matches("\\d+") ?
-                (new BigInteger(prePart)).compareTo(new BigInteger(otherPrePart)) : -1;
+    private int comparePrePart(String leftPrePart, String rightPrePart) {
+        if (leftPrePart.matches("\\d+")) {
+            return rightPrePart.matches("\\d+") ?
+                (new BigInteger(leftPrePart)).compareTo(new BigInteger(rightPrePart)) : -1;
         } else {
-            return otherPrePart.matches("\\d+") ?
-                1 : prePart.compareTo(otherPrePart);
+            return rightPrePart.matches("\\d+") ?
+                1 : leftPrePart.compareTo(rightPrePart);
         }
     }
 

+ 3 - 3
libs/dissect/src/main/java/org/elasticsearch/dissect/DissectMatch.java

@@ -85,11 +85,11 @@ final class DissectMatch {
 
     /**
      * Checks if results are valid.
-     * @param results the results to check
+     * @param resultsToCheck the results to check
      * @return true if all dissect keys have been matched and the results are of the expected size.
      */
-    boolean isValid(Map<String, String> results) {
-        return fullyMatched() && results.size() == maxResults;
+    boolean isValid(Map<String, String> resultsToCheck) {
+        return fullyMatched() && resultsToCheck.size() == maxResults;
     }
 
     /**

+ 10 - 10
libs/dissect/src/main/java/org/elasticsearch/dissect/DissectParser.java

@@ -108,39 +108,39 @@ public final class DissectParser {
         while (matcher.find()) {
             leadingDelimiter = matcher.group(1);
         }
-        List<DissectPair> matchPairs = new ArrayList<>();
+        List<DissectPair> dissectPairs = new ArrayList<>();
         matcher = KEY_DELIMITER_FIELD_PATTERN.matcher(pattern.substring(leadingDelimiter.length()));
         while (matcher.find()) {
             DissectKey key = new DissectKey(matcher.group(1));
             String delimiter = matcher.group(2);
-            matchPairs.add(new DissectPair(key, delimiter));
+            dissectPairs.add(new DissectPair(key, delimiter));
         }
-        this.maxMatches = matchPairs.size();
-        this.maxResults = Long.valueOf(matchPairs.stream()
+        this.maxMatches = dissectPairs.size();
+        this.maxResults = Long.valueOf(dissectPairs.stream()
             .filter(dissectPair -> dissectPair.getKey().skip() == false).map(KEY_NAME).distinct().count()).intValue();
         if (this.maxMatches == 0 || maxResults == 0) {
             throw new DissectException.PatternParse(pattern, "Unable to find any keys or delimiters.");
         }
         //append validation - look through all of the keys to see if there are any keys that need to participate in an append operation
         // but don't have the '+' defined
-        Set<String> appendKeyNames = matchPairs.stream()
+        Set<String> appendKeyNames = dissectPairs.stream()
             .filter(dissectPair -> APPEND_MODIFIERS.contains(dissectPair.getKey().getModifier()))
             .map(KEY_NAME).distinct().collect(Collectors.toSet());
         if (appendKeyNames.size() > 0) {
-            List<DissectPair> modifiedMatchPairs = new ArrayList<>(matchPairs.size());
-            for (DissectPair p : matchPairs) {
+            List<DissectPair> modifiedMatchPairs = new ArrayList<>(dissectPairs.size());
+            for (DissectPair p : dissectPairs) {
                 if (p.getKey().getModifier().equals(DissectKey.Modifier.NONE) && appendKeyNames.contains(p.getKey().getName())) {
                     modifiedMatchPairs.add(new DissectPair(new DissectKey(p.getKey(), DissectKey.Modifier.APPEND), p.getDelimiter()));
                 } else {
                     modifiedMatchPairs.add(p);
                 }
             }
-            matchPairs = modifiedMatchPairs;
+            dissectPairs = modifiedMatchPairs;
         }
         appendCount = appendKeyNames.size();
 
         //reference validation - ensure that '*' and '&' come in pairs
-        Map<String, List<DissectPair>> referenceGroupings = matchPairs.stream()
+        Map<String, List<DissectPair>> referenceGroupings = dissectPairs.stream()
             .filter(dissectPair -> ASSOCIATE_MODIFIERS.contains(dissectPair.getKey().getModifier()))
             .collect(Collectors.groupingBy(KEY_NAME));
         for (Map.Entry<String, List<DissectPair>> entry : referenceGroupings.entrySet()) {
@@ -152,7 +152,7 @@ public final class DissectParser {
         }
 
         referenceCount = referenceGroupings.size() * 2;
-        this.matchPairs = Collections.unmodifiableList(matchPairs);
+        this.matchPairs = Collections.unmodifiableList(dissectPairs);
     }
 
 

+ 2 - 3
libs/geo/src/main/java/org/elasticsearch/geometry/Polygon.java

@@ -36,15 +36,14 @@ public final class Polygon implements Geometry {
         if (holes == null) {
             throw new IllegalArgumentException("holes must not be null");
         }
-        boolean hasAlt = polygon.hasZ();
+        this.hasAlt = polygon.hasZ();
         checkRing(polygon);
         for (LinearRing hole : holes) {
-            if (hole.hasZ() != hasAlt) {
+            if (hole.hasZ() != this.hasAlt) {
                 throw new IllegalArgumentException("holes must have the same number of dimensions as the polygon");
             }
             checkRing(hole);
         }
-        this.hasAlt = hasAlt;
     }
 
     /**

+ 3 - 3
libs/grok/src/main/java/org/elasticsearch/grok/Grok.java

@@ -91,11 +91,11 @@ public final class Grok {
         this.compiledExpression = new Regex(expressionBytes, 0, expressionBytes.length, Option.DEFAULT, UTF8Encoding.INSTANCE,
             message -> logCallBack.accept(message));
 
-        List<GrokCaptureConfig> captureConfig = new ArrayList<>();
+        List<GrokCaptureConfig> grokCaptureConfigs = new ArrayList<>();
         for (Iterator<NameEntry> entry = compiledExpression.namedBackrefIterator(); entry.hasNext();) {
-            captureConfig.add(new GrokCaptureConfig(entry.next()));
+            grokCaptureConfigs.add(new GrokCaptureConfig(entry.next()));
         }
-        this.captureConfig = List.copyOf(captureConfig);
+        this.captureConfig = List.copyOf(grokCaptureConfigs);
     }
 
     /**

+ 9 - 9
libs/nio/src/main/java/org/elasticsearch/nio/InboundChannelBuffer.java

@@ -162,20 +162,20 @@ public final class InboundChannelBuffer implements AutoCloseable {
             pageCount += 1;
         }
 
-        Page[] pages = new Page[pageCount];
+        Page[] duplicatePages = new Page[pageCount];
         Iterator<Page> pageIterator = this.pages.iterator();
         Page firstPage = pageIterator.next().duplicate();
         ByteBuffer firstBuffer = firstPage.byteBuffer();
         firstBuffer.position(firstBuffer.position() + offset);
-        pages[0] = firstPage;
-        for (int i = 1; i < pages.length; i++) {
-            pages[i] = pageIterator.next().duplicate();
+        duplicatePages[0] = firstPage;
+        for (int i = 1; i < duplicatePages.length; i++) {
+            duplicatePages[i] = pageIterator.next().duplicate();
         }
         if (finalLimit != 0) {
-            pages[pages.length - 1].byteBuffer().limit(finalLimit);
+            duplicatePages[duplicatePages.length - 1].byteBuffer().limit(finalLimit);
         }
 
-        return pages;
+        return duplicatePages;
     }
 
     /**
@@ -238,10 +238,10 @@ public final class InboundChannelBuffer implements AutoCloseable {
         return remaining;
     }
 
-    private int numPages(long capacity) {
-        final long numPages = (capacity + PAGE_MASK) >>> PAGE_SHIFT;
+    private int numPages(long requiredCapacity) {
+        final long numPages = (requiredCapacity + PAGE_MASK) >>> PAGE_SHIFT;
         if (numPages > Integer.MAX_VALUE) {
-            throw new IllegalArgumentException("pageSize=" + (PAGE_MASK + 1) + " is too small for such as capacity: " + capacity);
+            throw new IllegalArgumentException("pageSize=" + (PAGE_MASK + 1) + " is too small for such as capacity: " + requiredCapacity);
         }
         return (int) numPages;
     }

+ 2 - 2
libs/nio/src/main/java/org/elasticsearch/nio/RoundRobinSupplier.java

@@ -29,8 +29,8 @@ final class RoundRobinSupplier<S> implements Supplier<S> {
 
     @Override
     public S get() {
-        S[] selectors = this.selectors;
-        return selectors[counter.getAndIncrement() % selectors.length];
+        S[] currentSelectors = this.selectors;
+        return currentSelectors[counter.getAndIncrement() % currentSelectors.length];
     }
 
     void setSelectors(S[] selectors) {

+ 4 - 4
libs/nio/src/main/java/org/elasticsearch/nio/SocketChannelContext.java

@@ -252,7 +252,7 @@ public abstract class SocketChannelContext extends ChannelContext<SocketChannel>
     // data that is copied to the buffer for a write, but not successfully flushed immediately, must be
     // copied again on the next call.
 
-    protected int readFromChannel(InboundChannelBuffer channelBuffer) throws IOException {
+    protected int readFromChannel(InboundChannelBuffer inboundChannelBuffer) throws IOException {
         ByteBuffer ioBuffer = getSelector().getIoBuffer();
         int bytesRead;
         try {
@@ -266,14 +266,14 @@ public abstract class SocketChannelContext extends ChannelContext<SocketChannel>
             return 0;
         } else {
             ioBuffer.flip();
-            channelBuffer.ensureCapacity(channelBuffer.getIndex() + ioBuffer.remaining());
-            ByteBuffer[] buffers = channelBuffer.sliceBuffersFrom(channelBuffer.getIndex());
+            inboundChannelBuffer.ensureCapacity(inboundChannelBuffer.getIndex() + ioBuffer.remaining());
+            ByteBuffer[] buffers = inboundChannelBuffer.sliceBuffersFrom(inboundChannelBuffer.getIndex());
             int j = 0;
             while (j < buffers.length && ioBuffer.remaining() > 0) {
                 ByteBuffer buffer = buffers[j++];
                 ByteBufferUtils.copyBytes(ioBuffer, buffer);
             }
-            channelBuffer.incrementIndex(bytesRead);
+            inboundChannelBuffer.incrementIndex(bytesRead);
             return bytesRead;
         }
     }

+ 3 - 3
libs/ssl-config/src/main/java/org/elasticsearch/common/ssl/SslConfigurationLoader.java

@@ -335,12 +335,12 @@ public abstract class SslConfigurationLoader {
         return buildDefaultTrustConfig(defaultTrustConfig, keyConfig);
     }
 
-    protected SslTrustConfig buildDefaultTrustConfig(SslTrustConfig defaultTrustConfig, SslKeyConfig keyConfig) {
+    protected SslTrustConfig buildDefaultTrustConfig(SslTrustConfig trustConfig, SslKeyConfig keyConfig) {
         final SslTrustConfig trust = keyConfig.asTrustConfig();
         if (trust == null) {
-            return defaultTrustConfig;
+            return trustConfig;
         } else {
-            return new CompositeTrustConfig(List.of(defaultTrustConfig, trust));
+            return new CompositeTrustConfig(List.of(trustConfig, trust));
         }
     }
 

+ 2 - 3
libs/x-content/src/main/java/org/elasticsearch/common/xcontent/ConstructingObjectParser.java

@@ -475,12 +475,11 @@ public final class ConstructingObjectParser<Value, Context> extends AbstractObje
          * Queue a consumer that we'll call once the targetObject is built. If targetObject has been built this will fail because the caller
          * should have just applied the consumer immediately.
          */
+        @SuppressWarnings({"unchecked", "rawtypes"})
         private void queue(Consumer<Value> queueMe) {
             assert targetObject == null: "Don't queue after the targetObject has been built! Just apply the consumer directly.";
             if (queuedFields == null) {
-                @SuppressWarnings({"unchecked", "rawtypes"})
-                Consumer<Value>[] queuedFields = new Consumer[numberOfFields];
-                this.queuedFields = queuedFields;
+                this.queuedFields = (Consumer<Value>[]) new Consumer[numberOfFields];
             }
             queuedFields[queuedFieldsCount] = queueMe;
             queuedFieldsCount++;

+ 1 - 1
libs/x-content/src/main/java/org/elasticsearch/common/xcontent/InstantiatingObjectParser.java

@@ -76,7 +76,7 @@ public class InstantiatingObjectParser<Value, Context>
             this.valueClass = valueClass;
         }
 
-        @SuppressWarnings("unchecked")
+        @SuppressWarnings({"unchecked", "checkstyle:HiddenField"})
         public InstantiatingObjectParser<Value, Context> build() {
             Constructor<?> constructor = null;
             int neededArguments = constructingObjectParser.getNumberOfFields();

+ 6 - 6
libs/x-content/src/main/java/org/elasticsearch/common/xcontent/NamedXContentRegistry.java

@@ -88,26 +88,26 @@ public class NamedXContentRegistry {
             return emptyMap();
         }
 
-        Map<RestApiVersion,Map<Class<?>, Map<String, Entry>>> registry = new HashMap<>();
+        Map<RestApiVersion,Map<Class<?>, Map<String, Entry>>> newRegistry = new HashMap<>();
         for (Entry entry : entries) {
             for (String name : entry.name.getAllNamesIncludedDeprecated()) {
                 if (RestApiVersion.minimumSupported().matches(entry.restApiCompatibility)) {
-                    registerParsers(registry, entry, name, RestApiVersion.minimumSupported());
+                    registerParsers(newRegistry, entry, name, RestApiVersion.minimumSupported());
                 }
                 if (RestApiVersion.current().matches(entry.restApiCompatibility)) {
-                    registerParsers(registry, entry, name, RestApiVersion.current());
+                    registerParsers(newRegistry, entry, name, RestApiVersion.current());
                 }
             }
         }
-        return registry;
+        return newRegistry;
     }
 
-    private void registerParsers(Map<RestApiVersion, Map<Class<?>, Map<String, Entry>>> registry,
+    private void registerParsers(Map<RestApiVersion, Map<Class<?>, Map<String, Entry>>> newRegistry,
                                  Entry entry,
                                  String name,
                                  RestApiVersion restApiVersion) {
         final Map<Class<?>, Map<String, Entry>> classRegistry =
-            registry.computeIfAbsent(restApiVersion, (v) -> new HashMap<>());
+            newRegistry.computeIfAbsent(restApiVersion, (v) -> new HashMap<>());
         final Map<String, Entry> parsers =
             classRegistry.computeIfAbsent(entry.categoryClass, (v) -> new HashMap<>());
         Object old = parsers.put(name, entry);

+ 26 - 12
libs/x-content/src/main/java/org/elasticsearch/common/xcontent/ObjectParser.java

@@ -419,15 +419,19 @@ public final class ObjectParser<Value, Context> extends AbstractObjectParser<Val
             try {
                 XContentParser.Token token = p.nextToken();
                 assert token == XContentParser.Token.FIELD_NAME;
-                String name = p.currentName();
+                String currentName = p.currentName();
                 try {
-                    T namedObject = namedObjectParser.parse(p, c, name);
+                    T namedObject = namedObjectParser.parse(p, c, currentName);
                     // consume the end object token
                     token = p.nextToken();
                     assert token == XContentParser.Token.END_OBJECT;
                     return namedObject;
                 } catch (Exception e) {
-                    throw new XContentParseException(p.getTokenLocation(), "[" + field + "] failed to parse field [" + name + "]", e);
+                    throw new XContentParseException(
+                        p.getTokenLocation(),
+                        "[" + field + "] failed to parse field [" + currentName + "]",
+                        e
+                    );
                 }
             } catch (IOException e) {
                 throw new XContentParseException(p.getTokenLocation(), "[" + field + "] error while parsing named object", e);
@@ -448,11 +452,15 @@ public final class ObjectParser<Value, Context> extends AbstractObjectParser<Val
             }
             // This messy exception nesting has the nice side effect of telling the user which field failed to parse
             try {
-                String name = p.currentName();
+                String currentName = p.currentName();
                 try {
-                    return namedObjectParser.parse(p, c, name);
+                    return namedObjectParser.parse(p, c, currentName);
                 } catch (Exception e) {
-                    throw new XContentParseException(p.getTokenLocation(), "[" + field + "] failed to parse field [" + name + "]", e);
+                    throw new XContentParseException(
+                        p.getTokenLocation(),
+                        "[" + field + "] failed to parse field [" + currentName + "]",
+                        e
+                    );
                 }
             } catch (IOException e) {
                 throw new XContentParseException(p.getTokenLocation(), "[" + field + "] error while parsing", e);
@@ -603,14 +611,20 @@ public final class ObjectParser<Value, Context> extends AbstractObjectParser<Val
             this.type = type;
         }
 
-        void assertSupports(String parserName, XContentParser parser, String currentFieldName) {
-            if (parseField.match(parserName, parser::getTokenLocation, currentFieldName, parser.getDeprecationHandler()) == false) {
-                throw new XContentParseException(parser.getTokenLocation(),
+        void assertSupports(String parserName, XContentParser xContentParser, String currentFieldName) {
+            boolean match = parseField.match(
+                parserName,
+                xContentParser::getTokenLocation,
+                currentFieldName,
+                xContentParser.getDeprecationHandler()
+            );
+            if (match == false) {
+                throw new XContentParseException(xContentParser.getTokenLocation(),
                         "[" + parserName  + "] parsefield doesn't accept: " + currentFieldName);
             }
-            if (supportedTokens.contains(parser.currentToken()) == false) {
-                throw new XContentParseException(parser.getTokenLocation(),
-                        "[" + parserName + "] " + currentFieldName + " doesn't support values of type: " + parser.currentToken());
+            if (supportedTokens.contains(xContentParser.currentToken()) == false) {
+                throw new XContentParseException(xContentParser.getTokenLocation(),
+                        "[" + parserName + "] " + currentFieldName + " doesn't support values of type: " + xContentParser.currentToken());
             }
         }
 

+ 13 - 13
libs/x-content/src/main/java/org/elasticsearch/common/xcontent/ParseField.java

@@ -25,7 +25,7 @@ public class ParseField {
     private final String[] deprecatedNames;
     private final Function<RestApiVersion, Boolean> forRestApiVersion;
     private final String allReplacedWith;
-    private boolean fullyDeprecated;
+    private final boolean fullyDeprecated;
 
     private final String[] allNames;
 
@@ -46,10 +46,10 @@ public class ParseField {
         }
         this.forRestApiVersion = forRestApiVersion;
 
-        Set<String> allNames = new HashSet<>();
-        allNames.add(name);
-        Collections.addAll(allNames, this.deprecatedNames);
-        this.allNames = allNames.toArray(new String[allNames.size()]);
+        Set<String> names = new HashSet<>();
+        names.add(name);
+        Collections.addAll(names, this.deprecatedNames);
+        this.allNames = names.toArray(new String[names.size()]);
     }
 
     /**
@@ -80,23 +80,23 @@ public class ParseField {
     }
 
     /**
-     * @param deprecatedNames
+     * @param deprecatedNamesOverride
      *            deprecated names to include with the returned
      *            {@link ParseField}
      * @return a new {@link ParseField} using the preferred name from this one
      *         but with the specified deprecated names
      */
-    public ParseField withDeprecation(String... deprecatedNames) {
-        return new ParseField(this.name, this.forRestApiVersion, deprecatedNames, this.fullyDeprecated, this.allReplacedWith);
+    public ParseField withDeprecation(String... deprecatedNamesOverride) {
+        return new ParseField(this.name, this.forRestApiVersion, deprecatedNamesOverride, this.fullyDeprecated, this.allReplacedWith);
     }
 
 
     /**
      * Creates a new field with current name and deprecatedNames, but overrides forRestApiVersion
-     * @param forRestApiVersion - a boolean function indicating for what version a deprecated name is available
+     * @param forRestApiVersionOverride - a boolean function indicating for what version a deprecated name is available
      */
-    public ParseField forRestApiVersion(Function<RestApiVersion, Boolean> forRestApiVersion) {
-        return new ParseField(this.name, forRestApiVersion, this.deprecatedNames,
+    public ParseField forRestApiVersion(Function<RestApiVersion, Boolean> forRestApiVersionOverride) {
+        return new ParseField(this.name, forRestApiVersionOverride, this.deprecatedNames,
             this.fullyDeprecated, this.allReplacedWith);
     }
 
@@ -111,9 +111,9 @@ public class ParseField {
      * Return a new ParseField where all field names are deprecated and replaced
      * with {@code allReplacedWith}.
      */
-    public ParseField withAllDeprecated(String allReplacedWith) {
+    public ParseField withAllDeprecated(String allReplacedWithOverride) {
         return new ParseField(this.name, this.forRestApiVersion, getAllNamesIncludedDeprecated(),
-            this.fullyDeprecated, allReplacedWith);
+            this.fullyDeprecated, allReplacedWithOverride);
     }
 
     /**

+ 7 - 7
libs/x-content/src/main/java/org/elasticsearch/common/xcontent/ParsedMediaType.java

@@ -120,16 +120,16 @@ public class ParsedMediaType {
      * @return a MediaType instance or null if no media type could be found or if a known parameter do not passes validation
      */
     public  <T extends MediaType> T toMediaType(MediaTypeRegistry<T> mediaTypeRegistry) {
-        T type = mediaTypeRegistry.typeWithSubtypeToMediaType(mediaTypeWithoutParameters());
-        if (type != null) {
+        T someType = mediaTypeRegistry.typeWithSubtypeToMediaType(mediaTypeWithoutParameters());
 
+        if (someType != null) {
             Map<String, Pattern> registeredParams = mediaTypeRegistry.parametersFor(mediaTypeWithoutParameters());
             for (Map.Entry<String, String> givenParamEntry : parameters.entrySet()) {
                 if (isValidParameter(givenParamEntry.getKey(), givenParamEntry.getValue(), registeredParams) == false) {
                     return null;
                 }
             }
-            return type;
+            return someType;
         }
         return null;
     }
@@ -153,12 +153,12 @@ public class ParsedMediaType {
     }
 
     //used in testing
-    public String responseContentTypeHeader(Map<String,String> parameters) {
-        return mediaTypeWithoutParameters() + formatParameters(parameters);
+    public String responseContentTypeHeader(Map<String,String> params) {
+        return mediaTypeWithoutParameters() + formatParameters(params);
     }
 
-    private String formatParameters(Map<String, String> parameters) {
-        String joined = parameters.entrySet().stream()
+    private String formatParameters(Map<String, String> params) {
+        String joined = params.entrySet().stream()
             .map(e -> e.getKey() + "=" + e.getValue())
             .collect(Collectors.joining(";"));
         return joined.isEmpty() ? "" : ";" + joined;

+ 2 - 2
libs/x-content/src/main/java/org/elasticsearch/common/xcontent/XContentBuilder.java

@@ -279,8 +279,8 @@ public final class XContentBuilder implements Closeable, Flushable {
      * Set the "human readable" flag. Once set, some types of values are written in a
      * format easier to read for a human.
      */
-    public XContentBuilder humanReadable(boolean humanReadable) {
-        this.humanReadable = humanReadable;
+    public XContentBuilder humanReadable(boolean isHumanReadable) {
+        this.humanReadable = isHumanReadable;
         return this;
     }
 

+ 8 - 8
libs/x-content/src/main/java/org/elasticsearch/common/xcontent/json/JsonXContentGenerator.java

@@ -62,34 +62,34 @@ public class JsonXContentGenerator implements XContentGenerator {
     private static final DefaultPrettyPrinter.Indenter INDENTER = new DefaultIndenter("  ", LF.getValue());
     private boolean prettyPrint = false;
 
-    public JsonXContentGenerator(JsonGenerator jsonGenerator, OutputStream os, Set<String> includes, Set<String> excludes) {
+    public JsonXContentGenerator(JsonGenerator baseJsonGenerator, OutputStream os, Set<String> includes, Set<String> excludes) {
         Objects.requireNonNull(includes, "Including filters must not be null");
         Objects.requireNonNull(excludes, "Excluding filters must not be null");
         this.os = os;
-        if (jsonGenerator instanceof GeneratorBase) {
-            this.base = (GeneratorBase) jsonGenerator;
+        if (baseJsonGenerator instanceof GeneratorBase) {
+            this.base = (GeneratorBase) baseJsonGenerator;
         } else {
             this.base = null;
         }
 
-        JsonGenerator generator = jsonGenerator;
+        JsonGenerator jsonGenerator = baseJsonGenerator;
 
         boolean hasExcludes = excludes.isEmpty() == false;
         if (hasExcludes) {
-            generator = new FilteringGeneratorDelegate(generator, new FilterPathBasedFilter(excludes, false), true, true);
+            jsonGenerator = new FilteringGeneratorDelegate(jsonGenerator, new FilterPathBasedFilter(excludes, false), true, true);
         }
 
         boolean hasIncludes = includes.isEmpty() == false;
         if (hasIncludes) {
-            generator = new FilteringGeneratorDelegate(generator, new FilterPathBasedFilter(includes, true), true, true);
+            jsonGenerator = new FilteringGeneratorDelegate(jsonGenerator, new FilterPathBasedFilter(includes, true), true, true);
         }
 
         if (hasExcludes || hasIncludes) {
-            this.filter = (FilteringGeneratorDelegate) generator;
+            this.filter = (FilteringGeneratorDelegate) jsonGenerator;
         } else {
             this.filter = null;
         }
-        this.generator = generator;
+        this.generator = jsonGenerator;
     }
 
     @Override

+ 3 - 3
libs/x-content/src/main/java/org/elasticsearch/common/xcontent/support/filtering/FilterPathBasedFilter.java

@@ -49,11 +49,11 @@ public class FilterPathBasedFilter extends TokenFilter {
     /**
      * Evaluates if a property name matches one of the given filter paths.
      */
-    private TokenFilter evaluate(String name, FilterPath[] filters) {
-        if (filters != null) {
+    private TokenFilter evaluate(String name, FilterPath[] filterPaths) {
+        if (filterPaths != null) {
             List<FilterPath> nextFilters = null;
 
-            for (FilterPath filter : filters) {
+            for (FilterPath filter : filterPaths) {
                 FilterPath next = filter.matchProperty(name);
                 if (next != null) {
                     if (next.matches()) {

+ 1 - 1
modules/transport-netty4/src/main/java/org/elasticsearch/transport/netty4/Netty4Transport.java

@@ -114,7 +114,7 @@ public class Netty4Transport extends TcpTransport {
             sharedGroup = sharedGroupFactory.getTransportGroup();
             clientBootstrap = createClientBootstrap(sharedGroup);
             if (NetworkService.NETWORK_SERVER.get(settings)) {
-                for (ProfileSettings profileSettings : profileSettings) {
+                for (ProfileSettings profileSettings : profileSettingsSet) {
                     createServerBootstrap(profileSettings, sharedGroup);
                     bindServer(profileSettings);
                 }

+ 2 - 2
plugins/examples/painless-whitelist/src/main/java/org/elasticsearch/example/painlesswhitelist/ExampleWhitelistedClass.java

@@ -31,8 +31,8 @@ public class ExampleWhitelistedClass {
         return this.privateMember;
     }
 
-    public void setPrivateMemberAccessor(int privateMember) {
-        this.privateMember = privateMember;
+    public void setPrivateMemberAccessor(int value) {
+        this.privateMember = value;
     }
 
     public static void staticMethod() {

+ 2 - 2
plugins/examples/painless-whitelist/src/main/java/org/elasticsearch/example/painlesswhitelist/ExampleWhitelistedInstance.java

@@ -15,8 +15,8 @@ public class ExampleWhitelistedInstance {
         this.value = value;
     }
 
-    public int addValue(int value) {
-        return this.value + value;
+    public int addValue(int valueToAdd) {
+        return this.value + valueToAdd;
     }
 
     public int getValue() {

+ 2 - 2
plugins/examples/rescore/src/main/java/org/elasticsearch/example/rescore/ExampleRescoreBuilder.java

@@ -97,9 +97,9 @@ public class ExampleRescoreBuilder extends RescorerBuilder<ExampleRescoreBuilder
 
     @Override
     public RescoreContext innerBuildContext(int windowSize, SearchExecutionContext context) throws IOException {
-        IndexFieldData<?> factorField =
+        IndexFieldData<?> factorFieldData =
                 this.factorField == null ? null : context.getForField(context.getFieldType(this.factorField));
-        return new ExampleRescoreContext(windowSize, factor, factorField);
+        return new ExampleRescoreContext(windowSize, factor, factorFieldData);
     }
 
     @Override

+ 1 - 1
plugins/transport-nio/src/main/java/org/elasticsearch/transport/nio/NioTransport.java

@@ -87,7 +87,7 @@ public class NioTransport extends TcpTransport {
 
             if (NetworkService.NETWORK_SERVER.get(settings)) {
                 // loop through all profiles and start them up, special handling for default one
-                for (ProfileSettings profileSettings : profileSettings) {
+                for (ProfileSettings profileSettings : profileSettingsSet) {
                     String profileName = profileSettings.profileName;
                     TcpChannelFactory factory = serverChannelFactory(profileSettings);
                     profileToChannelFactory.putIfAbsent(profileName, factory);

+ 2 - 2
server/src/main/java/org/elasticsearch/transport/RemoteClusterAwareClient.java

@@ -54,7 +54,7 @@ final class RemoteClusterAwareClient extends AbstractClient {
     }
 
     @Override
-    public Client getRemoteClusterClient(String clusterAlias) {
-        return remoteClusterService.getRemoteClusterClient(threadPool(), clusterAlias);
+    public Client getRemoteClusterClient(String remoteClusterAlias) {
+        return remoteClusterService.getRemoteClusterClient(threadPool(), remoteClusterAlias);
     }
 }

+ 1 - 1
server/src/main/java/org/elasticsearch/transport/RemoteClusterConnection.java

@@ -71,7 +71,7 @@ final class RemoteClusterConnection implements Closeable {
     /**
      * Updates the skipUnavailable flag that can be dynamically set for each remote cluster
      */
-    void updateSkipUnavailable(boolean skipUnavailable) {
+    void setSkipUnavailable(boolean skipUnavailable) {
         this.skipUnavailable = skipUnavailable;
     }
 

+ 3 - 4
server/src/main/java/org/elasticsearch/transport/RemoteClusterService.java

@@ -224,7 +224,7 @@ public final class RemoteClusterService extends RemoteClusterAware implements Cl
     private synchronized void updateSkipUnavailable(String clusterAlias, Boolean skipUnavailable) {
         RemoteClusterConnection remote = this.remoteClusters.get(clusterAlias);
         if (remote != null) {
-            remote.updateSkipUnavailable(skipUnavailable);
+            remote.setSkipUnavailable(skipUnavailable);
         }
     }
 
@@ -344,9 +344,8 @@ public final class RemoteClusterService extends RemoteClusterAware implements Cl
             throw new IllegalArgumentException(
                 "this node does not have the " + DiscoveryNodeRole.REMOTE_CLUSTER_CLIENT_ROLE.roleName() + " role");
         }
-        Map<String, RemoteClusterConnection> remoteClusters = this.remoteClusters;
         for (String cluster : clusters) {
-            if (remoteClusters.containsKey(cluster) == false) {
+            if (this.remoteClusters.containsKey(cluster) == false) {
                 listener.onFailure(new NoSuchRemoteClusterException(cluster));
                 return;
             }
@@ -356,7 +355,7 @@ public final class RemoteClusterService extends RemoteClusterAware implements Cl
         CountDown countDown = new CountDown(clusters.size());
         Function<String, DiscoveryNode> nullFunction = s -> null;
         for (final String cluster : clusters) {
-            RemoteClusterConnection connection = remoteClusters.get(cluster);
+            RemoteClusterConnection connection = this.remoteClusters.get(cluster);
             connection.collectNodes(new ActionListener<Function<String, DiscoveryNode>>() {
                 @Override
                 public void onResponse(Function<String, DiscoveryNode> nodeLookup) {

+ 4 - 4
server/src/main/java/org/elasticsearch/transport/RemoteConnectionStrategy.java

@@ -227,10 +227,10 @@ public abstract class RemoteConnectionStrategy implements TransportConnectionLis
         boolean runConnect = false;
         final ActionListener<Void> listener =
             ContextPreservingActionListener.wrapPreservingContext(connectListener, transportService.getThreadPool().getThreadContext());
-        boolean closed;
+        boolean isCurrentlyClosed;
         synchronized (mutex) {
-            closed = this.closed.get();
-            if (closed) {
+            isCurrentlyClosed = this.closed.get();
+            if (isCurrentlyClosed) {
                 assert listeners.isEmpty();
             } else {
                 if (listeners.size() >= maxPendingConnectionListeners) {
@@ -243,7 +243,7 @@ public abstract class RemoteConnectionStrategy implements TransportConnectionLis
                 runConnect = listeners.size() == 1;
             }
         }
-        if (closed) {
+        if (isCurrentlyClosed) {
             connectListener.onFailure(new AlreadyClosedException("connect handler is already closed"));
             return;
         }

+ 6 - 6
server/src/main/java/org/elasticsearch/transport/SniffConnectionStrategy.java

@@ -198,22 +198,22 @@ public class SniffConnectionStrategy extends RemoteConnectionStrategy {
         return new SniffModeInfo(configuredSeedNodes, maxNumRemoteConnections, connectionManager.size());
     }
 
-    private void collectRemoteNodes(Iterator<Supplier<DiscoveryNode>> seedNodes, ActionListener<Void> listener) {
+    private void collectRemoteNodes(Iterator<Supplier<DiscoveryNode>> seedNodesSuppliers, ActionListener<Void> listener) {
         if (Thread.currentThread().isInterrupted()) {
             listener.onFailure(new InterruptedException("remote connect thread got interrupted"));
             return;
         }
 
-        if (seedNodes.hasNext()) {
+        if (seedNodesSuppliers.hasNext()) {
             final Consumer<Exception> onFailure = e -> {
                 if (e instanceof ConnectTransportException ||
                     e instanceof IOException ||
                     e instanceof IllegalStateException) {
                     // ISE if we fail the handshake with an version incompatible node
-                    if (seedNodes.hasNext()) {
+                    if (seedNodesSuppliers.hasNext()) {
                         logger.debug(() -> new ParameterizedMessage(
                             "fetching nodes from external cluster [{}] failed moving to next seed node", clusterAlias), e);
-                        collectRemoteNodes(seedNodes, listener);
+                        collectRemoteNodes(seedNodesSuppliers, listener);
                         return;
                     }
                 }
@@ -221,7 +221,7 @@ public class SniffConnectionStrategy extends RemoteConnectionStrategy {
                 listener.onFailure(e);
             };
 
-            final DiscoveryNode seedNode = seedNodes.next().get();
+            final DiscoveryNode seedNode = seedNodesSuppliers.next().get();
             logger.trace("[{}] opening transient connection to seed node: [{}]", clusterAlias, seedNode);
             final StepListener<Transport.Connection> openConnectionStep = new StepListener<>();
             try {
@@ -276,7 +276,7 @@ public class SniffConnectionStrategy extends RemoteConnectionStrategy {
                 ThreadContext threadContext = threadPool.getThreadContext();
                 TransportService.ContextRestoreResponseHandler<ClusterStateResponse> responseHandler = new TransportService
                     .ContextRestoreResponseHandler<>(threadContext.newRestorableContext(false),
-                    new SniffClusterStateResponseHandler(connection, listener, seedNodes));
+                    new SniffClusterStateResponseHandler(connection, listener, seedNodesSuppliers));
                 try (ThreadContext.StoredContext ignore = threadContext.stashContext()) {
                     // we stash any context here since this is an internal execution and should not leak any
                     // existing context information.

+ 7 - 7
server/src/main/java/org/elasticsearch/transport/TcpTransport.java

@@ -99,7 +99,7 @@ public abstract class TcpTransport extends AbstractLifecycleComponent implements
     protected final ThreadPool threadPool;
     protected final PageCacheRecycler pageCacheRecycler;
     protected final NetworkService networkService;
-    protected final Set<ProfileSettings> profileSettings;
+    protected final Set<ProfileSettings> profileSettingsSet;
     private final CircuitBreakerService circuitBreakerService;
 
     private final ConcurrentMap<String, BoundTransportAddress> profileBoundAddresses = newConcurrentMap();
@@ -124,7 +124,7 @@ public abstract class TcpTransport extends AbstractLifecycleComponent implements
                         CircuitBreakerService circuitBreakerService, NamedWriteableRegistry namedWriteableRegistry,
                         NetworkService networkService) {
         this.settings = settings;
-        this.profileSettings = getProfileSettings(settings);
+        this.profileSettingsSet = getProfileSettings(settings);
         this.version = version;
         this.threadPool = threadPool;
         this.pageCacheRecycler = pageCacheRecycler;
@@ -417,9 +417,9 @@ public abstract class TcpTransport extends AbstractLifecycleComponent implements
         String[] boundAddressesHostStrings = new String[boundAddresses.size()];
         TransportAddress[] transportBoundAddresses = new TransportAddress[boundAddresses.size()];
         for (int i = 0; i < boundAddresses.size(); i++) {
-            InetSocketAddress boundAddress = boundAddresses.get(i);
-            boundAddressesHostStrings[i] = boundAddress.getHostString();
-            transportBoundAddresses[i] = new TransportAddress(boundAddress);
+            InetSocketAddress nextAddress = boundAddresses.get(i);
+            boundAddressesHostStrings[i] = nextAddress.getHostString();
+            transportBoundAddresses[i] = new TransportAddress(nextAddress);
         }
 
         List<String> publishHosts = profileSettings.publishHosts;
@@ -928,10 +928,10 @@ public abstract class TcpTransport extends AbstractLifecycleComponent implements
             if (countDown.countDown()) {
                 final TcpChannel handshakeChannel = channels.get(0);
                 try {
-                    executeHandshake(node, handshakeChannel, connectionProfile, ActionListener.wrap(version -> {
+                    executeHandshake(node, handshakeChannel, connectionProfile, ActionListener.wrap(responseVersion -> {
                         final long connectionId = outboundConnectionCount.incrementAndGet();
                         logger.debug("opened transport connection [{}] to [{}] using channels [{}]", connectionId, node, channels);
-                        NodeChannels nodeChannels = new NodeChannels(node, channels, connectionProfile, version);
+                        NodeChannels nodeChannels = new NodeChannels(node, channels, connectionProfile, responseVersion);
                         long relativeMillisTime = threadPool.relativeTimeInMillis();
                         nodeChannels.channels.forEach(ch -> {
                             // Mark the channel init time

+ 4 - 4
server/src/main/java/org/elasticsearch/transport/TransportHandshaker.java

@@ -118,12 +118,12 @@ final class TransportHandshaker {
         @Override
         public void handleResponse(HandshakeResponse response) {
             if (isDone.compareAndSet(false, true)) {
-                Version version = response.responseVersion;
-                if (currentVersion.isCompatible(version) == false) {
-                    listener.onFailure(new IllegalStateException("Received message from unsupported version: [" + version
+                Version responseVersion = response.responseVersion;
+                if (currentVersion.isCompatible(responseVersion) == false) {
+                    listener.onFailure(new IllegalStateException("Received message from unsupported version: [" + responseVersion
                         + "] minimal compatible version is: [" + currentVersion.minimumCompatibilityVersion() + "]"));
                 } else {
-                    listener.onResponse(version);
+                    listener.onResponse(responseVersion);
                 }
             }
         }

+ 2 - 2
server/src/main/java/org/elasticsearch/transport/TransportMessage.java

@@ -17,8 +17,8 @@ public abstract class TransportMessage implements Writeable, RefCounted {
 
     private TransportAddress remoteAddress;
 
-    public void remoteAddress(TransportAddress remoteAddress) {
-        this.remoteAddress = remoteAddress;
+    public void remoteAddress(TransportAddress address) {
+        this.remoteAddress = address;
     }
 
     public TransportAddress remoteAddress() {

+ 2 - 2
server/src/main/java/org/elasticsearch/transport/TransportService.java

@@ -1159,8 +1159,8 @@ public class TransportService extends AbstractLifecycleComponent
             return getClass().getName() + "/" + delegate.toString();
         }
 
-        void setTimeoutHandler(TimeoutHandler handler) {
-            this.handler = handler;
+        void setTimeoutHandler(TimeoutHandler timeoutHandler) {
+            this.handler = timeoutHandler;
         }
 
     }

+ 26 - 25
server/src/main/java/org/elasticsearch/watcher/FileWatcher.java

@@ -26,23 +26,24 @@ import java.util.Arrays;
 public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
 
     private FileObserver rootFileObserver;
-    private Path file;
+    private final Path path;
 
     private static final Logger logger = LogManager.getLogger(FileWatcher.class);
 
     /**
      * Creates new file watcher on the given directory
+     * @param path the directory to watch
      */
-    public FileWatcher(Path file) {
-        this.file = file;
-        rootFileObserver = new FileObserver(file);
+    public FileWatcher(Path path) {
+        this.path = path;
+        rootFileObserver = new FileObserver(path);
     }
 
     /**
      * Clears any state with the FileWatcher, making all files show up as new
      */
     public void clearState() {
-        rootFileObserver = new FileObserver(file);
+        rootFileObserver = new FileObserver(path);
         try {
             rootFileObserver.init(false);
         } catch (IOException e) {
@@ -60,18 +61,18 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
         rootFileObserver.checkAndNotify();
     }
 
-    private static FileObserver[] EMPTY_DIRECTORY = new FileObserver[0];
+    private static final FileObserver[] EMPTY_DIRECTORY = new FileObserver[0];
 
     private class FileObserver {
-        private Path file;
+        private final Path path;
         private boolean exists;
         private long length;
         private long lastModified;
         private boolean isDirectory;
         private FileObserver[] children;
 
-        FileObserver(Path file) {
-            this.file = file;
+        FileObserver(Path path) {
+            this.path = path;
         }
 
         public void checkAndNotify() throws IOException {
@@ -80,10 +81,10 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
             long prevLength = length;
             long prevLastModified = lastModified;
 
-            exists = Files.exists(file);
+            exists = Files.exists(path);
             // TODO we might use the new NIO2 API to get real notification?
             if (exists) {
-                BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
+                BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
                 isDirectory = attributes.isDirectory();
                 if (isDirectory) {
                     length = 0;
@@ -144,9 +145,9 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
         }
 
         private void init(boolean initial) throws IOException {
-            exists = Files.exists(file);
+            exists = Files.exists(path);
             if (exists) {
-                BasicFileAttributes attributes = Files.readAttributes(file, BasicFileAttributes.class);
+                BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
                 isDirectory = attributes.isDirectory();
                 if (isDirectory) {
                     onDirectoryCreated(initial);
@@ -165,7 +166,7 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
         }
 
         private Path[] listFiles() throws IOException {
-            final Path[] files = FileSystemUtils.files(file);
+            final Path[] files = FileSystemUtils.files(path);
             Arrays.sort(files);
             return files;
         }
@@ -173,11 +174,11 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
         private FileObserver[] listChildren(boolean initial) throws IOException {
             Path[] files = listFiles();
             if (CollectionUtils.isEmpty(files) == false) {
-                FileObserver[] children = new FileObserver[files.length];
+                FileObserver[] childObservers = new FileObserver[files.length];
                 for (int i = 0; i < files.length; i++) {
-                    children[i] = createChild(files[i], initial);
+                    childObservers[i] = createChild(files[i], initial);
                 }
-                return children;
+                return childObservers;
             } else {
                 return EMPTY_DIRECTORY;
             }
@@ -197,7 +198,7 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
                     } else if (child >= children.length) {
                         compare = 1;
                     } else {
-                        compare = children[child].file.compareTo(files[file]);
+                        compare = children[child].path.compareTo(files[file]);
                     }
 
                     if (compare  == 0) {
@@ -243,9 +244,9 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
             for (FileChangesListener listener : listeners()) {
                 try {
                     if (initial) {
-                        listener.onFileInit(file);
+                        listener.onFileInit(path);
                     } else {
-                        listener.onFileCreated(file);
+                        listener.onFileCreated(path);
                     }
                 } catch (Exception e) {
                     logger.warn("cannot notify file changes listener", e);
@@ -256,7 +257,7 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
         private void onFileDeleted() {
             for (FileChangesListener listener : listeners()) {
                 try {
-                    listener.onFileDeleted(file);
+                    listener.onFileDeleted(path);
                 } catch (Exception e) {
                     logger.warn("cannot notify file changes listener", e);
                 }
@@ -266,7 +267,7 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
         private void onFileChanged() {
             for (FileChangesListener listener : listeners()) {
                 try {
-                    listener.onFileChanged(file);
+                    listener.onFileChanged(path);
                 } catch (Exception e) {
                     logger.warn("cannot notify file changes listener", e);
                 }
@@ -278,9 +279,9 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
             for (FileChangesListener listener : listeners()) {
                 try {
                     if (initial) {
-                        listener.onDirectoryInit(file);
+                        listener.onDirectoryInit(path);
                     } else {
-                        listener.onDirectoryCreated(file);
+                        listener.onDirectoryCreated(path);
                     }
                 } catch (Exception e) {
                     logger.warn("cannot notify file changes listener", e);
@@ -296,7 +297,7 @@ public class FileWatcher extends AbstractResourceWatcher<FileChangesListener> {
             }
             for (FileChangesListener listener : listeners()) {
                 try {
-                    listener.onDirectoryDeleted(file);
+                    listener.onDirectoryDeleted(path);
                 } catch (Exception e) {
                     logger.warn("cannot notify file changes listener", e);
                 }

+ 1 - 1
server/src/test/java/org/elasticsearch/transport/RemoteClusterServiceTests.java

@@ -832,7 +832,7 @@ public class RemoteClusterServiceTests extends ESTestCase {
 
     public static void updateSkipUnavailable(RemoteClusterService service, String clusterAlias, boolean skipUnavailable) {
         RemoteClusterConnection connection = service.getRemoteClusterConnection(clusterAlias);
-        connection.updateSkipUnavailable(skipUnavailable);
+        connection.setSkipUnavailable(skipUnavailable);
     }
 
     public static void addConnectionListener(RemoteClusterService service, TransportConnectionListener listener) {

+ 1 - 1
test/framework/src/main/java/org/elasticsearch/transport/nio/MockNioTransport.java

@@ -115,7 +115,7 @@ public class MockNioTransport extends TcpTransport {
 
             if (NetworkService.NETWORK_SERVER.get(settings)) {
                 // loop through all profiles and start them up, special handling for default one
-                for (ProfileSettings profileSettings : profileSettings) {
+                for (ProfileSettings profileSettings : profileSettingsSet) {
                     String profileName = profileSettings.profileName;
                     MockTcpChannelFactory factory = new MockTcpChannelFactory(false, profileSettings, profileName);
                     profileToChannelFactory.putIfAbsent(profileName, factory);