Skip to content

Commit 6fc8166

Browse files
authored
Checkstyle shadows vars pt8 (#81147) (#81250)
Part of #19752. Fix more instances where local variable names were shadowing field names. Also expand the possible method names that are skipped when checking for shadowed vars, and allow shadowed vars in builder classes.
1 parent c23f8f6 commit 6fc8166

File tree

58 files changed

+254
-224
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+254
-224
lines changed

build-conventions/src/main/java/org/elasticsearch/gradle/internal/checkstyle/HiddenFieldCheck.java

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import com.puppycrawl.tools.checkstyle.utils.TokenUtil;
3131

3232
import java.util.HashSet;
33+
import java.util.List;
3334
import java.util.Locale;
3435
import java.util.Objects;
3536
import java.util.Set;
@@ -342,24 +343,33 @@ private boolean isSetterMethod(DetailAST aMethodAST, String aName) {
342343
boolean isSetterMethod = false;
343344

344345
// ES also allows setters with the same name as a property, and builder-style settings that start with "with".
345-
if (("set" + capitalize(aName)).equals(methodName) || ("with" + capitalize(aName)).equals(methodName) || aName.equals(methodName)) {
346+
final List<String> possibleSetterNames = List.of(
347+
"set" + capitalize(aName, true),
348+
"set" + capitalize(aName, false),
349+
"with" + capitalize(aName, true),
350+
"with" + capitalize(aName, false),
351+
aName
352+
);
353+
354+
if (possibleSetterNames.contains(methodName)) {
346355
// method name did match set${Name}(${anyType} ${aName})
347356
// where ${Name} is capitalized version of ${aName}
348357
// therefore this method is potentially a setter
349358
final DetailAST typeAST = aMethodAST.findFirstToken(TokenTypes.TYPE);
350359
final String returnType = typeAST.getFirstChild().getText();
351-
if (typeAST.findFirstToken(TokenTypes.LITERAL_VOID) != null || setterCanReturnItsClass && frame.isEmbeddedIn(returnType)) {
352-
// this method has signature
353-
//
354-
// void set${Name}(${anyType} ${name})
355-
//
356-
// and therefore considered to be a setter
357-
//
358-
// or
359-
//
360-
// return type is not void, but it is the same as the class
361-
// where method is declared and and mSetterCanReturnItsClass
362-
// is set to true
360+
361+
// The method is named `setFoo`, `withFoo`, or just `foo` and returns void
362+
final boolean returnsVoid = typeAST.findFirstToken(TokenTypes.LITERAL_VOID) != null;
363+
364+
// Or the method is named as above, and returns the class type or a builder type.
365+
// It ought to be possible to see if we're in a `${returnType}.Builder`, but for some reason the parse
366+
// tree has `returnType` as `.` when the current class is `Builder` so instead assume that a class called `Builder` is OK.
367+
final boolean returnsSelf = setterCanReturnItsClass && frame.isEmbeddedIn(returnType);
368+
369+
final boolean returnsBuilder = setterCanReturnItsClass
370+
&& (frame.isEmbeddedIn(returnType + "Builder") || (frame.isEmbeddedIn("Builder")));
371+
372+
if (returnsVoid || returnsSelf || returnsBuilder) {
363373
isSetterMethod = true;
364374
}
365375
}
@@ -374,13 +384,13 @@ private boolean isSetterMethod(DetailAST aMethodAST, String aName) {
374384
* @param name a property name
375385
* @return capitalized property name
376386
*/
377-
private static String capitalize(final String name) {
387+
private static String capitalize(final String name, boolean javaBeanCompliant) {
378388
String setterName = name;
379389
// we should not capitalize the first character if the second
380390
// one is a capital one, since according to JavaBeans spec
381391
// setXYzz() is a setter for XYzz property, not for xYzz one.
382-
// @pugnascotia: unless the first char is 'x'.
383-
if (name.length() == 1 || (Character.isUpperCase(name.charAt(1)) == false || name.charAt(0) == 'x')) {
392+
// @pugnascotia: this is unhelpful in the Elasticsearch codebase. We have e.g. xContent -> setXContent, or nNeighbors -> nNeighbors.
393+
if (name.length() == 1 || (javaBeanCompliant == false || Character.isUpperCase(name.charAt(1)) == false)) {
384394
setterName = name.substring(0, 1).toUpperCase(Locale.ENGLISH) + name.substring(1);
385395
}
386396
return setterName;

server/src/internalClusterTest/java/org/elasticsearch/action/IndicesRequestIT.java

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -282,31 +282,31 @@ public void testBulk() {
282282
String[] bulkShardActions = new String[] { BulkAction.NAME + "[s][p]", BulkAction.NAME + "[s][r]" };
283283
interceptTransportActions(bulkShardActions);
284284

285-
List<String> indices = new ArrayList<>();
285+
List<String> indicesOrAliases = new ArrayList<>();
286286
BulkRequest bulkRequest = new BulkRequest();
287287
int numIndexRequests = iterations(1, 10);
288288
for (int i = 0; i < numIndexRequests; i++) {
289289
String indexOrAlias = randomIndexOrAlias();
290290
bulkRequest.add(new IndexRequest(indexOrAlias, "type", "id").source(Requests.INDEX_CONTENT_TYPE, "field", "value"));
291-
indices.add(indexOrAlias);
291+
indicesOrAliases.add(indexOrAlias);
292292
}
293293
int numDeleteRequests = iterations(1, 10);
294294
for (int i = 0; i < numDeleteRequests; i++) {
295295
String indexOrAlias = randomIndexOrAlias();
296296
bulkRequest.add(new DeleteRequest(indexOrAlias, "type", "id"));
297-
indices.add(indexOrAlias);
297+
indicesOrAliases.add(indexOrAlias);
298298
}
299299
int numUpdateRequests = iterations(1, 10);
300300
for (int i = 0; i < numUpdateRequests; i++) {
301301
String indexOrAlias = randomIndexOrAlias();
302302
bulkRequest.add(new UpdateRequest(indexOrAlias, "type", "id").doc(Requests.INDEX_CONTENT_TYPE, "field1", "value1"));
303-
indices.add(indexOrAlias);
303+
indicesOrAliases.add(indexOrAlias);
304304
}
305305

306306
internalCluster().coordOnlyNodeClient().bulk(bulkRequest).actionGet();
307307

308308
clearInterceptedActions();
309-
assertIndicesSubset(indices, bulkShardActions);
309+
assertIndicesSubset(indicesOrAliases, bulkShardActions);
310310
}
311311

312312
public void testGet() {
@@ -346,36 +346,36 @@ public void testMultiTermVector() {
346346
String multiTermVectorsShardAction = MultiTermVectorsAction.NAME + "[shard][s]";
347347
interceptTransportActions(multiTermVectorsShardAction);
348348

349-
List<String> indices = new ArrayList<>();
349+
List<String> indicesOrAliases = new ArrayList<>();
350350
MultiTermVectorsRequest multiTermVectorsRequest = new MultiTermVectorsRequest();
351351
int numDocs = iterations(1, 30);
352352
for (int i = 0; i < numDocs; i++) {
353353
String indexOrAlias = randomIndexOrAlias();
354354
multiTermVectorsRequest.add(indexOrAlias, "type", Integer.toString(i));
355-
indices.add(indexOrAlias);
355+
indicesOrAliases.add(indexOrAlias);
356356
}
357357
internalCluster().coordOnlyNodeClient().multiTermVectors(multiTermVectorsRequest).actionGet();
358358

359359
clearInterceptedActions();
360-
assertIndicesSubset(indices, multiTermVectorsShardAction);
360+
assertIndicesSubset(indicesOrAliases, multiTermVectorsShardAction);
361361
}
362362

363363
public void testMultiGet() {
364364
String multiGetShardAction = MultiGetAction.NAME + "[shard][s]";
365365
interceptTransportActions(multiGetShardAction);
366366

367-
List<String> indices = new ArrayList<>();
367+
List<String> indicesOrAliases = new ArrayList<>();
368368
MultiGetRequest multiGetRequest = new MultiGetRequest();
369369
int numDocs = iterations(1, 30);
370370
for (int i = 0; i < numDocs; i++) {
371371
String indexOrAlias = randomIndexOrAlias();
372372
multiGetRequest.add(indexOrAlias, "type", Integer.toString(i));
373-
indices.add(indexOrAlias);
373+
indicesOrAliases.add(indexOrAlias);
374374
}
375375
internalCluster().coordOnlyNodeClient().multiGet(multiGetRequest).actionGet();
376376

377377
clearInterceptedActions();
378-
assertIndicesSubset(indices, multiGetShardAction);
378+
assertIndicesSubset(indicesOrAliases, multiGetShardAction);
379379
}
380380

381381
public void testFlush() {
@@ -389,9 +389,9 @@ public void testFlush() {
389389
internalCluster().coordOnlyNodeClient().admin().indices().flush(flushRequest).actionGet();
390390

391391
clearInterceptedActions();
392-
String[] indices = TestIndexNameExpressionResolver.newInstance()
392+
String[] concreteIndexNames = TestIndexNameExpressionResolver.newInstance()
393393
.concreteIndexNames(client().admin().cluster().prepareState().get().getState(), flushRequest);
394-
assertIndicesSubset(Arrays.asList(indices), indexShardActions);
394+
assertIndicesSubset(Arrays.asList(concreteIndexNames), indexShardActions);
395395
}
396396

397397
public void testForceMerge() {
@@ -416,9 +416,9 @@ public void testRefresh() {
416416
internalCluster().coordOnlyNodeClient().admin().indices().refresh(refreshRequest).actionGet();
417417

418418
clearInterceptedActions();
419-
String[] indices = TestIndexNameExpressionResolver.newInstance()
419+
String[] concreteIndexNames = TestIndexNameExpressionResolver.newInstance()
420420
.concreteIndexNames(client().admin().cluster().prepareState().get().getState(), refreshRequest);
421-
assertIndicesSubset(Arrays.asList(indices), indexShardActions);
421+
assertIndicesSubset(Arrays.asList(concreteIndexNames), indexShardActions);
422422
}
423423

424424
public void testClearCache() {
@@ -675,21 +675,21 @@ private String randomIndexOrAlias() {
675675

676676
private String[] randomIndicesOrAliases() {
677677
int count = randomIntBetween(1, indices.size() * 2); // every index has an alias
678-
String[] indices = new String[count];
678+
String[] randomNames = new String[count];
679679
for (int i = 0; i < count; i++) {
680-
indices[i] = randomIndexOrAlias();
680+
randomNames[i] = randomIndexOrAlias();
681681
}
682-
return indices;
682+
return randomNames;
683683
}
684684

685685
private String[] randomUniqueIndicesOrAliases() {
686686
String[] uniqueIndices = randomUniqueIndices();
687-
String[] indices = new String[uniqueIndices.length];
687+
String[] randomNames = new String[uniqueIndices.length];
688688
int i = 0;
689689
for (String index : uniqueIndices) {
690-
indices[i++] = randomBoolean() ? index + "-alias" : index;
690+
randomNames[i++] = randomBoolean() ? index + "-alias" : index;
691691
}
692-
return indices;
692+
return randomNames;
693693
}
694694

695695
private String[] randomUniqueIndices() {
@@ -776,8 +776,8 @@ synchronized List<TransportRequest> consumeRequests(String action) {
776776
return requests.remove(action);
777777
}
778778

779-
synchronized void interceptTransportActions(String... actions) {
780-
Collections.addAll(this.actions, actions);
779+
synchronized void interceptTransportActions(String... transportActions) {
780+
Collections.addAll(this.actions, transportActions);
781781
}
782782

783783
synchronized void clearInterceptedActions() {

x-pack/plugin/analytics/src/test/java/org/elasticsearch/xpack/analytics/topmetrics/InternalTopMetricsTests.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ private InternalTopMetrics createTestInstance(
337337
@Override
338338
protected InternalTopMetrics mutateInstance(InternalTopMetrics instance) throws IOException {
339339
String name = instance.getName();
340-
SortOrder sortOrder = instance.getSortOrder();
340+
SortOrder instanceSortOrder = instance.getSortOrder();
341341
List<String> metricNames = instance.getMetricNames();
342342
int size = instance.getSize();
343343
List<InternalTopMetrics.TopMetric> topMetrics = instance.getTopMetrics();
@@ -346,7 +346,7 @@ protected InternalTopMetrics mutateInstance(InternalTopMetrics instance) throws
346346
name = randomAlphaOfLength(6);
347347
break;
348348
case 1:
349-
sortOrder = sortOrder == SortOrder.ASC ? SortOrder.DESC : SortOrder.ASC;
349+
instanceSortOrder = instanceSortOrder == SortOrder.ASC ? SortOrder.DESC : SortOrder.ASC;
350350
Collections.reverse(topMetrics);
351351
break;
352352
case 2:
@@ -372,7 +372,7 @@ protected InternalTopMetrics mutateInstance(InternalTopMetrics instance) throws
372372
default:
373373
throw new IllegalArgumentException("bad mutation");
374374
}
375-
return new InternalTopMetrics(name, sortOrder, metricNames, size, topMetrics, instance.getMetadata());
375+
return new InternalTopMetrics(name, instanceSortOrder, metricNames, size, topMetrics, instance.getMetadata());
376376
}
377377

378378
/**

x-pack/plugin/core/src/main/java/org/elasticsearch/license/License.java

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -555,11 +555,11 @@ public XContentBuilder toInnerXContent(XContentBuilder builder, Params params) t
555555
builder.humanReadable(true);
556556
}
557557
}
558-
final int version;
558+
final int licenseVersion;
559559
if (params.param(LICENSE_VERSION_MODE) != null && restViewMode) {
560-
version = Integer.parseInt(params.param(LICENSE_VERSION_MODE));
560+
licenseVersion = Integer.parseInt(params.param(LICENSE_VERSION_MODE));
561561
} else {
562-
version = this.version;
562+
licenseVersion = this.version;
563563
}
564564
if (restViewMode) {
565565
builder.field(Fields.STATUS, status().label());
@@ -569,19 +569,19 @@ public XContentBuilder toInnerXContent(XContentBuilder builder, Params params) t
569569
final String bwcType = hideEnterprise && "enterprise".equals(type) ? "platinum" : type;
570570
builder.field(Fields.TYPE, bwcType);
571571

572-
if (version == VERSION_START) {
572+
if (licenseVersion == VERSION_START) {
573573
builder.field(Fields.SUBSCRIPTION_TYPE, subscriptionType);
574574
}
575575
builder.timeField(Fields.ISSUE_DATE_IN_MILLIS, Fields.ISSUE_DATE, issueDate);
576-
if (version == VERSION_START) {
576+
if (licenseVersion == VERSION_START) {
577577
builder.field(Fields.FEATURE, feature);
578578
}
579579

580580
if (expiryDate != LicenseService.BASIC_SELF_GENERATED_LICENSE_EXPIRATION_MILLIS) {
581581
builder.timeField(Fields.EXPIRY_DATE_IN_MILLIS, Fields.EXPIRY_DATE, expiryDate);
582582
}
583583

584-
if (version >= VERSION_ENTERPRISE) {
584+
if (licenseVersion >= VERSION_ENTERPRISE) {
585585
builder.field(Fields.MAX_NODES, maxNodes == -1 ? null : maxNodes);
586586
builder.field(Fields.MAX_RESOURCE_UNITS, maxResourceUnits == -1 ? null : maxResourceUnits);
587587
} else if (hideEnterprise && maxNodes == -1) {
@@ -598,7 +598,7 @@ public XContentBuilder toInnerXContent(XContentBuilder builder, Params params) t
598598
if (restViewMode) {
599599
builder.humanReadable(previouslyHumanReadable);
600600
}
601-
if (version >= VERSION_START_DATE) {
601+
if (licenseVersion >= VERSION_START_DATE) {
602602
builder.timeField(Fields.START_DATE_IN_MILLIS, Fields.START_DATE, startDate);
603603
}
604604
return builder;
@@ -921,7 +921,7 @@ public Builder startDate(long startDate) {
921921
return this;
922922
}
923923

924-
public Builder fromLicenseSpec(License license, String signature) {
924+
public Builder fromLicenseSpec(License license, String licenseSignature) {
925925
return uid(license.uid()).version(license.version())
926926
.issuedTo(license.issuedTo())
927927
.issueDate(license.issueDate())
@@ -933,7 +933,7 @@ public Builder fromLicenseSpec(License license, String signature) {
933933
.maxResourceUnits(license.maxResourceUnits())
934934
.expiryDate(license.expiryDate())
935935
.issuer(license.issuer())
936-
.signature(signature);
936+
.signature(licenseSignature);
937937
}
938938

939939
/**

x-pack/plugin/core/src/main/java/org/elasticsearch/license/LicenseService.java

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,8 +109,8 @@ public class LicenseService extends AbstractLifecycleComponent implements Cluste
109109
/**
110110
* Currently active license
111111
*/
112-
private final AtomicReference<License> currentLicense = new AtomicReference<>();
113-
private SchedulerEngine scheduler;
112+
private final AtomicReference<License> currentLicenseHolder = new AtomicReference<>();
113+
private final SchedulerEngine scheduler;
114114
private final Clock clock;
115115

116116
/**
@@ -447,7 +447,7 @@ protected void doStop() throws ElasticsearchException {
447447
clusterService.removeListener(this);
448448
scheduler.stop();
449449
// clear current license
450-
currentLicense.set(null);
450+
currentLicenseHolder.set(null);
451451
}
452452

453453
@Override
@@ -567,9 +567,9 @@ private void onUpdate(final LicensesMetadata currentLicensesMetadata) {
567567
// license can be null if the trial license is yet to be auto-generated
568568
// in this case, it is a no-op
569569
if (license != null) {
570-
final License previousLicense = currentLicense.get();
570+
final License previousLicense = currentLicenseHolder.get();
571571
if (license.equals(previousLicense) == false) {
572-
currentLicense.set(license);
572+
currentLicenseHolder.set(license);
573573
license.setOperationModeFileWatcher(operationModeFileWatcher);
574574
scheduler.add(new SchedulerEngine.Job(LICENSE_JOB, nextLicenseCheck(license)));
575575
for (ExpirationCallback expirationCallback : expirationCallbacks) {

x-pack/plugin/core/src/main/java/org/elasticsearch/license/Licensing.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ public Licensing(Settings settings) {
7575

7676
@Override
7777
public List<RestHandler> getRestHandlers(
78-
Settings settings,
78+
Settings unused,
7979
RestController restController,
8080
ClusterSettings clusterSettings,
8181
IndexScopedSettings indexScopedSettings,

x-pack/plugin/core/src/main/java/org/elasticsearch/license/StartBasicClusterTask.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,9 +73,9 @@ public ClusterState execute(ClusterState currentState) throws Exception {
7373
if (shouldGenerateNewBasicLicense(currentLicense)) {
7474
License selfGeneratedLicense = generateBasicLicense(currentState);
7575
if (request.isAcknowledged() == false && currentLicense != null) {
76-
Map<String, String[]> ackMessages = LicenseService.getAckMessages(selfGeneratedLicense, currentLicense);
77-
if (ackMessages.isEmpty() == false) {
78-
this.ackMessages.set(ackMessages);
76+
Map<String, String[]> ackMessageMap = LicenseService.getAckMessages(selfGeneratedLicense, currentLicense);
77+
if (ackMessageMap.isEmpty() == false) {
78+
this.ackMessages.set(ackMessageMap);
7979
return currentState;
8080
}
8181
}

0 commit comments

Comments
 (0)