blob: 9706e0ef17ffaf27babae926bf72ffc33adf8d7a [file] [log] [blame]
Madan Jampanib5d72d52015-04-03 16:53:50 -07001/*
2 * Copyright 2015 Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.cli.net;
17
18import java.util.Map;
19
20import org.apache.karaf.shell.commands.Command;
21import org.onosproject.cli.AbstractShellCommand;
22import org.onosproject.store.service.StorageAdminService;
23
24import com.fasterxml.jackson.databind.JsonNode;
25import com.fasterxml.jackson.databind.ObjectMapper;
26import com.fasterxml.jackson.databind.node.ArrayNode;
27import com.fasterxml.jackson.databind.node.ObjectNode;
28
29/**
30 * Command to list the various counters in the system.
31 */
32@Command(scope = "onos", name = "counters",
33 description = "Lists information about atomic counters in the system")
34public class CountersListCommand extends AbstractShellCommand {
35
Madan Jampani3e033bd2015-04-08 13:03:49 -070036 private static final String FMT = "name=%s value=%d";
Madan Jampanib5d72d52015-04-03 16:53:50 -070037
38 /**
39 * Displays counters as text.
40 *
Charles M.C. Chan6f5bdc62015-04-22 01:21:09 +080041 * @param counters counter info
Madan Jampanib5d72d52015-04-03 16:53:50 -070042 */
43 private void displayCounters(Map<String, Long> counters) {
Madan Jampani3e033bd2015-04-08 13:03:49 -070044 counters.forEach((name, value) -> print(FMT, name, value));
Madan Jampanib5d72d52015-04-03 16:53:50 -070045 }
46
47 /**
48 * Converts info for counters into a JSON object.
49 *
50 * @param counters counter info
51 */
52 private JsonNode json(Map<String, Long> counters) {
53 ObjectMapper mapper = new ObjectMapper();
54 ArrayNode jsonCounters = mapper.createArrayNode();
55
56 // Create a JSON node for each counter
57 counters.forEach((name, value) -> {
58 ObjectNode jsonCounter = mapper.createObjectNode();
59 jsonCounter.put("name", name)
60 .put("value", value);
61 jsonCounters.add(jsonCounter);
62 });
63
64 return jsonCounters;
65 }
66
67 @Override
68 protected void execute() {
69 StorageAdminService storageAdminService = get(StorageAdminService.class);
70 Map<String, Long> counters = storageAdminService.getCounters();
71 if (outputJson()) {
72 print("%s", json(counters));
73 } else {
74 displayCounters(counters);
75 }
76 }
77}