Ray Milkey
Committed by Gerrit Code Review

ONOS-1219 - Add JSON output to the leaders command

Change-Id: I180b39c16dcbc9d71f857507c1f04ed01e11a240
......@@ -24,6 +24,10 @@ import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.cluster.Leadership;
import org.onosproject.cluster.LeadershipService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
/**
* Prints the leader for every topic.
*/
......@@ -33,16 +37,10 @@ public class LeaderCommand extends AbstractShellCommand {
private static final String FMT = "%-20s | %-15s | %-6s | %-10s |";
@Override
protected void execute() {
LeadershipService leaderService = get(LeadershipService.class);
Map<String, Leadership> leaderBoard = leaderService.getLeaderBoard();
print("--------------------------------------------------------------");
print(FMT, "Topic", "Leader", "Epoch", "Elected");
print("--------------------------------------------------------------");
Comparator<Leadership> leadershipComparator =
/**
* Compares leaders, sorting by toString() output.
*/
private Comparator<Leadership> leadershipComparator =
(e1, e2) -> {
if (e1.leader() == null && e2.leader() == null) {
return 0;
......@@ -56,6 +54,16 @@ public class LeaderCommand extends AbstractShellCommand {
return e1.leader().toString().compareTo(e2.leader().toString());
};
/**
* Displays text representing the leaders.
*
* @param leaderBoard map of leaders
*/
private void displayLeaders(Map<String, Leadership> leaderBoard) {
print("--------------------------------------------------------------");
print(FMT, "Topic", "Leader", "Epoch", "Elected");
print("--------------------------------------------------------------");
leaderBoard.values()
.stream()
.sorted(leadershipComparator)
......@@ -66,4 +74,39 @@ public class LeaderCommand extends AbstractShellCommand {
Tools.timeAgo(l.electedTime())));
print("--------------------------------------------------------------");
}
/**
* Returns JSON node representing the leaders.
*
* @param leaderBoard map of leaders
*/
private JsonNode json(Map<String, Leadership> leaderBoard) {
ObjectMapper mapper = new ObjectMapper();
ArrayNode result = mapper.createArrayNode();
leaderBoard.values()
.stream()
.sorted(leadershipComparator)
.forEach(l ->
result.add(
mapper.createObjectNode()
.put("topic", l.topic())
.put("leader", l.leader().toString())
.put("epoch", l.epoch())
.put("electedTime", Tools.timeAgo(l.electedTime()))));
return result;
}
@Override
protected void execute() {
LeadershipService leaderService = get(LeadershipService.class);
Map<String, Leadership> leaderBoard = leaderService.getLeaderBoard();
if (outputJson()) {
print("%s", json(leaderBoard));
} else {
displayLeaders(leaderBoard);
}
}
}
......