Potential Null Pointer Exception fix for Cpman, Groups , Flows and Mastership API

Change-Id: I5720152a66855dd2f9f20b01da8e2dc6ee24fa7f
diff --git a/apps/cpman/app/src/main/java/org/onosproject/cpman/rest/ControlMetricsWebResource.java b/apps/cpman/app/src/main/java/org/onosproject/cpman/rest/ControlMetricsWebResource.java
index 59dfee6..4b6b406 100644
--- a/apps/cpman/app/src/main/java/org/onosproject/cpman/rest/ControlMetricsWebResource.java
+++ b/apps/cpman/app/src/main/java/org/onosproject/cpman/rest/ControlMetricsWebResource.java
@@ -50,12 +50,6 @@
 @Path("controlmetrics")
 public class ControlMetricsWebResource extends AbstractWebResource {
 
-    private final ControlPlaneMonitorService monitorService =
-            get(ControlPlaneMonitorService.class);
-    private final ClusterService clusterService = get(ClusterService.class);
-    private final NodeId localNodeId = clusterService.getLocalNode().id();
-    private final ObjectNode root = mapper().createObjectNode();
-
     /**
      * Returns control message metrics of all devices.
      *
@@ -66,7 +60,10 @@
     @Path("messages")
     @Produces(MediaType.APPLICATION_JSON)
     public Response controlMessageMetrics() {
-
+        ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        ClusterService clusterService = get(ClusterService.class);
+        NodeId localNodeId = clusterService.getLocalNode().id();
         ArrayNode deviceNodes = root.putArray("devices");
         monitorService.availableResourcesSync(localNodeId, CONTROL_MESSAGE).forEach(name -> {
             ObjectNode deviceNode = mapper().createObjectNode();
@@ -94,7 +91,10 @@
     @Produces(MediaType.APPLICATION_JSON)
     @Path("messages/{deviceId}")
     public Response controlMessageMetrics(@PathParam("deviceId") String deviceId) {
-
+        ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        ClusterService clusterService = get(ClusterService.class);
+        NodeId localNodeId = clusterService.getLocalNode().id();
         metricsStats(monitorService, localNodeId, CONTROL_MESSAGE_METRICS,
                 DeviceId.deviceId(deviceId), root);
 
@@ -111,7 +111,10 @@
     @Path("cpu_metrics")
     @Produces(MediaType.APPLICATION_JSON)
     public Response cpuMetrics() {
-
+        ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        ClusterService clusterService = get(ClusterService.class);
+        NodeId localNodeId = clusterService.getLocalNode().id();
         metricsStats(monitorService, localNodeId, CPU_METRICS, root);
         return ok(root).build();
     }
@@ -126,7 +129,10 @@
     @Path("memory_metrics")
     @Produces(MediaType.APPLICATION_JSON)
     public Response memoryMetrics() {
-
+        ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        ClusterService clusterService = get(ClusterService.class);
+        NodeId localNodeId = clusterService.getLocalNode().id();
         metricsStats(monitorService, localNodeId, MEMORY_METRICS, root);
         return ok(root).build();
     }
@@ -141,7 +147,10 @@
     @Path("disk_metrics")
     @Produces(MediaType.APPLICATION_JSON)
     public Response diskMetrics() {
-
+        ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        ClusterService clusterService = get(ClusterService.class);
+        NodeId localNodeId = clusterService.getLocalNode().id();
         ArrayNode diskNodes = root.putArray("disks");
         monitorService.availableResourcesSync(localNodeId, DISK).forEach(name -> {
             ObjectNode diskNode = mapper().createObjectNode();
@@ -167,7 +176,10 @@
     @Path("network_metrics")
     @Produces(MediaType.APPLICATION_JSON)
     public Response networkMetrics() {
-
+        ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        ClusterService clusterService = get(ClusterService.class);
+        NodeId localNodeId = clusterService.getLocalNode().id();
         ArrayNode networkNodes = root.putArray("networks");
         monitorService.availableResourcesSync(localNodeId, NETWORK).forEach(name -> {
             ObjectNode networkNode = mapper().createObjectNode();
diff --git a/apps/cpman/app/src/main/java/org/onosproject/cpman/rest/SystemMetricsCollectorWebResource.java b/apps/cpman/app/src/main/java/org/onosproject/cpman/rest/SystemMetricsCollectorWebResource.java
index 0fd18e0..60c8691 100644
--- a/apps/cpman/app/src/main/java/org/onosproject/cpman/rest/SystemMetricsCollectorWebResource.java
+++ b/apps/cpman/app/src/main/java/org/onosproject/cpman/rest/SystemMetricsCollectorWebResource.java
@@ -55,9 +55,6 @@
 public class SystemMetricsCollectorWebResource extends AbstractWebResource {
 
     private final Logger log = LoggerFactory.getLogger(getClass());
-    private final ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
-    private final MetricsService metricsService = get(MetricsService.class);
-
     private static final int UPDATE_INTERVAL_IN_MINUTE = 1;
     private static final String INVALID_SYSTEM_SPECS = "Invalid system specifications";
     private static final String INVALID_RESOURCE_NAME = "Invalid resource name";
@@ -89,6 +86,8 @@
     @Consumes(MediaType.APPLICATION_JSON)
     public Response cpuMetrics(InputStream stream) {
         ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        MetricsService metricsService = get(MetricsService.class);
         ControlMetric cm;
         try {
             ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
@@ -150,6 +149,8 @@
     @Consumes(MediaType.APPLICATION_JSON)
     public Response memoryMetrics(InputStream stream) {
         ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        MetricsService metricsService = get(MetricsService.class);
         ControlMetric cm;
         try {
             ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
@@ -205,6 +206,8 @@
     @Consumes(MediaType.APPLICATION_JSON)
     public Response diskMetrics(InputStream stream) {
         ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        MetricsService metricsService = get(MetricsService.class);
         ControlMetric cm;
         try {
             ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
@@ -251,6 +254,8 @@
     @Consumes(MediaType.APPLICATION_JSON)
     public Response networkMetrics(InputStream stream) {
         ObjectNode root = mapper().createObjectNode();
+        ControlPlaneMonitorService monitorService = get(ControlPlaneMonitorService.class);
+        MetricsService metricsService = get(MetricsService.class);
         ControlMetric cm;
         try {
             ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
diff --git a/web/api/src/main/java/org/onosproject/rest/resources/FlowsWebResource.java b/web/api/src/main/java/org/onosproject/rest/resources/FlowsWebResource.java
index f2ce22b..2f532ac 100644
--- a/web/api/src/main/java/org/onosproject/rest/resources/FlowsWebResource.java
+++ b/web/api/src/main/java/org/onosproject/rest/resources/FlowsWebResource.java
@@ -170,6 +170,7 @@
     @Consumes(MediaType.APPLICATION_JSON)
     @Produces(MediaType.APPLICATION_JSON)
     public Response createFlows(@QueryParam("appId") String appId, InputStream stream) {
+        FlowRuleService service = get(FlowRuleService.class);
         ObjectNode root = mapper().createObjectNode();
         ArrayNode flowsNode = root.putArray(FLOWS);
         try {
@@ -183,7 +184,7 @@
 
             List<FlowRule> rules = codec(FlowRule.class).decode(flowsArray, this);
 
-            get(FlowRuleService.class).applyFlowRules(rules.toArray(new FlowRule[rules.size()]));
+            service.applyFlowRules(rules.toArray(new FlowRule[rules.size()]));
             rules.forEach(flowRule -> {
                 ObjectNode flowNode = mapper().createObjectNode();
                 flowNode.put(DEVICE_ID, flowRule.deviceId().toString())
@@ -209,10 +210,11 @@
     // TODO: we need to add "/device" suffix to the path to differentiate with appId
     @Path("{deviceId}")
     public Response getFlowByDeviceId(@PathParam("deviceId") String deviceId) {
+        FlowRuleService service = get(FlowRuleService.class);
         ObjectNode root = mapper().createObjectNode();
         ArrayNode flowsNode = root.putArray(FLOWS);
         Iterable<FlowEntry> flowEntries =
-                get(FlowRuleService.class).getFlowEntries(DeviceId.deviceId(deviceId));
+                service.getFlowEntries(DeviceId.deviceId(deviceId));
 
         if (flowEntries == null || !flowEntries.iterator().hasNext()) {
             throw new ItemNotFoundException(DEVICE_NOT_FOUND);
@@ -237,10 +239,11 @@
     @Path("{deviceId}/{flowId}")
     public Response getFlowByDeviceIdAndFlowId(@PathParam("deviceId") String deviceId,
                                                @PathParam("flowId") long flowId) {
+        FlowRuleService service = get(FlowRuleService.class);
         ObjectNode root = mapper().createObjectNode();
         ArrayNode flowsNode = root.putArray(FLOWS);
         Iterable<FlowEntry> flowEntries =
-                get(FlowRuleService.class).getFlowEntries(DeviceId.deviceId(deviceId));
+                service.getFlowEntries(DeviceId.deviceId(deviceId));
 
         if (flowEntries == null || !flowEntries.iterator().hasNext()) {
             throw new ItemNotFoundException(DEVICE_NOT_FOUND);
@@ -287,9 +290,10 @@
     @Produces(MediaType.APPLICATION_JSON)
     @Path("application/{appId}")
     public Response removeFlowByAppId(@PathParam("appId") String appId) {
+        FlowRuleService service = get(FlowRuleService.class);
         ApplicationService appService = get(ApplicationService.class);
         ApplicationId idInstant = nullIsNotFound(appService.getId(appId), APP_ID_NOT_FOUND);
-        get(FlowRuleService.class).removeFlowRulesById(idInstant);
+        service.removeFlowRulesById(idInstant);
         return Response.noContent().build();
     }
 
@@ -313,6 +317,7 @@
     public Response createFlow(@PathParam("deviceId") String deviceId,
                                @QueryParam("appId") String appId,
                                InputStream stream) {
+        FlowRuleService service = get(FlowRuleService.class);
         try {
             ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
             JsonNode specifiedDeviceId = jsonTree.get("deviceId");
@@ -328,7 +333,7 @@
             }
 
             FlowRule rule = codec(FlowRule.class).decode(jsonTree, this);
-            get(FlowRuleService.class).applyFlowRules(rule);
+            service.applyFlowRules(rule);
             UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                     .path("flows")
                     .path(deviceId)
diff --git a/web/api/src/main/java/org/onosproject/rest/resources/GroupsWebResource.java b/web/api/src/main/java/org/onosproject/rest/resources/GroupsWebResource.java
index d2a361e..80eba7a 100644
--- a/web/api/src/main/java/org/onosproject/rest/resources/GroupsWebResource.java
+++ b/web/api/src/main/java/org/onosproject/rest/resources/GroupsWebResource.java
@@ -67,8 +67,6 @@
 
     private static final String DEVICE_INVALID = "Invalid deviceId in group creation request";
     private static final String GROUP_NOT_FOUND = "Group was not found";
-
-    private final GroupService groupService = get(GroupService.class);
     private final ObjectNode root = mapper().createObjectNode();
     private final ArrayNode groupsNode = root.putArray("groups");
 
@@ -89,6 +87,7 @@
     @GET
     @Produces(MediaType.APPLICATION_JSON)
     public Response getGroups() {
+        GroupService groupService = get(GroupService.class);
         final Iterable<Device> devices = get(DeviceService.class).getDevices();
         devices.forEach(device -> {
             final Iterable<Group> groups = groupService.getGroups(device.id());
@@ -111,6 +110,7 @@
     @Produces(MediaType.APPLICATION_JSON)
     @Path("{deviceId}")
     public Response getGroupsByDeviceId(@PathParam("deviceId") String deviceId) {
+        GroupService groupService = get(GroupService.class);
         final Iterable<Group> groups = groupService.getGroups(DeviceId.deviceId(deviceId));
 
         groups.forEach(group -> groupsNode.add(codec(Group.class).encode(group, this)));
@@ -131,6 +131,7 @@
     @Path("{deviceId}/{appCookie}")
     public Response getGroupByDeviceIdAndAppCookie(@PathParam("deviceId") String deviceId,
                                                    @PathParam("appCookie") String appCookie) {
+        GroupService groupService = get(GroupService.class);
         final DeviceId deviceIdInstance = DeviceId.deviceId(deviceId);
 
         final GroupKey appCookieInstance = createKey(appCookie);
@@ -158,6 +159,7 @@
     @Produces(MediaType.APPLICATION_JSON)
     public Response createGroup(@PathParam("deviceId") String deviceId,
                                 InputStream stream) {
+        GroupService groupService = get(GroupService.class);
         try {
 
             ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
@@ -196,6 +198,7 @@
     @Path("{deviceId}/{appCookie}")
     public Response deleteGroupByDeviceIdAndAppCookie(@PathParam("deviceId") String deviceId,
                                                       @PathParam("appCookie") String appCookie) {
+        GroupService groupService = get(GroupService.class);
         DeviceId deviceIdInstance = DeviceId.deviceId(deviceId);
 
         final GroupKey appCookieInstance = createKey(appCookie);
@@ -213,6 +216,7 @@
      */
     private void updateGroupBuckets(String deviceIdString, String appCookieString, InputStream stream)
                  throws IOException {
+        GroupService groupService = get(GroupService.class);
         DeviceId deviceId = DeviceId.deviceId(deviceIdString);
         final GroupKey groupKey = createKey(appCookieString);
 
@@ -273,6 +277,7 @@
     private void removeGroupBuckets(String deviceIdString, String appCookieString, String bucketIds) {
         DeviceId deviceId = DeviceId.deviceId(deviceIdString);
         final GroupKey groupKey = createKey(appCookieString);
+        GroupService groupService = get(GroupService.class);
 
         Group group = nullIsNotFound(groupService.getGroup(deviceId, groupKey), GROUP_NOT_FOUND);
 
diff --git a/web/api/src/main/java/org/onosproject/rest/resources/MastershipWebResource.java b/web/api/src/main/java/org/onosproject/rest/resources/MastershipWebResource.java
index cfd0f26..8b5484f 100644
--- a/web/api/src/main/java/org/onosproject/rest/resources/MastershipWebResource.java
+++ b/web/api/src/main/java/org/onosproject/rest/resources/MastershipWebResource.java
@@ -60,11 +60,6 @@
     private static final String ROLE_INFO_NOT_FOUND = "Role info is not found";
     private static final String MASTERSHIP_ROLE_NOT_FOUND = "Mastership role is not found";
 
-    private final DeviceService deviceService = get(DeviceService.class);
-    private final MastershipService mastershipService = get(MastershipService.class);
-    private final MastershipAdminService mastershipAdminService =
-                                         get(MastershipAdminService.class);
-
     /**
      * Returns the role of the local node for the specified device.
      *
@@ -76,6 +71,7 @@
     @Produces(MediaType.APPLICATION_JSON)
     @Path("{deviceId}/local")
     public Response getLocalRole(@PathParam("deviceId") String deviceId) {
+        MastershipService mastershipService = get(MastershipService.class);
         MastershipRole role = mastershipService.getLocalRole(DeviceId.deviceId(deviceId));
         ObjectNode root = codec(MastershipRole.class).encode(role, this);
         return ok(root).build();
@@ -92,6 +88,7 @@
     @Produces(MediaType.APPLICATION_JSON)
     @Path("{deviceId}/master")
     public Response getMasterFor(@PathParam("deviceId") String deviceId) {
+        MastershipService mastershipService = get(MastershipService.class);
         NodeId id = nullIsNotFound(mastershipService.getMasterFor(
                     DeviceId.deviceId(deviceId)), NODE_ID_NOT_FOUND);
 
@@ -112,6 +109,7 @@
     @Produces(MediaType.APPLICATION_JSON)
     @Path("{deviceId}/role")
     public Response getNodesFor(@PathParam("deviceId") String deviceId) {
+        MastershipService mastershipService = get(MastershipService.class);
         RoleInfo info = nullIsNotFound(mastershipService.getNodesFor(
                         DeviceId.deviceId(deviceId)), ROLE_INFO_NOT_FOUND);
         ObjectNode root = codec(RoleInfo.class).encode(info, this);
@@ -129,6 +127,7 @@
     @Produces(MediaType.APPLICATION_JSON)
     @Path("{nodeId}/device")
     public Response getDeviceOf(@PathParam("nodeId") String nodeId) {
+        MastershipService mastershipService = get(MastershipService.class);
         ObjectNode root = mapper().createObjectNode();
         ArrayNode devicesNode = root.putArray(DEVICE_IDS);
 
@@ -152,6 +151,8 @@
     @Produces(MediaType.APPLICATION_JSON)
     @Path("{deviceId}/request")
     public Response requestRoleFor(@PathParam("deviceId") String deviceId) {
+        MastershipService mastershipService = get(MastershipService.class);
+        DeviceService deviceService = get(DeviceService.class);
         DeviceId id = DeviceId.deviceId(deviceId);
         nullIsNotFound(deviceService.getDevice(id), DEVICE_ID_NOT_FOUND);
 
@@ -173,6 +174,7 @@
     @Produces(MediaType.APPLICATION_JSON)
     @Path("{deviceId}/relinquish")
     public Response relinquishMastership(@PathParam("deviceId") String deviceId) {
+        MastershipService mastershipService = get(MastershipService.class);
         DeviceId id = DeviceId.deviceId(deviceId);
         mastershipService.relinquishMastershipSync(id);
         return Response.created(id.uri()).build();
@@ -189,6 +191,7 @@
     @PUT
     @Consumes(MediaType.APPLICATION_JSON)
     public Response setRole(InputStream stream) {
+        MastershipAdminService mastershipAdminService = get(MastershipAdminService.class);
 
         try {
             ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
@@ -222,6 +225,7 @@
     @GET
     @Produces(MediaType.APPLICATION_JSON)
     public Response balanceRoles() {
+        MastershipAdminService mastershipAdminService = get(MastershipAdminService.class);
         mastershipAdminService.balanceRoles();
         return Response.ok().build();
     }