Prevent MetaClient LeaderElectionClient isLeader NPE before joining pool (#2798)
Prevent MetaClient LeaderElectionClient isLeader NPE before joining pool
diff --git a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
index 3bcf09c..373d360 100644
--- a/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
+++ b/meta-client/src/main/java/org/apache/helix/metaclient/recipes/leaderelection/LeaderElectionClient.java
@@ -121,7 +121,8 @@
* Returns true if current participant is the current leadership.
*/
public boolean isLeader(String leaderPath) {
- return getLeader(leaderPath).equalsIgnoreCase(_participant);
+ String leader = getLeader(leaderPath);
+ return leader != null && leader.equalsIgnoreCase(_participant);
}
/**
diff --git a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
index 7591762..2486436 100644
--- a/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
+++ b/meta-client/src/test/java/org/apache/helix/metaclient/recipes/leaderelection/TestLeaderElection.java
@@ -41,7 +41,21 @@
}
}
+ // Test that calling isLeader before client joins LeaderElectionParticipantPool returns false and does not throw NPE
@Test
+ public void testIsLeaderBeforeJoiningParticipantPool() throws Exception {
+ String leaderPath = LEADER_PATH + "/testIsLeaderBeforeJoiningPool";
+ LeaderElectionClient clt1 = createLeaderElectionClient(PARTICIPANT_NAME1);
+ try {
+ boolean isLeader = clt1.isLeader(leaderPath);
+ Assert.assertFalse(isLeader, "Expected isLeader to return false before joining participant pool");
+ } catch (NullPointerException npe) {
+ Assert.fail("isLeader threw NPE before joining participant pool: " + npe.getMessage());
+ }
+ clt1.close();
+ }
+
+ @Test (dependsOnMethods = "testIsLeaderBeforeJoiningParticipantPool")
public void testAcquireLeadership() throws Exception {
System.out.println("START TestLeaderElection.testAcquireLeadership");
String leaderPath = LEADER_PATH + "/testAcquireLeadership";